Your SlideShare is downloading. ×

Head first java_second_edition

2,547
views

Published on


0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,547
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
115
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. www.it-ebooks.info
  • 2. www.it-ebooks.infoTable of Contents (summary) Intro xxi 1 Breaking the Surface: a quick dip 1 2 A Trip to Objectville: yes, there will be objects 27 3 Know Your Variables: primitives and references 49 4 How Objects Behave: object state affects method behavior 71 5 Extra-Strength Methods: flow control, operations, and more 95 6 Using the Java Library: so you don’t have to write it all yourself 125 7 Better Living in Objectville: planning for the future 165 8 Serious Polymorphism: exploiting abstract classes and interfaces 197 9 Life and Death of an Object: constructors and memory management 235 10 Numbers Matter: math, formatting, wrappers, and statics 273 11 Risky Behavior: exception handling 315 12 A Very Graphic Story: intro to GUI, event handling, and inner classes 353 13 Work on Your Swing: layout managers and components 399 14 Saving Objects: serialization and I/O 429 15 Make a Connection: networking sockets and multithreading 471 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 A Appendix A: Final code kitchen 649 B Appendix B: Top Ten Things that didn’t make it into the rest of the book 659 Index 677Table of Contents (the full version)i Intro Your brain on Java. Who is this book for? xxii What your brain is thinking xxiii Metacognition xxv Bend your brain into submission xxvii What you need for this book xxviii Technical editors xxx Acknowledgements xxxi ix
  • 3. www.it-ebooks.info 1 Breaking the Surface Java takes you to new places. The way Java works 2 Virtual Code structure in Java 7 Machines Anatomy of a class 8 The main() method 9 Method Party() Looping 11 0 aload_0 Conditional branching (if tests) 13 1 invokespe- cial #1 <Method Coding the “99 bottles of beer” app 14 java.lang.Object()> Phrase-o-matic 16 4 return Fireside chat: compiler vs. JVM 18 Compiled You Bet Shoot Me Exercises and puzzles 20 bytecode 2 A Trip to Objectville I was told there would be objects. Chair Wars (Brad the OO guy vs. Larry the procedural guy) 28 Inheritance (an introduction) 31 Overriding methods (an introduction) 32 What’s in a class? (methods, instance variables) 34 Making your first object 36 Using main() 38 Guessing Game code 39 Exercises and puzzles 42x
  • 4. www.it-ebooks.info 3 Know Your Variables Variables come in two flavors: primitive and reference. Declaring a variable (Java cares about type) 50 24 size Primitive types (“I’d like a double with extra foam, please”) 51 Java keywords 53 int Reference variables (remote control to an object) 54 ct Object declaration and assignment 55 Dog obje Objects on the garbage-collectible heap 57 fido Arrays (a first look) 59 Exercises and puzzles 63 Dog reference 4 How Objects Behave State affects behavior, behavior affects state. Methods use object state (bark different) 73pass-by-value means Method arguments and return types 74pass-by-copy Pass-by-value (the variable is always copied) 77 Getters and Setters 79 copy of Encapsulation (do it or risk humiliation) 80 x Using references in an array 83 111 0 111 00 00 Exercises and puzzles 88 0 00 00 X Z int intfoo.go(x); void go(int z){ } xi
  • 5. www.it-ebooks.info 5 Extra-Strength Methods Let’s put some muscle in our methods. e a build th e’re gonnt Com game W Sink a Do Building the Sink a Dot Com game 96 Starting with the Simple Dot Com game (a simpler version) 98 Writing prepcode (pseudocode for the game) 100 Test code for Simple Dot Com 102 Coding the Simple Dot Com game 103 Final code for Simple Dot Com 106 Generating random numbers with Math.random() 111 Ready-bake code for getting user input from the command-line 112 Looping with for loops 114 Casting primitives from a large size to a smaller size 117 Converting a String to an int with Integer.parseInt() 117 Exercises and puzzles 118 6 Using the Java Library Java ships with hundreds of pre-built classes. Analying the bug in the Simple Dot Com Game 126 ArrayList (taking advantage of the Java API) 132 Fixing the DotCom class code 138 Building the real game (Sink a Dot Com) 140 - Julia, 31, hand model Prepcode for the real game 144 Code for the real game 146 boolean expressions 151 Using the library (Java API) 154 Using packages (import statements, fully-qualified names) 155 Using the HTML API docs and reference books 158 Exercises and puzzles 161xii
  • 6. www.it-ebooks.info 7 Better Living in Objectville Plan your programs with the future in mind. Understanding inheritance (superclass and subclass relationships) 168 Designing an inheritance tree (the Animal simulation) 170 Make it Stick Avoiding duplicate code (using inheritance) 171 Overriding methods 172 IS-A and HAS-A (bathtub girl) 177 What do you inherit from your superclass? 180 What does inheritance really buy you? 182 Polymorphism (using a supertype reference to a subclass object) 183 Rules for overriding (don’t touch those arguments and return types!) 190 Method overloading (nothing more than method name re-use) 191 Exercises and puzzles 192 8 Serious Polymorphism Inheritance is just the beginning. Some classes just should not be instantiated 200Object o = al.get(id); Abstract classes (can’t be instantiated) 201Dog d = (Dog) o; Abstract methods (must be implemented) 203d.bark(); Polymorphism in action 206 Class Object (the ultimate superclass of everything) 208 Object Taking 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 o objec Get in touch with your inner object 214 cast t Polymorphic references 215 back tohe Object Object Casting an object reference (moving lower on the inheritance tree) 216 d know is a Dog we there. Deadly Diamond of Death (multiple inheritance problem) 223 Dog Using interfaces (the best solution!) 224 Exercises and puzzles 230 xiii
  • 7. www.it-ebooks.info 9 Life and Death of an Object Objects are born and objects die. The stack and the heap, where objects and variables live 236 calls When someone od, this Methods on the stack 237 eth the go() m oned. His Where local variables live 238 Duck is aband has been only reference for a Where instance variables live 239 reprogrammed k. The miracle of object creation 240 Du ec differ ent Duc Constructors (the code that runs when you say new) 241 t ck obj Initializing the state of a new Duck 243 d Overloaded constructors 247 Du Heap Superclass constructors (constructor chaining) 250 ck objec t Invoking overloaded constructors using this() 256 ing the ‘d’ is assigned a new Duck object, leav . That Life of an object 258 original (first) Duck object abandoned Garbage Collection (and making objects eligible) 260 first Duck is toast.. Exercises and puzzles 266Static variablesare shared by 10 Numbers Matter Do the Math.all instances ofa class. static variable: iceCream Math class (do you really need an instance of it?) 274 kid instance twokid instance one static methods 275 instance variables: static variables 277 one per instance Constants (static final variables) 282 Math methods (random(), round(), abs(), etc.) 286 static variables: one per class Wrapper classes (Integer, Boolean, Character, etc.) 287 Autoboxing 289 Number formatting 294 Date formatting and manipulation 301 Static imports 307 Exercises and puzzles 310xiv
  • 8. www.it-ebooks.info 11 Risky Behavior Stuff happens. Making a music machine (the BeatBox) 316 What if you need to call risky code? 319 an excepti ows on hr 2 ba Exceptions say “something bad may have happened...” 320 ck t The compiler guarantees (it checks) that you’re aware of the risks 321 class 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 blocks 326 } int stuff() { } x.beep(); } } calls risky method The finally block (no matter what happens, turn off the oven!) 327 Catching multiple exceptions (the order matters) 329 your code class with a risky method Declaring an exception (just duck it) 335 Handle or declare law 337 Code Kitchen (making sounds) 339 Exercises and puzzles 348 12 A Very Graphic Story Face it, you need to make GUIs. class MyOuter { class MyInner { void go() { Your first GUI 355 } Getting a user event 357 } Implement a listener interface 358 } Getting a button’s ActionEvent 360 Putting graphics on a GUI 363The outer and inner objectsare now intimately linked. Fun with paintComponent() 365 oute r The Graphics2D object 366 Putting more than one button on a screen 370 objects on the These two a special bond. The inner Inner classes to the rescue (make your listener an inner class) 376 heap have use the outer’s inner can (and vice-versa). Animation (move it, paint it, move it, paint it, move it, paint it...) 382 variables Code Kitchen (painting graphics with the beat of the music) 386 Exercises and puzzles 394 xv
  • 9. www.it-ebooks.info 13 Work on your Swing Swing is easy. Swing Components 400Components in Layout Managers (they control size and placement) 401the east and Three Layout Managers (border, flow, box) 403west get theirth. BorderLayout (cares about five regions) 404 preferred wid FlowLayout (cares about the order and preferred size) 408Things in the BoxLayout (like flow, but can stack components vertically) 411north and The center gets JTextField (for single-line user input) 413south get their whatever’s 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 424 14 Saving Objects Objects can be flattened and inflated. serialized Saving object state 431 Writing a serialized object to a file 432 Java input and output streams (connections and chains) 433 Object serialization 434 ions? Any quest Implementing the Serializable interface Using transient variables 437 439 deserialized Deserializing an object 441 Writing to a text file 447 java.io.File 452 Reading from a text file 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 00 Chat program overview 473196.164.1.10er at Connecting, sending, and receiving 474 3 Network sockets 475 TCP ports 476 Reading data from a socket (using BufferedReader) 478 Writing data to a socket (using PrintWriter) 479 Client Server nnection Writing the Daily Advice Client program 480 Socket oco he client t Writing a simple server 483 back t 64.1.100, at 196.1242 Daily Advice Server code 484 port 4 Writing a chat client 486 Multiple call stacks 490 Launching a new thread (make it, start it) 492 The Runnable interface (the thread’s job) 494 Three states of a new Thread object (new, runnable, running) 495 The runnable-running loop 496 Thread scheduler (it’s 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 code 506 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.info 16 Data Structures Sorting is a snap in Java. Collections 533 Sorting an ArrayList with Collections.sort() 534 List 0 1 2 3 Generics and type-safety 540 Sorting things that implement the Comparable interface 547 Sorting things with a custom Comparator 552 The collection API—lists, sets, and maps 557 Set Avoiding duplicates with HashSet 559 Overriding hashCode() and equals() 560 HashMap 567 Using wildcards for polymorphism 574 Map “Ball” “Ball1” “Ball2” “Fish”“Car” “Fish” “Car” Exercises and puzzles 576 17 Release Your Code It’s time to let go. classes Deployment options 582 com Keep your source code and class files separate 584 101101 foo 10 110 1 0 11 0 Making an executable JAR (Java ARchives) 585 MyApp.jar 001 10 001 01 Running an executable JAR 586 MyApp.class Put your classes in a package! 587 Packages must have a matching directory structure 589 Web Server Compiling and running with packages 590 JWS Lorper iure Compiling with -d 591 eugue tat vero conse euguero- Making an executable JAR (with packages) 592 MyApp.jar MyApp.jnlp MyApp.jar Java Web Start (JWS) for deployment from the web 597 How to make and deploy a JWS application 600 Exercises and puzzles 601xviii
  • 12. www.it-ebooks.info 18 Distributed Computing Being remote doesn’t have to be a bad thing. Client Server Java Remote Method Invocation (RMI), hands-on, very detailed 614 Servlets (a quick look) 625 RMI STUB RMI SKELETON Enterprise JavaBeans (EJB), a very quick look 631 Jini, the best trick of all 632 Se e r C li ent helper rvice help Se rvice objec tC li Building the really cool universal service browser 636 ent object The End 648 A Appendix A The final Code Kitchen project. BeatBoxFinal (client code) 650 MusicServer (server code) 657 B Appendix B The Top Ten Things that didn’t make it into the book. Top Ten List 660 i Index 677 xix
  • 13. www.it-ebooks.infohow to use thOIS book Intro -the bl>Yli,,~ ,~tiOf: DID :h<1 f.t Wl ,•• J••• ""~,.~-;~ boo<r" IY -this stl.bOfI Wt. .lYlSHt:Y So, whY xxi
  • 14. www.it-ebooks.infohow to use this bookWho is this book for? If you can answer "yes" to all of these: This is NOT a reference E!)" Have you done some programming? book. Head First Java is a book designed for earning, ® Do you want to learn Java? not an encyclopedia of Java facts. ® Do you prefer stimulating dinner party conversation to dry, dull, technical lectures? this book is for you.Who should probably back away frotH this book? If you can answer "yes" to anyone of these: Is your programming background limited to HTML only, with no scripting language experience? (If youve don e anything with looping, or if/then logic , you ll do fine with this book, but HTML tagging alone might not be enough.) ® Are you a kick-butt C++ programmer looking for a reference book? ® Are youyou rather try something different? Would afraid to have a root canal than I mix stripes with plaid? Do you believe than a technical book cant be serious If theres a picture of a duck in the memory management section? this book is not for you .xxii intr o
  • 15. www.it-ebooks.info the intraWe k.,ow what you"re thittkhtg."How can this be a seriousJava programming book?""Whats with all the graphics?""Can I actually learn it this way?""Do I smell pizza?"A.,d we kt10w what your brain is thittkittg.Your brain craves novelty. Its always searching, scanning, waiting forsomething unusual. It was built that way, and it helps you stay alive.Today, youre less likely to be a tiger snack. But your brain s stilllooking. You just never know.So what does your brain do with all the routine, ordinary, normalthings you encounter? Everything it can to stop them frominterfering with the brains realjotr-recording things that matter. Itdoesnt bother saving the boring things; they never make it past the"th is is obviously not important" filter.How does your brain know whats important? Suppose youre out fora day hike and a tigerjumps in front of you , what happens inside yourhead?Neurons fire. Emotions crank up. Chemicals suWAnd thats how your brain knows ...This must be Importantl Dont forget ItIBut imagine youre at home, or in a library. Its a safe, warm, tiger-freezone. Youre studying. Getting ready for an exam. Or trying to learnsome tough technical topic your boss thinks will take a week, ten daysat the most,Just one problem. Your brains trying to do you a big favor. It strying to make sure that this obviou.sly non-important contentdoesnt clutter up scarce resources. Resources that are betterspent storing the really bigthings. Like tigers. Like the danger offire. Like how you should never again snowboard in shorts.And theres no simple way to tell your brain, "Hey brain, thankyou very much, but no matter how dull this book is. and howlittle Im registering on the emotional richter scale right now, Ireally do want you to keep this stuff around. h you are he re ~ xxiII
  • 16. www.it-ebooks.info how to use this book We tlUn1 of a "!lead FllSt Java" reader as a learner. - So what does It take to learn something? First, you have to get It, then make sure you dont forgetll Its not about pushing facts Into your head. Based on the latest research In cognltJve science, neurobiology, and educatJonal psychology, learning takes a lot more than text on a page . We know what turns your brain on. Soma of the Head First learning principles: Make It visual. Images are far more memorable than words RMI"(loo~ ~ite alone, and make learning much more effective (Up to 89% Improvement in recall and transfer studies) . It also makes things more understandable. Put the words within or near the graphics they relate to, rather than on the bottom or on another page, and learners will be up to twice as likely to solve problems related to the content. Use a conversational and personalized style,In recent studies, students performed up to 40% better on post-learning tests if the content spoke It re4l1y SlJcks to ~ <III Qbstl"<lct m~tkod. You directly to the reader, using a flrst-person, conversational style rather than dont heve Q body. taking a formal tone.Tell stories instead of lecturing. Use casual language. Dont take yourself too seriously. Which would you pay more attention to: a stimulating o dinner party companion, or a lecture? o Get the learner to think more deeply. In other words, unless you actively flex your neurons, nothing much happens in your head. A reader has to be motivated, engaged, curious, and inspired to solve problems, draw conclusions, and generate new knowledge. And for that, you need challenges, exercises, and thought- ~0llll10 ; provoking questions, and actlvlties that involve both sides of the brain, and multiple senses. ~,-.A l>o41· ,~ t tl4~i- ~ ;Ie. Oet-and kee,,-,he readers attention. Weve all had the" really want to learn this but I cant stay awake past page one" experience. Your brain pays arrentlon to things that are out of the ordinary, interesting, strange, eye-catching, unexpected. Learning a new, tough, technical topic doesnt have to be boring. Your brain will learn much more qUicklyjf its not. Touch their emotlon8. We now know that your ability to remember something Is largely dependent on Its emotional content. You remember what you care about. You remember when you feel somethIng. No were not talking heart-wrenching stories about a boy and hIs dog . Were talking emotions like surprise, curiosity, fun, "what the ...T", and the feeling of "I Rulel" that comes when you solve a puzzle, learn something everybody else thinks Is hard, or realize you know something that ·"m more technical than thou Bob from engineering doe$nt.XXiv in t ra
  • 17. www.it-ebooks.info the introMetacogtlitiott: thittkittg about thittki"Q.If you really want to learn, and you want to learn more quickly and more deeply,pay attention to how you pay attention. Think about how you think, Learn howyou learn.Most of us did not take courses on metacognition or learning theory when we weregrowing up. We were expected to learn, but rarely taught to learn. o oBut we assume that if youre holding this book, you want to learn Java. And youprobably dont want to spend a lot of time.To get the most from this book, or any book or learning experience, takeresponsibility for your brain. Your brain 00 thai content.The trick is to get your brain to see the new material youre learningas Really Important. Crucial to your well-being. As important asa tiger. Otherwise, youre in for a constant battle, with your braindoing its best to keep tile new content from sticking.So Just how DO you get your brain to treat Java like Itwas a hungry tiger?Theres the slow, tedious way, or the faster, more effective way. Theslow way is about sheer repetition. You obviously know that you areable to learn and remember even the dullest of topics, if you keep poundingon the same thing. With enough repetition, your brain says, "This doesntfeelimportant to him, but he keeps looking at the same thing overand over and over, soI suppose it must be."The faster way is to do anything that increases brain activity, especially different typesof brain activity. The things on the previous page are a big part of the solution,and theyre all things that have been proven to help your brain work in your favor.For example, studies show that putting words within the pictures they describe (asopposed to somewhere else in the page, like a caption or in the body text) causesyour brain to try to makes sense of how the words and picture relate, and thiscauses more neurons to fire. More neurons firing = more chances for your brainto get that this is something worth paying attention to, and possibly recording.A conversational style helps because people tend to pay more attention when theyperceive that theyre in a conversation, since theyre expected to follow along andhold up their end. The amazing thing is, your brain doesnt necessarily care thatthe "conversation" is between you and a book! On the other hand, if the writingstyle is formal and dry, your brain perceives it the same way you experience beinglectured to while sitting in a roomful of passive attendees. No need to stay awake.But pictures and conversational style are just the beginning. you are here ~ xxv
  • 18. www.it-ebooks.infohow to use this bookHere"s what WE did:We used pidures, because your brain is tuned for visuals, not text As fur as yourbrains concerned, a picture really ssworth 1024 words. And when text and pictureswork together, we embedded the text in the pictures because your brain worksmore effectively when the text is wiihin the thing the text refers to, as opposed to ina caption or buried in the text somewhere.We used repetitUm, saying the same thing in different ways and with different mediatypes, and multiplesenses, to increase the chance that the content gets coded codedinto more than one area of your brain.We used concepts and pictures in ~ways because your brain is tuned fornovelty, and we used pictures and ideas with at least SO1M emf>tional content, becauseyour brain is tuned to pay attention to thebiochemlstry of emotions. That whichcauses you to feel something is more likely to be remembered. even if that feeling isnothing more than a little humor; SU1"f1rise, or interest.We used a personalized, conversational style, because your brain is tuned to pay moreattention when it believes you re in a conversation than if it thinks youre passivelylistening to a presentation. Your brain does this even when youre reading.We included more than 50 ~ , because your brain is tuned to learn andremember more when you do things than when you readabout things. And wemade the exercises challenging-yet-do-able, because thats what most pet1J/.e prefer.We used multiple learning styles, because you might prefer step-by-step procedures,while someone else wants to understand the big picture first, while someone elsejust wants to see a code example. But regardless of your own learning preference,everyone benefits from seeing the same content represented in multiple ways.We include content for both rides ofyour brain; because the more of your brain youengage, the more likely you are to learn and remember, and the longer you canstay focused. Since working one side of the brain often means giving the other sidea chance to rest, you can be more productive at learning for a longer period oftime.And we included storie: and exercises that present JTUWe than one point ofview, ~8"Barlle"because your brain is tuned to learn more deeply when its forced to makeevaluations and judgements.We included chaIknges, with exercises, and by asking qrustions that dont always havea straight answer, because your brain is tuned to learn and remember when it hasto work at something (just as you cant get your body in shape by watching peopleat the gym). But we did our best to make sure that when youre working hard, itson the right things: That yourenot spending one exITa denLfrile processing a hard-to-understand example, or parsing difficult,jargon-Iaden, or extremely terse text.We used an 80/20 approach. We assume that if you re going for a PhD in java,this wont be your only book. So we dont talk about everything. Just the stuff youllactually use.xxvi Intra
  • 19. www.it-ebooks.info the intra Herels what YOU ca., do to be.,d your brah1 i"to subltdssiot1. So, we did our part. The rest is up to you . These tips are a starting point; Listen to your brain and figure out what works for you and what doesnt. Try new things. lki. -this OUt dhd sf.itk t Oh yOlJ.r l"e+l"id9tt"ak .I. _ - - _ . _ - - - - - - - - - - -~ ----------------------------------------------------------- ~ . Slow down. The more you understand, the less you have to memorize. Dont just read. Stop and think. When the book asks you a question, dont just skip to • Drink water. Lots of It. Your brain works best in a nice bath of fluid. Dehydration (which can happen before you ever feel thirsty) decreases cognitive function. • the answer. Imagine that someone really is asking the question. The more deeply you Talk about It. Out loud. force your brain to think, the better chance Speaking activates a different part of you have of learning and remembering. the brain. If youre trying to understand something, or increase your chance of Do the exercises. Write your own notes. remembering it later, say it out loud. Better We put them in, but if we did them for you, still, try to explain it out loud to someone that would be like having someone else else . Youll learn more quickly, and you might do your workouts for you . And dont just uncover ideas you hadnt known were there look at the exercises. Use a pencil. Theres when you were reading about it. plenty of evidence that physical activity while learning can increase the learning. Listen to your brain. Pay attention to whether your brain is getting Read the "There are No Dumb Questions" overloaded. If you find yourself starting to ski m That means all of them. Theyre not the surface or forget what you just read, its optional side-bars-theyre part of the core time for a break. Once you go past a certain contentl Sometimes the questions are more point, you wont learn faster by trying to shove useful than the answers. more in, and you might even hurt the process. Dont do all your reading In one place. • Feel somethlngl Stand-up, stretch, move around . change Your brain needs to know that this mauers. Get chairs, change rooms. Itll help your brain involved with the stories. Make up your 0>11 feel 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 you Part of the learning (especially the transfer can experiment with changing and improving to long-term memory) happens afleryou put the code (or breaking it, which is sometimes the book down. Your brain needs time on the best way to figure alit whats really its own , to do more processing. If you put in happening). For long examples or Ready-bake something new during that processing-time, code, you can download the source files from some 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 mar1<eting reasons, shortly before release, Sun renamed It Java 5, while still keeping "1 .5" asthe version number forthe developers kit So, if you see Java 1.5 orJava 5 orJava 5.0, or "Tiger" (version 5s original code-name), they all mean the same thing. There was never a Java 3.0 or 4.Q--it jumped from version 1.4 to5.0,bu1 you will still find places where itscalled 1.5 instead of 5. Donl ask. (Oh, and just 10 make il more entertaining, Java 5 and the Mac OS X 10.4 were both given the same code-name of"Tiger", and since OS X 10.4 is the version of the Mac OS you need to run Java 5, voullhear people talk about "Tiger on TIger". II justmeans Java 5 on OS X 10.4). • The SDK does not include the API documentatIon, and you need that! Go back tojava.sun. com and get the J2SE APr documentation. You can also access the API docs online, without downloading them, but thaIs apain. Trusl us, irs worth the download. • You need a texteditor. Virtually any text editor will do (vi, emacs, pica), including the GUI ones that come with most operating systems. Nolepad, Wordpad, TextEdlt, etc. allwork, aslong as you make sure they donl append a ".txt" on tothe end of your source code. • Once youve downloaded and unpackedfzippedfwhatever (depends on which version and for which OS). you need to add an entry toyour PATH environment variable that points tothe fbln directory inside the main Java directory. For example, if the J2SDK puts a directory on your drive called "j2sdk1.5,O, look inside that directory and youlI find the "bin" directory where the Java binaries (the tools) live. The bin directory is the one you need a PATH to, sothaI when you type: % javac atthe command-line, your terminal will know how tofind the javac compiler. Note: if you have trouble with you installation, we recommend you gotojavaranch.com, and join the Java-Beginning forum! Actually, you should dothat whether you have trouble or not. Nole: much of the code from this book Is available at wlckedlysmart.comxxvlll intra
  • 21. www.it-ebooks.info the introLast.. tMinute thhtgs you need to know:This is a learning experience, not a reference book. We deliberatelystripped out everything that might get in the way of lmrningwhatever itis were working on at that point in the book. And the first time through,you need to begin at the beginning, because the book makes assumptionsabout what youve already seen and Learned.We use simple UML.-IIke diagrams. DogIfwed used pure UML, youd be seeing something that looks like Java , butwith syntax thats just plain 1UTfYflf;. So we use a simplified version ofUML sizethat doesnt conflict with Java syntax. If you dont already know UML. youwont have to worry about leamingJava and UML at the same time. barkQ eatO chaseCatQWe dont worry about organizing and packaging your owncode until the end of the book.In this book, you can get on with the business of learningJava , without -stressing over some of the organizational or administrative details ofdeveLopingJava programs. You will, in the real world, need to know-anduse--these details, so we cover them in depth. But we save them for the endof the book (chapter 17) . Relax while you ease intoJava, gently.The end-of-chapter exercises are mandatory; puzzles areoptional. Answers for both are at the end of each chapter.One thing you need to know about the puzzles-tmy re puxxles. As in Logicpuzzles, brain teasers, crossword puzzles, etc. The exercises are here to help}ou practice what youve learned, and you should do them all. The puzzlesare a different story, and some of them are quite challenging in a puzzleway. These puzzles are meant for pualets, and you probably already know ifyou are one. If youre not sure, we suggest you give some of them a try, butwhatever happens, dont be discouraged if you cant solve a puzzle or if yousimply cant be bothered to take the time to work them out.The Sharpen Your Pencil exercises dont have answers.Not printed in the book, anyway. For some of them, there is no rightanswer, and for the others, part of the learning experience for the Sharpenactivities is for you to decide if and when your answers are right, (Some ofour suggested answers are available on wickedlysman.com)The code examples are as lean as possibleIts frustrating to wade through 200 lines of code looking for the two linesyou need to understand. Most examples in this book are shown within thesmallest possible context, so that the part youre trying to learn is clear andsimple. So dont expect the code to be robust, or even complete. ThatsJour assignment for after you finish the book. The book examples arewritten specifically for learning, and arent always fully-functional. you are here ~ xxix
  • 22. www.it-ebooks.infotech editing: Jessica and Valentinfecht-tical Editors "Credit goes to all, but mistakes are the sale reponsibility of theauthor...", Does anyone really believe that? See the two people onthis page? If you find technical problems, its probably theirfaulL : ) Vjjellt,i,,s ·be Valentin Valentin Creuaz has a Masters degree in Information and Computer Science from Jess works at Hewlett-Packard on the Self- the Swiss Federal Institute of Technology in Healing Services Team. She has a Bachelors Lausanne (EPFL). He has worked as a software in Computer Engineering from Villanova engineer with SRI International (Menlo Park, University, has her SCPJ 1.4 and SCWCD CA) and as a principal engineer in the Software certifications, and is literally months away Engineering Laboratory of EPFL. from receiving her Masters in Software Valentin is the co-founder and CTO of Condris Engineering at Drexel University (whewl) Technologies, a company specializing in the When shes not working, studying or development of software architecture solutions. motoring in her MINI Cooper S,jess can His research and development interests be found fighting her cat for yam as she include aspect-oriented technologies, design completes her latest knitting or crochet and architectural patterns, web services, and project (anybody want a hat?) She is software architecture. Besides taking care of originally from Salt Lake City, Utah (no, his wife. gardening, reading. and doing some shes not Mormon ... yes, you were too sport, Valentin moderates the SCBCD and going to ask) and is currently living near SCDJWS forums atJavaranch.com . He holds Philadelphia with her husband. Mendra, and the SCJP, SCjD, SCBCD, scwco, and SCD]WS two cats: Chai and Sake. certifications. He has also bad the opporruniry You can catch her moderating technical to serve as a co-author for Whizlabs SCBCD forums acjavaranch.com. Exam Simulator. (Were still in shock from seeing him in a tie.)XXX intra
  • 23. www.it-ebooks.info the in tra t"~ditOther people to b~e: $OfrIe ~ 0".... Java !)I.~t .... t . . !vi~e ....s...•41 OReilly: Our biggest thanks to Mike Loukides at OReilly, for taking a chance on this , and helping to shape the Head First concept into a book (and series) . As this second edition goes to print there are now five Head First books, and hes been with us all the way. To Tim OReilly, for his willingness 10 launch into something completely new and different. Thanks to the clever Kyle Hart for figuring out how Head First fits into the world, and for launching the series . Finally, to Edie Freedman for designing the H ead First"emphasize the head" cover.Our intrepid beta testers and reviewer team:Our top honors and thanks go to the director of our javaranchtech review team.johannes deJong. This is your fifth time aroundwith us on a Head First book, and were thrilled youre still speakingto us, Jeff Cumps is on his third book with us now and relentlessabout finding areas where we needed to be more clear or correct.Corey McGlone, you rock. And we think you give the clearestexplanations on javaranch, Youll probably notice we stole one ortwo of them. Jason Menard saved our technical butts on morethan a few details, and Thomas Paul, as always, g-ave us expertfeedback and found the subtle Java issues the rest of us missed.Jane Griscti has herJava chops (and knows a thing or two about",-riting) and it was great to have her helping on the new editionalong with long-timejavarancher Barry Gaunt:farilyn de Queiroz gave us excellent help on both editions of thebook. Chris Jones,Jobn Nyquist, James Cubeta, Terri Cubeta,and Ira Becker gave us a ton of help on the first edition.Special thanks to a few of the Head First ers whove been helpingus from the beginning: Angelo Celeste, Mikalai Zaikin, andThomas Duff (twduff.corn). And thanks to our terrific agent, DavidRoge1berg of StudioB (but seriously, what about the movie rights?) you are here ~ xxxi
  • 24. www.it-ebooks.info" still more acknowledgements Just whet1 you thought there wouldt1t be at1Y tMore ackt1owledgetMet1ts*. MoreJava technical experts woo helped out on the first edition (in pseudo-random order): Emiko Hori, Michael Taupitz, Mike Gallihugh, Manish Hatwalne,James Chegwidden, Shweta Mathur, Mohamed Mazahim,John Paverd,Joseph Bih, Skulrat Patanavanich, Sunil Palicha, Suddhasatwa Ghosh, Ramki Srinivasan, Alfred Raouf, Angelo Celeste, Mikalai Zaikin,John Zoetebier,Jim Pleger, Barry Gaunt, and Mark Dielen. The first edition puzzle team: Dirk Schreckmann, Mary JavaCross Champion" Leners, Rodney J. Woodruff, Gavin Bong, and Jason Menard. Javaranch is lucky to have you all helping out. Other co-conspirators to thank: Paul Wheaton, the javaranch Trail Boss for supporting thousands ofJava learners. Solveig Haugland, mistress ofJ2EE and author of "Dating Design Patterns". Authors Don Smith and Tom Negrino (backupbrain.com) , for helping us navigate the tech book world. Our Head First partners in crime, Eric Freeman and Beth Freeman (authors of Head First Design Patterns) , for giving us the Bawls" to finish this on time. Sherry Dorris, for the things that really matter. Brave Early Adopters of the Head First series: Joe Litton, Ross P. Goldberg, Dominic Da Silva, honestpuck, Danny Bromberg, Stephen Lepp, Elton Hughes, Eric Christensen, Vulinh Nguyen, Mark Rau, Abdulhaf, Nathan Oliphant, Michael Bradly, Alex Darrow, Michael Fischer, Sarah Nottingham, Tim Allen, Bob Thomas, and Mike Bibby (the first). "The large number of acknOWledgements is because were testing the theory that everyone mentioned in a book acknowledgement will bUy at least one copy, probably more , what with relatives and everyth ing. If youd like to be in the acknowledgement of our next book, and you have a large family, write to us. xxxii intro
  • 25. www.it-ebooks.info1 dive in A Quick Dip Breaking the Surface Come on, the waters great! Well dive right in and write some code, then compile and run it. Were talking syntax, looping and branching, and a look at what makes J alia so cool. Youll be coding in no time. Java takes you to new places. From its humble release to the public as the (wimpy) version 1.02,Java seduced programmers with Its friendly syntax, object-orlented features, memory management, and best of aU-the promise of portability. The lure of wrlte-once/run- anywhere Isjust too strong. A devoted followlnq exploded, as programmers fought against bugs, limitations, and, on yeah, the fact that it was dog slow. But that was ages ago. If youre just starting in Java, youre lucky. Some of us had to walk five miles in the snow, uphill both ways (barefoot), to get even the most trivial applet to work. But you, why,yov get to ride the sleeker, faster. much more powerful Javaof today. .....".--..•. this is a new chapter 1
  • 26. www.it-ebooks.infothe way Java worksfhe Way Java Works The goal Is to write one application (in this example, an interactive party Invitation) and have It work on whatever device your friends have. source code (or Method Pany() Oalo;l<-O the Interactive 1 invobspe- party hwltaUon. ----.. clal #1 <Method java.lang.Obf&dO> 4 rerum Source Output (code) oCreate a source COIMpiler Virtual Machhudocument. 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 complier Any device capable of checks for errors and running Java will be able a physical Java Machine, wont let you compile to Interpret/translate but they all have a until Its satisfied that this file into something virtual 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.info dive 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 <Method pc.;b!ic void bu~dlnvlte() ( Java,lang.ObjedO> PartY at Tims1 Fl3me r=IlllW FtameO; 4 return Labell =new LabellParty atTlms1; B tton b =new ButIoII(You ber) ; Method void bulidInviteO Button C =te« Button("Shool me): onew #2 <Class java.aWl.Frame> Panel p =new PanelO; Virtual p.addO): 3 dup } II more code here... 4 Invokespec1al #J <Method MachlttU) Source Java.aWl.FrameQ> o o Output (code) Run the program by starting the Java Virtual Machine (JVM) with the Party.doss file. The JVM Type your source code. translates the bytecode into something the Saveas: Party.Java underlying platform Complied code: Party.dass understands, and runs your program . (NoU: U,is is ~ ....e.l"t to be d h-kial... 101<11 bt OI"H:i~ Yedl tilde ill a ....OIOOt, bl.t .f~ MW, ole jll1t wa,,-t: fOJ. U> ~tt d .fccl .f~ how it all .fib ~etkcYJ you are here ~ 3
  • 28. www.it-ebooks.info Avery brief history of Java ~ 3500 I! ~ 3000 ! lIlI "a 2500 c S lill 2000 ~ ., > CII 1500 .. G) .z:. .5 1000 1ft G) 500 1ft 1ft lIlI 0 U Java 1.02 Java 2 Java 5.0 250 classes 500 classes (wnloKs 1.2 .. t~) (wrsloKs 1.5 attd up) Slow. A little faster. 2300dasses 3500 classes Cute name and logo. More capable, friendlier. Much faster. More power, ~/e, to Fun 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 a the Big Thing. powerful. Comes in three thousand additional classes, flavors: Micro Edition (J2ME), Java 5.0 (known as"Tiger")~> Standard Edition (J2SE) and added major changes to ....«l -~ Enterprise Edition (J2EE). the language itself, making 2 a.0 Becomes the langutlge of it easier (at least in theory) III s:~ chola for new enterprise for programmers and giving o.s01 (especially web-based) and mobile applications. it new features that were popular in other languages.:c ~
  • 29. www.it-ebooks.info dive 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 name sequence woul d be ·3: but caIIing Java 1.5 Java 3 seemed more confusing, so they decided to name It Java 5.0 to : The joys of marketing... when the version of Java match 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 official rna 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 though 1.4 were "Java 2~ And beginning with version 1.5, Java is actual version of Java was 1.2. But versions 1.3 and 1.4 called "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 decided idea what will happen with the next release... you are here ~ 5
  • 30. www.it-ebooks.info .why Java Is cool pen your pencil answers Dont wotry about whether you understand any ofthis yeti look how easy It Everything here Is explained in great detall!n the book, most Is towrite Java. within the first 40 pages).If Java resembles a language youve used in the past, some of th is will be simple. If not, dont worry about it. Wellget there... int size::; 27; String name = #FidoHj dett.rt ~ ~~ of l~,)lW1"aridbl, Nlr.ed ~ ..c ~r.d ~i" it ~ ."Iot "Fido Dog myDog ::; new Dog (name, size); du.lm .1 _ D~ v~blc ..yD~ a.v:l ~U ~ _ D~ 1Iii~ (~ ..rod siu x = 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<Jd &-y Md~Y th~ .. catch(FileNotFoundException ex) { this ~ be wkrt Oil fi,.o Nt ~ u.e tho h-led did,,i warle._ System.out.print(HFile not found."); ~ !he I:.hi~ u-ied t~iled , rri"t "Fil, root fOllNl" out at the ~-liM Ill( } locks li~ t"Icryl:.hi~ i" the { } is wlIat to do ~ the fry did,,t ~ ...6 chapter 1
  • 31. www.it-ebooks.info dive In A Quick DipCode structure i., Java public class Dog { What goes in a source file? A source code file (with the .java extension) holds one class defini- tion. The class represents a piece of your program, although a very tiny application might need just a single class. The class must go within a pair of curly braces. class Put a class in a source file. What goes in a public class Dog { class? void bark () { Put methods in a class. A class has one or more methods. In the Dog class, the bark method Put statements In a method. will hold instructions for how the Dog should bark. Your methods must be declared inside a class (in other words, within the curly braces of the class). tttefho~ public class Dog l What goes In a method? void bark () { s ta temen tl ; Within the curly braces of a method, write your instructions statemen t2 ; for how that method should be performed. Method code is basi- cally a set of statements, and for } now you can think of a method sfafetttet1fs kind of like a function or proce- dure. you ar e here • 7
  • 32. www.it-ebooks.infoa Java classAttafottty of aclassWhen thejVM starts running, it looks for the class you give it at the com-mand line. Then it starts looking for a specially-Written method that looksexactly like: public static void main (String() argsl ( II your code goes hereNext, theJVM runs everything between the curly braces { }of your mainmethod. EveryJava application has to have at least one class. and at leastone main method (not one main per class;just one main per applU:ation). DOIli warry aW ",e"Oriz.j..~ a..yt.hiIl9 "i~ht lIOW ... this tholfW" is }st to ~d yCJ. sta....ud.8 chapter 1
  • 33. www.it-ebooks.info dive In A Quick DipWriti"Q aclass with amainInJava, everything goes in a class. Youll type your source code file (with a.java extension), then compile it into a new class file (with a . class extension).When you run your program, youre really running a class.Running a program means telling the Java VIrtual Machine (JVM) to "Load theHello class, then start executing its main () method. Keep running til all thecode in main is finished."In chapter 2. we go deeper into the whole class thing, but for now, all you need tothink is, how cUJ 1 writeJava code $0 that it will run 1 And it all begins with mainf).The mamO method is where your program starts running.No matter how big your program is (in other words, no matter how many classesyour program uses), theres got to be a mainO method to get the ball rolling. public class MyFirst.Aflp ( o Save MyFirstApp. java public static void main (strinq[] arqs) Systall.out.priJ)t1n("I Ma!H); System. out . println (l.be World") ; ) o Compile javac MyFirstApp.java -,,~MyFlrstApp.Java 4t..~~ E)Run ~ t %j a va MyFirstApp I Rule! The WorldMyFlratApp.clau - you are here ~ 9
  • 34. www.it-ebooks.infostatements, looping, branchingWhat ca., you say I., the",al., ",ethod1Once you re inside main (or any method), the funbegins. You can say all the normal things that you sayin most programming languages to make the computerdo something.Your code can tell the JVM to : o do solttethi.,g Statements: declaratlons, assignments. method calls.etc, int x ~ 3; String name = ~Dirk"; x = x * 17; System .ouc .print("x is " + x); double d = Math.random(); II this is a comment Syntax Fun e do solttethlttQ agal., and agal" Loops: (or and while while (x > 12) x = )( - 1; .. Each statement must end in a semicolon. 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 begins with two forward slashes. e do solttethlttQ uttder this CO.,dltlon Branching: If/else tests x = 22; II this line disturbs me if (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 a name and a type (youll learn about if «x < 3) & (name.equals("Dirk ll » ) ) all the Java types In chapter 3). System.out.println(~Gently "); int weight; Iitype: int, name: weight System .out.print("this line runs no matter what ll ) ; .. Classes and methods must be deflned within a pair of curly braces. public void go ( ) ( II amazing code here }10 chapter 1
  • 35. www.it-ebooks.info dive In A Quick Dip while (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 some Notice the difference between the assignmentcondition is true, you do everything inside the operator (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 a while > 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.aCnamlnTMTub x = x-I; II or wed loop foreveris true; keep scooping", you have a clear booleantest. There either is ice cream in the cub or there inc 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 not II z is not equal to 17wearing plaid..." you are here ~ 11
  • 36. www.it-ebooks.infoJava basics Exall1ple of a while loop public class Loopy { Q: Whydoes everything have public static void main (String[] args) ( to be In a dass7 int x .. 1; A: ~ava is 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 one monolithic source file with a pile x = x + 1; of procedures. In chapter 2 youll ) learn that a class Is a blueprint for System.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 Loopy every class I write1 Before the Loop In the loop A: Nope .A Java prog ram might use dozens of classes (even Va.lue In the loop ot x is 1 hundreds), but you might only Va.lue of x i8 2 have one with a maIn method- In th8 loop the one that starts the program Value of x is 3 running.You might wrIte test This is aft.r the loop classes, though, that have main methods for testing your other POI~ 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"Q Java, 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 can public 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 void main (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 Iflest2II is ~ 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 in ONE 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.14 chapter 1
  • 39. www.it-ebooks.info dive 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 cant find a Java-enabled version of your favorite gadget. you can stili run it as if it were a Java device by controlling it through some other Interface (say, your laptop) that is runnIng Java.This Is known as the Jini surrogate architecture. Y~ you con have that geek dream home.·IPmulticast If youre gonna be all picky about protocol you are her e ~ 15
  • 40. www.it-ebooks.infolets write a program Try my new phrase-a-matic and youll be a slick talker just like the boss or those 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"} j Strinq[] 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 ...d11bt iot one.Lenqth " wordListOne . length; int twoLength " wordListTwo .length; int threeLength = wordListThree.lenqthj / / generate .... random numbers int randl :lII (int) (Math.random() " ooeLenqth) j int rand2 ::: (int) (Math .randomO • twoLength); int rand3 " (int) (Math.randa:n() " threeLength); O //now build a pllrue String phrase" wordListOne [randl] + " " + wordListTwo[rand2] + " " + wordListTbree[rand3] ; / / print oat the phra.. Sys.tem.out.println("What we need is a " + phrase); }16 ch 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 need random number between 0 and 13 (Java arrays are zero-based, so the first word is at ition 0, the second word position I, and the last word is position 13 in a 14-element what 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 competency point number that we wanted to convert to an integer.~t z • (int) 24.6; 24/1 empowered mindshare ow 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 vision ether. 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 JVM Fireside Chats Ton1gb.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 exactly would you run? Theres a TMSonJava was designed to use a bytecode compiler, for your information. IfJava were a purely interpreted language, where-s-at runtime-s-the virtual machine had to translate straight-from-a-text- editor source code, a java program would run at a ludicrously glacial pace. javas had a challenging enough time convincing people that 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 (not to mention arrogant) perspective. While it is true that-tJuoretically--you can run any properly formatted bytecode even if it didnt come out of a Java compiler, in practice thats absurd. A programmer writing bytecode by hand is like doing your word processing by writing raw postscript. And I would appreciate it 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 people to 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 Magnets Code Magnets A working Java program is all scrambled up on the fridge. Can you rearrange the code snippets to make a working Java program that produces the output listed below? Some of the curly braces fell on the floor if ( JC <: <: 1) ( and they were too small to pick up, so feel free to add as many of those as you need! SYSt.,~ ...... OUt . JC .. .. ·Pr.lnt( "d" ) • ... - 1: i f (x == 2) { class Shuftlel ( public static Void main(String I) args) ( if pc. > 2) { sygtem.out.print(~a~); int x 3; >r .. x-I; System. Out . . pr.l n t(,,_,,); while (x > 0) { ~ I., java Shufflel a-b c-d
  • 45. www.it-ebooks.info dive In A Quick Dip B public 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 page represents 11 complete source file. Your job is to pIa} cotJ1Piler and determine whether each of these files will cottlPile. If-they wont cottlPile. how woald you l"lX them? A c class Exerciselb {~_ass Exerciselb { int x • 5; public static void main(String [) args) while ( x > 1 ) int x " Ii x =x - Ii while ( x < 10 if ( x < 3) ( if ( x > 3) ( System.out.println(~small x~); systam.out.println(~big X")i you are here ~ 21
  • 46. www.it-ebooks.infopuzzle: crossword 1 2 J 4 S f- I Ja~Cr~ss t. O II ~ --- 8 - 9 10 ~ l..- lets give your right brain somethIng to do. 2 I- - Itsyour standard crossword, but almost all f- ~ I-- 13 of the solution words are from chapter 1.Just 4 5 6 to keep you awake we alsothrew in a few , (non-Java) words from the high-tech world. - - - - ~ 18 9 Across I- 20 - 4. Command-line invoker 6. Back again? L- -- bL 21 8. Cant go both ways 1 9. Acronym for your laptopS power 12. number variabletype 13. Acronym for a chip Down 14. SaysomethIng 1. Not an integer (or _ _ your boat) 18. Quite a crew of characters 2. Come back empty-handed 19. Announce a new class or method 3. Open house 21. Whatsa prompt good for? 5. ThIngs holders 7. Until attitudes improve 10. Sourcecode consumer 11 . Can pin it down t 13. Dept. of LANJockeys 1S. Shocking modifier 16. Justgona haveone 17. How to get things done 20. Bytecode consumer22 chapter 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 x 0; int y = 0; while x < 5 ) System.out.print(x + "" + y +" "); x = x + 1; candidates: Possible output: 00 11 21 32 42 lJ. 21 32 42 53 00 11 23 36 410 02 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~l puzzle while ( ) { Your job is to take code snippets from the pool and place them into the blank lines in the code. You may not use the if ( 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 that will compile and run and produce the output listed. Dont be fooled-this ones harder than it looks. if ( ) { Output } if ( x 1 ) { %java PoolPuzzleOne a noise } if ) { annoys an oyster } System.out.println(""); } }Note: Each snippetfrom the pool can beused only oncel24 chapter 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, it int 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 - Ij int 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 0 Systern.out.print("d")j } class d~c1Qratlon, and dont forget x = x - Ij ) the matching curly brace! } } class Exerciss1b { public static void main(String Uargs) { int x = Sj j a v a Shuffle! while ( x > 1 a- b c - d x .. x - 1; C if ( 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 answers fF IV -P •J s L 0 0 p A V A R ,,- -U W .E- I -B D It V IS B R A IN C H A "- l A 1: N T 0 A I - - - It Y L M R t s y s ir 8 E M a u T P R r N T L. Iclass PoolPuzzleOne { public static void main(String (] args) { - T A A - I - L -A B ~ M ~ int x == 0; 18 S T R I N G 9 D E C L A R e while ( X • 4 ) { I R E T f-- f-- ~J System.out. prlntfQ); C ---- - -H if ( x < 1 ) { V 0 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: Syst£ln. out. prlnt(olsej; } System.out.println(UU); X =X + 1; y j ava PoolPuzzl c One } Ct noise } anno~s} an o ~s t e r 32 U 53 .I.f I Y < 5 ) II - X + 1, UIy<3 :It - x-II ) 1. • Y. + 2.26 ch apter 1
  • 51. www.it-ebooks.info2 classes and objects A Trip to Objectville We’re going to Objectville! We’re leaving this dusty ol’ procedural town for good. I’ll send you a postcard. I was told there would be objects. this is a new chapter 27
  • 52. www.it-ebooks.infoonce upon a time in ObjectvilleChair Wars(or How Objects Can Change Your Life) the specO the chairIn Larry’s cube At Brad’s laptop at the cafe rotate(shapeNum) { // make the shape rotate 360º } playSound(shapeNum) { // use shapeNum to lookup which } // AIF sound to play, and play it } } }28 chapter 2
  • 53. www.it-ebooks.info classes and objectsLarry thought he’d nailed it. He could almost feel the rolledsteel of the Aeron beneath his...But wait! There’s been a spec change. ape moeba sh l be an a he others. There wil en, with t what got added to the spec re on the sc ser clicks on the eu e the When th rotate lik nd file amoeb a, it will .hif sou d play a o thers, anBack in Larry’s cube At Brad’s laptop at the beachplaySound(shapeNum) { // if the shape is not an amoeba, // use shapeNum to lookup which Amoeba // AIF sound to play, and play it rotate() { // else // code to rotate an amoeba // play amoeba .hif sound } } playSound() { // code to play the new // .hif file for an amoeba } you are here4 29
  • 54. www.it-ebooks.infoonce upon a time in ObjectvilleLarry snuck in just moments ahead of Brad. 1) determine the rectangle that surrounds the shape 2) calculate the center of that rectangle, and rotate the shape around that point. Larry point in rotation Ameoba version: ’s and Brad What the spec conveniently forgot to mention atio n meba rot Wh ere the a e: uld b point shoBack in Larry’s cube At Brad’s laptop on his lawn chair at the Telluride Bluegrass Festival rotate(shapeNum, xPt, yPt) { Amoeba // if the shape is not an amoeba, int xPoint int yPoint // calculate the center point rotate() { // based on a rectangle, // code to rotate an amoeba // then rotate // using amoeba’s x and y // else } // use the xPt and yPt as playSound() { // the rotation point offset // code to play the new // .hif file for an amoeba // and then rotate } }30 chapter 2
  • 55. www.it-ebooks.info classes and objectsSo, Brad the OO guy got the chair, right ? What Larry wanted (figured the chair would impress her) 1 Square Circle Triangle Amoeba I looked at what all four rotate() rotate() rotate() rotate() classes have in common. playSound() playSound() playSound() playSound() 2They’re Shapes, and they all rotate and ShapeplaySound. So I abstracted out thecommon features and put them into a rotate() playSound() 3new class called Shape. Then I linked the other Shape superclass four shape classes to rotate() playSound() the new Shape class, in a relationship called inheritance.You can read this as, “Square inherits from Shape”,“Circle inherits from Shape”, and so on. I removed subclassesrotate() and playSound() from the other shapes, so nowthere’s only one copy to maintain. Square Circle Triangle AmoebaThe Shape class is called the superclass of the other fourclasses. The other four are the subclasses of Shape. Thesubclasses inherit the methods of the superclass. In otherwords, if the Shape class has the functionality, then thesubclasses automatically get that same functionality. you are here4 31
  • 56. www.it-ebooks.infoonce upon a time in ObjectvilleWhat about the Amoeba rotate()? rride Now ve O As w k Me Ho superclass (more abstract) Shape 4 rotate() playSound() made the Amoeba class override I Imade the Amoeba class override the rotate() and playSound() the rotate() method of the superclassof the superclass Shape. methods Shape.subclasses(more specific) Overriding just means that aa Overriding just means that subclass redefines one of its subclass redefines one of its inherited methods when it needs inherited methods when it needs Square Circle Triangle Amoeba to change or extend the behavior to change or extend the behavior of that method. of that method. rotate() { // amoeba-specific // rotate code { Overriding methods playSound() { // amoeba-specific // sound code { I can take care of myself. I know how an Amoeba I know how a Shape is is supposed to rotate supposed to behave. Your and play a sound. job is to tell me what to do, and my job is to make it happen. Don’t you worry your little program- mer head about how I do it.32 chapter 2
  • 57. www.it-ebooks.info classes and objectsThe suspense is killing me.Who got the chair? What do you like about OO? “It helps me design in a more natural way. Things have a way of evolving.” -Joy, 27, software architect “Not messing around with code I’ve already tested, just to add a new feature.” -Brad, 32, programmer “I like that the data and the methods that oper- ate on that data are together in one class.” -Josh, 22, beer drinker “Reusing code in other applications. When I write a new class, I can make it flexible enough to be used in something new, later.” -Chris, 39, project manager “I can’t believe Chris just said that. He hasn’t written a line of code in 5 years.” -Daryl, 44, works for Chris metacognitive tip If you’re stuck on an exercise, try talking about “Besides the chair?” it out loud. Speaking (and hearing) activates -Amy, 34, programmer a different part of your brain. Although it works best if you have another person to discuss it with, pets work too. That’s how our dog learned polymorphism. you are here4 33
  • 58. www.it-ebooks.infothinking about objectsWhen you design a class, think about the objects thatwill be cre ated from that class t ype. Think about: things the object knows things the object does ShoppingCart Button Alarm label alarmTime cartContents knows color knows alarmMode knows setColor() setAlarmTime() addToCart() does setLabel() does getAlarmTime() setAlarm() does removeFromCart() dePress() isAlarmSet() checkOut() unDepress() snooze()Things an object knows about itself are called Song instance variables instance title knows variables artist (state) setTitle()Things an object can do are called methods setArtist() does (behavior) play() methods Sharpen your pencilThink of instance as another way of saying object.34 chapter 2
  • 59. www.it-ebooks.info classes and objects What’s the difference between a class and an object? A class is not an object. (but it’s used to construct them) JVM classLook at it this way... you are here4 35
  • 60. www.it-ebooks.infomaking objectsMaking your first object The Dot Operator (.) TestDriveBungee BungeeTestDrive TestDrive 1 Write your classclass Dog { instance va DOG riables int size; size String breed; breed name String name; a method bark() void bark() { System.out.println(“Ruff! Ruff!”); }} 2 Write a tester (TestDrive) class class DogTestDrive { ethod just a main m ut code public static void main (String[] args) { p step) // Dog test code goes here e onna (we’rit gn the next } in i } In your tester, make an object and access 3 the object’s variables and methods class DogTestDrive { public static void main (String[] args) { Dog d = new Dog(); make a Dog object d.size = 40; use the dot operator (.) dot r d.bark(); to set the size of the Do operato } and to call its bark g If you already have some OO savvy, you’ll know we’re not using encapsulation. } () method We’ll get there in chapter 4.36 chapter 2
  • 61. www.it-ebooks.info classes and objectsMaking and testing Movie objects class Movie { String title; String genre; int rating; void playIt() { System.out.println(“Playing the movie”); } } public class MovieTestDrive { public static void main(String[] args) { Movie one = new Movie(); one.title = “Gone with the Stock”; one.genre = “Tragic”; one.rating = -2; Movie two = new Movie(); two.title = “Lost in Cubicle Space”; two.genre = “Comedy”; two.rating = 5; two.playIt(); Movie three = new Movie(); three.title = “Byte Club”; three.genre = “Tragic but ultimately uplifting”; three.rating = 127; } } Sharpen your pencil title MOVIE object 1 genre title genre rating rating playIt() title object 2 genre rating title object 3 genre rating you are here4 37
  • 62. www.it-ebooks.infoget the heck out of mainQuick! Get out of main!The t wo uses of main: to test your real class to launch/start your Java application GameLauncher makes GuessG a object ame main(String[] args) tells it and startG to ameThe Guessing Game GuessGame instance p1 variables p2 forth p3 playerse three startGame() GuessGame.class Player.class GameLauncher.class the Player this pnlumber guessedayer number guess() meth makingod for guess a38 chapter 2
  • 63. www.it-ebooks.info classes and objectspublic class GuessGame { GuessGame has Player p1; variables for ththree instance e three Player Player p2; objects Player p3; public void startGame() { create three Play p1 = new Player(); assign them to theer objects and p2 = p3 = new Player(); new Player(); instance variables three Player int guessp1 = 0; declare three variables to hol int guessp2 = 0; int guessp3 = 0; three guesses the Players makd the e boolean p1isRight = false; boolean p2isRight = false; declare three variables to hold a true or boolean p3isRight = false; false based on the player’s answer int targetNumber = (int) (Math.random() * 10); make a ‘target’ number that the System.out.println(“I’m thinking of a number between 0 and 9...”); players have to guess while(true) { System.out.println(“Number to guess is “ + targetNumber); p1.guess(); p2.guess(); call each player’s guess() method p3.guess(); guessp1 = p1.number; System.out.println(“Player one guessed “ + guessp1); guessp2 = p2.number; get each player’s guess (the result of thei System.out.println(“Player two guessed “ + guessp2); guess() method running) by accessing the r guessp3 = p3.number; number variable of each player System.out.println(“Player three guessed “ + guessp3); if (guessp1 == targetNumber) { p1isRight = true; check each player’s guess to see if it mat the target number. If a player is right, ches } if (guessp2 == targetNumber) { p2isRight = true; then set that player’s variable to } (remember, we set it false by defabe true ult) if (guessp3 == targetNumber) { p3isRight = true; } if player one OR player two OR player three is right if (p1isRight || p2isRight || p3isRight) { (the || operator means OR) ... System.out.println(“We have a winner!”); System.out.println(“Player one got it right? “ + p1isRight); System.out.println(“Player two got it right? “ + p2isRight); System.out.println(“Player three got it right? “ + p3isRight); System.out.println(“Game is over.”); break; // game over, so break out of the loop otherwis players fe,rstay in the loop and ask } else { // we must keep going because nobody got it right! o another g System.out.println(“Players will have to try again.”); uess. the } // end if/else } // end loop } // end method} // end class you are here4 39
  • 64. www.it-ebooks.infoGuessing GameRunning the Guessing Gamepublic class Player { int number = 0; // where the guess goes public void guess() { number = (int) (Math.random() * 10); System.out.println(“I’m guessing “ File Edit Window Help Explode + number); %java GameLauncher }} I’m thinking of a number between 0 and 9... Number to guess is 7public class GameLauncher { I’m guessing 1 public static void main (String[] args) { I’m guessing 9 GuessGame game = new GuessGame(); game.startGame(); I’m guessing 9 } Player one guessed 1} Player two guessed 9 Player three guessed 9 Players will have to try again. Java takes out the Garbage Number to guess is 7 I’m guessing 3 I’m guessing 0 I’m guessing 9 Player one guessed 3 Player two guessed 0 Player three guessed 9 Players will have to try again. Number to guess is 7 I’m guessing 7 I’m guessing 5 I’m guessing 0 Player one guessed 7 Player two guessed 5 Player three guessed 0 We have a winner! Player one got it right? true Player two got it right? false Player three got it right? false Game is over.40 chapter 2
  • 65. www.it-ebooks.info classes and objects there are noDumb Questions Make it Stic k random() publicstatic BULLET POINTS ß Object-oriented programming lets you extend a program without having to touch previously-public static final tested, working code. ß All Java code is defined in a class. ß A class describes how to make an object of that class type. A class is like a blueprint. ß An object can take care of itself; you don’t have to know or care how the object does it. ß An object knows things and does things. ß Things an object knows about itself are called instance variables. They represent the state of an object. ß Things an object does are called methods. They represent the behavior of an object. random() ß When you create a class, you may also want to create a separate test class which you’ll Math use to create objects of your new class type. ß A class can inherit instance variables and methods from a more abstract superclass. ß At runtime, a Java program is nothing more than objects ‘talking’ to other objects. you are here4 41
  • 66. www.it-ebooks.infoexercise: Be the Compiler Each of the Java files on this page represents a complete source file. Your job is to play compiler and determine whether each of these files will compile. If they won’t compile, how would you fix them, and if they do compile, what would be their output? Aclass TapeDeck { boolean canRecord = false; B class DVDPlayer { void playTape() { System.out.println(“tape playing”); boolean canRecord = false; } void recordDVD() { void recordTape() { System.out.println(“DVD recording”); System.out.println(“tape recording”); } } }} class DVDPlayerTestDrive {class TapeDeckTestDrive { public static void main(String [] args) { public static void main(String [] args) { DVDPlayer d = new DVDPlayer(); t.canRecord = true; d.canRecord = true; t.playTape(); d.playDVD(); if (t.canRecord == true) { if (d.canRecord == true) { t.recordTape(); d.recordDVD(); } } } }} }42 chapter 2
  • 67. www.it-ebooks.info classes and objects d.playSnare(); DrumKit d = new DrumKit(); = true; boolean topHat = true; boolean snare void playSnare() { ang”); System.out.println(“bang bang ba-b } public static void main(String [] args) { if (d.s nare == tr ue) { d.playS nare(); } d.snare = false; class DrumKitTestDrive { (); TopHat d.play class DrumKit { void playTopH at () { System.out.p rintln(“ding ding da-ding”File Edit Window Help Dance } );% java DrumKitTestDrivebang bang ba-bangding ding da-ding you are here4 43
  • 68. www.it-ebooks.infopuzzle: Pool Puzzle public class EchoTestDrive { public static void main(String [] args) { Echo e1 = new Echo(); _________________________ Pool Puzzle int x = 0; while ( ___________ ) { e1.hello(); __________________________ if ( ____________ ) { e2.count = e2.count + 1; } if ( ____________ ) { e2.count = e2.count + e1.count; File Edit Window Help Implode } %java EchoTestDrive x = x + 1; helloooo... } helloooo... System.out.println(e2.count); helloooo... } helloooo... } 10 class ____________ { int _________ = 0; void ___________ { System.out.println(“helloooo... “); } }44 chapter 2
  • 69. www.it-ebooks.info classes and objects ? ho am IW I am compiled from a .java file. class My instance variable values can be different from my buddy’s values. I behave like a template. I like to do stuff. I can have many methods. I represent ‘state’. I have behaviors. I am located in objects. I live on the heap. I am used to create object instances. My state can change. I declare methods. I can change at runtime. you are here4 45
  • 70. www.it-ebooks.infoexercise solutions Be the Compiler: class TapeDeck { boolean canRecord = false; void playTape() { System.out.println(“tape playing”); A } void recordTape() { System.out.println(“tape recording”); } }Code Magnets: class TapeDeckTestDrive { public static void main(String [] args) {class DrumKit { TapeDeck t = new TapeDeck( ); boolean topHat = true; t.canRecord = true; boolean snare = true; t.playTape(); void playTopHat() { if (t.canRecord == true) { System.out.println(“ding ding da-ding”); t.recordTape(); } } } We’ve got the template, now we have void playSnare() { } to make an object ! System.out.println(“bang bang ba-bang”); }} class DVDPlayer { boolean canRecord = false;class DrumKitTestDrive { void recordDVD() { public static void main(String [] args) { System.out.println(“DVD recording”); } DrumKit d = new DrumKit(); void playDVD ( ) { d.playSnare(); System.out.println(“DVD playing”); d.snare = false; } d.playTopHat(); } if (d.snare == true) { class DVDPlayerTestDrive { d.playSnare(); public static void main(String [] args) { } DVDPlayer d = new DVDPlayer(); } B d.canRecord = true;} d.playDVD(); if (d.canRecord == true) {File Edit Window Help Dance d.recordDVD();% java DrumKitTestDrive }bang bang ba-bangding ding da-ding } The line: d.playDVD( ); wouldn’t } compile without a method !46 chapter 2
  • 71. www.it-ebooks.info classes and objects Pool Puzzlepublic class EchoTestDrive { public static void main(String [] args) { Echo e1 = new Echo(); Echo e2 = new Echo( ); // the correct answer I am compiled from a .java file. class - or - My instance variable values can be Echo e2 = e1; // is the bonus answer! different from my buddy’s values. object int x = 0; while ( x < 4 ) { I behave like a template. class e1.hello(); I like to do stuff. object, method e1.count = e1.count + 1; if ( x == 3 ) { I can have many methods. class, object e2.count = e2.count + 1; I represent ‘state’. instance variable } if ( x > 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 object System.out.println(e2.count); instances. class }} My state can change. object, instance variable I declare methods. class class Echo { int count = 0; I can change at runtime. object, instance variable void hello( ) { System.out.println(“helloooo... “); Note: both classes and objects are said to have state and behavior. } They’re defined in the class, but the object is also said to ‘have’ } them. Right now, we don’t care where they technically live. File Edit Window Help Assimilate %java EchoTestDrive helloooo... helloooo... helloooo... helloooo... 10 you are here4 47
  • 72. www.it-ebooks.info3 primitives and references Know Your Variables Variables come in two flavors: primitive and reference. So far youve used 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 a method 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 seen variables declared as something more complex like a String or an array. But theres gotta be more to life than integers, Strings, and arrays.What If you have a PetOwner object with a Dog instance variable? Or a Car with an Engine? In this chapter well unwrap the mysteries of Java types and look at what you can declare as a variable, what you can pur In a variable, and what you can 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 = new Giraffe(); 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 <, type na.....e Note: When you see a statement like: "an object of type X", think of l)Peand classes synonyms. (Well refine that a little more in later chapters.)50 chapter 3
  • 74. www.it-ebooks.info primitives and references Primitive Types n you think ofJava variables, think of cups. Coffee cups, tea cups, giant Type Bit Depth Value Range that hold lots and lots of beer, those big cups the popcorn comes in at boolean and char movies, cups with curvy, sexy handles, and cups with metallic trim that learned can never, ever go in the microwave. boolean (JVM .. pedfic) true or falsewariable is just a cup. A container. It holds something. char 16 bits 0 to 65535 a size, and a type. In this chapter, were going to look first at the numeric (all are signed)- bles (cups) that hold primitives, then a little later well look at cups Integer hold references to objects. Stay with us here on the whole cup analogy-as byte 8 bits -128 to 127 pie as it is right now, itll give us a common way to look at things when discussion gets more complex. And thatll happen soon. short 16 bits -32768 to 32767- itives are like the cups they have at the coffeehouse. If youve been to a int 32 bits -2147483648 ucks, you know what were talking about here. They come in different and each has a name like short, tall, and, "Id like a to 2147483647 de mocha half-eaffwith extra whipped cream". long 64 bits -huge to huge migh t see the cups displayed on the counter, u can order appropriately: floating point float 32 bits varies double 64 bits varies Primitive declarations small short tall grande with assignments: Int ){i --!II" And inJava, primitives come in different sizes, and those sizes have names. When you declare a variable in Java, x = 234; E ::a-Y must declare it with a specific type. The oU byte b = 89; I four containers here are for the four boolean isfun = true; integer primitives in Java. double d = 3456,98j char c =fj fang int short byte lnt z e x: cup holds a value, so for Java primitives, rather than saying, "Id like a boolean IsPunkRock; french roast", you say to the compiler, "Id like an int variable with the isPunkRock = false; ber 90 please." Except for one tiny difference ... in Java you also have to your cup a name. So its actually, "Id like an int please, with the value boolean powerOn;:H86, and name the variable height." Each primitive variable has a fixed powerOn = IsFun; ber of bits (cup size). The sizes for the six numeric primitives inJava long big = 3456789j shown below: float f = 32.5i .( qatta "a~t -that Nott tht ~ btU,<St ja~a thi"~ ..,i-th a ~. ~oab~ foi"t I~ byte short int long float double "ythi,,~ fI1-th a ,<St ~. 8 16 32 64 32 64 a ci~e, "",65 fO# you are here ~ 51
  • 75. www.it-ebooks.infoprlmltlve assignmentYou really dot1~t wat1t to spill that...Be sure the value can fit into the variable. You cant put a large value into a small cup. The compiler wont let you put a value from a large cup into WeU, OK, you can, but youll a small one. But what about lose some. Youll get, as we say, the other way-pouring a spillage. The compiler tries to small cup into a big one7 No help prevent this ifit can tell problem. from your code that somethings Basedon what you know not going to fit in the container about the size and type of the (variable/cup) youre using. pri mitive va rlables, see if you can figure out which of these For example, you cant pour an are legal and which arent, int-full of stuff into a byte-sized We havent covered all the container, as follows: rules yet, so on some of these youll have to use your best int x = 24; judgment. Tip: The compiler byte b = x; always errs on the side of safety. //wont work!! From the following list Circle the statements that would beWhy doesnt this work, you ask? After all, the value of x is 24, and 24 is definitely legal if these lines were in asmall enough to fit into a byte. You know that, and we know that, but all the single method:compiler cares about is that youre trying to put a big thing into a small thing.and theres the possibility of spilling. Dont expect the compiler to know what the 1. int x = 34.5;value of xis. even if you happen to be able to see it literally in your code. 2 . boolean boo x;You can assign a value to a variable in one of several ways including: 3 . int g = 17; • type a litera/value after the equals sign (x=12. isGood = true, etc.) 4. int y " 9; • assign the value of one variable to another (x =y) 5 . Y = Y + 10; • use an expression combining the two (x = y + 43)In the examples below, the literal values are in bold italics: 6. short s;int size = 32; declare an int named size, assIgn ilthe value 32 7. s = y;char initial = j; declare a char named initial, assign itlhe value T 8. byte b = 3;double d = 456.709; declare a double named d, assign it the value 456.709 9 . byte v = b;boolean isCrazy; declare a boolean named IsCrazy (no assignment) 10. short n " 12;isCrazy true; assign the value true to thepreviously-declared ;sCrazyint y = x + 456; declare an int named y, assign Itlhe value that is the sum 11. v " n ; of whatever x is now plus 456 12. byte k 128;52 chapter 3
  • 76. www.it-ebooks.info prlmitJves and referencesJack away frotH that keyword!lbu know you need a name and a type for your variables.YOu already know the primitive types.. , what can you we as names? The rules are simple. Youan name a class, method, or variable according to the owing rules (the real rules are slightly more flexible, t these will keep you safe) : ftIfIeS ote: . be• It must start with a letter, underscore U, or , /It primitIve 7" float do U . dollar algn ($). You cant atart a name with a The elg e s"lOft lot long . t/lem: number. eao char byt membermg boO onic for re , om nem• After the first character, you can u. . numbers as And here S , ges urge t S udnt n well. Just dont atart It with a number, CafefU~ 8eas "10• It can be anything you like, subject to those two 8e bertet. furry Oogs tll stick even rules, JU8t 80 long as It Isnt one of Javas reserved out own, I words. It yoU make up Y D S I LF- - B_ c- B_ - - public static voidAnd the primitive types are reserved as well: boolean char byte short int long floa.t double t there are a lot more we havent discussed yet. Even if you dont ed to know what they mean, you still need to know you can t useem yourself. Do not-under any circumstances-try to memorize these.w. To make room for these in your head, youd probably have to something else . Like where your car is parked. Dont worry, bythe end of the book youll have most of them down cold.fhls table reserved. boolean byte mar double flom Inl long protected abstract flnal native storic strictfp syndJronlzed transient If else do while swllm case delauh for break continue assart doss ex1and~ implements import rnstanceof interface new package super this catch flnol~ try throw throws return void canst gala enumJavas keywords and other reserved words (In no useful order). If you use these for names, the complier will be very, vel} upset. you are here I 53
  • 77. www.it-ebooks.infoobject referencesControlling your ~og objectYou know how to declare a primitive variable and assign it avalue . But now what about non-primitive variables? In otherwords, what about objects? Dog d = new Dog(); d.bark();• There Is actually no such thing as an object variable.• Theres only an object reference variable. thi.k ot this• An object reference variable holds bits that represent a way to access an object.• It doesnt hold the object Itsetf, but It holds something like a pointer. Or an address. Except., in Java we dont really know what Is Inside a reference variable. We do know that whatever It Is, It represents one and only one object. And the JVM knows how to use the reference to get to the object.You can 1 stuff an object into a variable. We often think ofit that way... we say things like, "I passed the String to theSystem.out.printlnf) method." Or, "The method returns a Dog",or, "I put a new Foo object into the variable named rnyfoo."But thats not what happens. There arent giantexpandable cups that can grow to the size of any Thillk o-f a D~object. Objects live in one place and one place referente vdliable alonly-the garbage collectible heap! (Youlllearn more about that later in this chapter) a D~ len-ote to.h-ol.Although a primitive variable is full of You. IUC it to ~tt -tl~bits representing the actual value of the objut to do ~tthill9variable, an object reference variable is fullof bits representing a way to get to the (hIVolcc ",et.h~) .obJect.You use the dot operator (.)on a reference variable 10 say,"use the thing before the dot toget me the thing after the dot." Forexample:myDog.bark() ;means, "use the object referenced by the variable myDog toinvoke the barkt) method." When you use the dot operator onan object reference variable, think of it like pressing a buttonon the remote control for that object.54 chapter 3
  • 78. www.it-ebooks.info primitives and references The 3 steps of object declaration, creation and assignment 1 2 ~3~ byte short int long reference Dog myDog = new Dog(); 8 16 32 64 Ibll depth not relevant)At1 object referet1ce is just Declare a referencea"other variable value. O variableSomething that goes In a cup. Doq myDoq = new Dog () ;Only this time, the value 15 a remote control. Tells the JVM to allocate space for a reference variable, and names thatPrhldtlve Variable ~.. variable myDog. The reference variable J~itive Is, forever. of type Dog.ln other words,byte x = 7; a remote control that has buttons tothe bits representing 7 go to the variable. (00000111), Ubyte vall.4t control a Dog, but not a Cat or a Button or a Socket. Dog e Create an object Dog myDog " new Dog () ;Dog myDog = new Doq() ; Tells the JVM to allocate space for a new Dog object on the heap (well learn a lot more about that process, especially in chapter 9,) Dog object e Link the object and the reference Dog myDog = new Dog () ; Assigns the new Dog to the reference variable myDog.ln other words, programs the remote control, Dog object ~n care how meny ts and Os tho,o are In a (afare~08l1tlriabla lrs UP10 a&eh: " a."ld Ihe phase of Ihe moon , Dog you are he re . 55
  • 79. www.it-ebooks.infoobject references ,D:therel~o " . ume ~uest19115 Java,£NposeclQ: How big 15 a reference This weeks Interview:variable? Object ReferenceA. :Vou dont know. Unlessyoure cozy with someone on the HeadFirst So, tell us, whats life likefor an object reference? Reference: Pretty simple, really. Im a remote control and I can be programmed toJVMs development team, you control different objects.dont know how a reference is HeadArst Do you mean different objects even while youre running? Like, can yourepresented. There are pointersin there somewhere, but you refer to a Dog and then five minutes later refer to a Car?cant access them .You wont Reference: or course not- Once Im declared, thats it. If Im a Dog remote controlneed to. (OK, Ifyou Inslst, you then ru never be able to point (oops- my bad, were not supposed to say poin~ I mean rifermight as well Just imagine It to anything but a Dog.to be a 54-bit value.) But whenyoure talking about memory HeadFirst Does that mean you can refer to only one Dog?allocation issues, your Big Reference: No. I can be referring to one Dog, and then five minutes later I can refer toConcern should be about howmany objects (as oppose-d to some other Dog. As long as its a Dog, I can be redirected (like reprogranuning your remoteobject references) youre creating, to a different TV) to it. Unless... no never mind.and how big they (the objects) HeadFirst No, tell me. What were you gonna say?really are. Reference: I dont think you want to get into this now, but Illjust giveyou the short version - if Im maned as final, then once I am assigned a Dog, I can never be repro- grammed to anything else but I1ul1 one and only Dog: In other words, no other object canQ:So, does that mean that be assigned to me.all object references are the HeadFirst Youre right, we dont want to talk about that now. OK, sounless youresame size, regardless of the size final, then you can refer to one Dog and then refer to a differentDog later. Can you everof the actua I objects to which refer to fIl)tJring at alP. Is it possible to not be programmed to anything?they refer? Reference: Yes, but it disturbs me to talk about it.A.: Yep. All references for agiven NM will be the same HeadArst Why is that? Reference: Because it means Im null, and thats upsetting to me.size regardless of the objects HeadFirst You mean. because then you have no value?they reference, but each JVMmight have a different way of Reference: Oh, null isa value. Im stilla remote control, but its like you broughtrepresenting references, so home a new universal remote control and you dont have a TV Im not programmed toreferences on one JVM may be control anything. They can press my buttons all day long, but nothing good happens. Ismaller or larger than references just feel so... useless. A waste of bits. Granted, not that many bits, but still. And thats noton another JVM. the worst part. If I am the only reference to a panicular object, and then Im set to null (deprogrammed), it means that now rwboqy can get to that object I had been referring to.Q:can I do arithmetic on a HeadFirst And thats bad because...reference variable, Increment Ityou know - C stuff7 Reference: You have to ask? Here Ive developed a relationship with thisobject, an intimate connection, and then the tie issuddenly, cruelly, severed. And I will never seeA.: Nope. Say It with me again,"Java Is not C." that object again, because now its eligible for [producer, cue.tragic music) garbage collection. Sniff. But do you think programmers ever consider !haP. Snif. Why, wIrY cant I be a primi- tive? I hate being a refcrcut. The responsibility, all the broken attachments...56 chapter 3
  • 80. www.it-ebooks.info primitives and references ott the garbage..collectible heap = new Book(); = new Book(); e two Book reference - les.Create two new Book . Assig n the Book objects to reference variables. Book two Book objects are now living e heap.Obiects: 2 BookBook d = c; re a new Book reference variable. r than creating a new, third Book •assign the value of variable c to . ble d. But what does th is mean? li ke saying, "Take the bits In c, make a of them, and stick that copy Into d."..... c and d refer to the same....ect.The c and d variables hold Booktwo dlHerent copies of the. .me value. Two remotes.....grammed to one TV. ferences: 3Objects: 2 Bookc = h;Assign the value of variable b tovariab le c. By now you know what is means. The bits inside variableat are copied, and that new copy Isstuffed into variable c.Both band c refer to thesame object.References: 3Objects : 2 you are here ~ 57
  • 81. www.it-ebooks.infoobjects on the heapUfe a.,d death 0., the heap Book b = new Book() ; Book c = new Book() i Declare two Book reference variables. Create two new Book objects. Assign the Book objects to the reference variables. The two book objects are now living on the heap. ActIve References: 2 Reachable Objects: 2 Book b = Ci Assign the value of variable c to variable b. The bits Inside variable c are copied, and that new copy is stuffed Into variable b. Both variables hold identical values. Both band c refer to the ••me object. Object 1 I. abandoned and eligible for Garbage Collec- tion (GC). Active References: 2 Reachable Objects: 1 Abandoned Objects: 1 The first object that b referenced, Object 1, has no more references. Its unreachable. C = null; Assign the value nu 11 to variable c. This makes c a null reference, meaning It doesnt refer to anything. But Its still a reference variable, and another Book object can stili be assigned to It . Object 2 .tlll h •• an active reference (b), and •• long as It does, the object I. not eligible for GC. ActIve References: 1 null References: 1 Reachable Objects: 1 Abandoned Objects: 1 Book68 chapter 3
  • 82. www.it-ebooks.info primitives and referencesAn array is like atray of cups o Declare an int array verinble. An array variable is a remote control to an array object. int[] nums; Create a new int array with a length of 7 and assign it to the previously- I declared int r J variable nums nums = new int[7] ; Give each element in the array an int value. Remember, elements in on int array are just int variables. ~ .:is .3 nums [0] = 6; ~ ~ nums[l] = 19 ;~·s nums[2] = 44: nums[3] = 42: int array object (int[]) nums [4] = 10: nums[5] = 20; nums [6] =1; int[] Notit~ that. -tne arYaf ihtlt is dll objtd:, evell t.h~h ~e I tltMtllt.s art f"i",j·I:.Ives.Arrays are objects too Java standard library includes reference variable. Anything you Be sure to notice one key thing of sophisticated data structures would put in a variable of that rype in the picture above - the arm) is uding maps, trees. and sets can be assigned to an array element an object, even though its an array of Appendix B). but arrays are of that type. So in an array of type primitives. t when you just want a quick. int (int[]) . each element can hold Arrays are always objects, whether red, efficient list of things. an int, In a Dog array (Dog[]) each theyre declared to bold primitives ,"5 give you fast random element can hold... a Dog? No. or object references. But you can ess by letting you use an index remember that a reference variable have an array object thats declared ition to get to any element in just holds a reference (a remote to hold primitive values. In other array. control), not the object itself. So words, the array object can have in a Dog array, each element can elements which are primitives. but ry element in an array isjust hold a remote control to a Dog. Of the array itself is nevera primi tive,nriable. In other words, one of course, we still have to make the Regardless of what the array holds, eight primitive variable types . k: Large Furry Dog) or a Dog objects... and youll see all that the array itself is always an objectl on the next page. you are here. 59
  • 83. www.it-ebooks.infoan array of objectsMake att array of Pogs o Declare a Dog array variable Dog[] pets; A Create a new Dog array with W a length of 7, and assign it to the previously-declared Dog [J variable pets pets = new D09[7]; What~ .ttfsShtg1 Dogsl We have an array of Dog rmrence$, but no actual Dog obJects I Dog array object (Dog[]) A Create new Dog objects, and V assign them to the array elements. Remember, elements in a Dog array are just Dog reference variables. We still need Dogs! pets[D] = new Dog(); pets[l] = new Dog();~n,~~::~:f_~~~i:/_t _ --~dmake -ne ofthe 11 objects? Dog array object (Dog[])58 (.. .r 3
  • 84. www.it-ebooks.info primitives and references , name Dog Cot1trol your ~og (with a referetlce variable) barkO Dog fide = new Dog(); eatO fido.name = ~FidoN; chaseCalO We created a Dog object and used the dot operator on the reference variable fido to access the name variable." We can use the fido reference to get the dog to barkt) or eat/) or chaseCatO . fido.bark() i DogJava cares about type. fido .chaseCat();Once youve declared an array. youcant put anything an It except thing-that are of the declared array type. What happetts ifthe POQ is IttFor example, you cant put Q COt into a Dog a OOQ array?array (it would be pretty awful if someone ~e know we can access the Dogsthinks that only Dogs are inthe orrat, so Instance variables and methods usingthe.y ask eoch one to ~ark, and th~n to their the dot operator, but em what1 horror discoverthere s a cat lurkmg.) And you cant stick a double into on int orratl When the Dog is in an array, we dont (spillage., remember?). You can, however. have an actual variable name (like put Qbyte into on in t arraf, b~QuSe a fido). Instead we use array notation and byte will always fit into on int-SIZed cup. push the remote control button (dot This is known as an Implicit wid&ning. We ~perator) on an object at a particular gat Into the details tater. for now just Index (position) in the array: remember that the compiler wont 1st you put the wrM9 thing In on orraf, based on Dog[] myDogs = new Dog[3]; the GtfOYs d&elored type. myDogs[O] = new Dog() ; myDogs[O].name = "Fido"; myDogs[O] .bark(); Yes weknow were notdemonslralin - trying tokeep it simple. For now We1IgdencapsuiatiOn he chapter re . _reo butwe4. 0 encapsulation 10 you are here ~ 61
  • 85. www.it-ebooks.infousing referencesclass Dog ( Str ing name ; A Pog exatMple publ i c static void main (String() args) Dog II make a Dog ob ject and a c cess it name Dog dogl = new Dog(); dogl.bark{) ; barkO eatO dogl.name = "Bart" ; chaseCal() I I now mak e a Dog ar ra y Dog() myDogs = new Dog[3); Output I I a nd put s ome dog s i n i~ myDogs[O ) ne w Dog () ; myDogs[l ) new Dog () ; myDogs [2 ) dog!; /1 now Rece s s t he Dogs u s i ng t he ar r a y I I r e f e r e nce s myDogs(O).name " Fr e d " ; myDogs(l).narne "Marge " ; II Hmmnm . . . wha t i s myDogs (2 j name? System.out .print( "!ast dogs name is "); Sys t em. ou t . pr in t l n (myDogs (2) . narne ) ; • Variables come intwo flavors: primitive and II now 100 t hr ough t he a r r y reference. I I a nd t e l l all dog s t o ba rk • Variables must always be declared with aname and a type. i nt x = 0; mYDOgs .1ength)~ • Aprimitive variable value isthe bits representing whi1e(x < J the value (5, a, true, 3.1416, etc.). myDogs [xl .ba r k () ; a /aYiabc l~~ • Areference variable value isthe bits x = X + 1; ay-yii(S ha/C t."c lI~bCl" representing away to get to an object on the t)lat. ~/ts lOlA aJ heap. L t,lc jlY"Y I ee,.,.tfV 111 • Areference variable is like aremote control. Using the dot operator (.) on a reference variable islike pressing a button on the remole pUblic void bark() ( control to access amethod orinstance variable. System.out.prin tln(narne i- " says Ruff !"); • Areference variable has a value of n u 11 when it is not referencing any object pUblic vo i d ea t ( ) { • An array is always an object, even if the" array p ub lic voi d c ha s e Ca t () isdeclared to hold primitives" There is no such thing as a primitive array, only an array that holds primitives.62 chapter 3
  • 86. www.it-ebooks.info prlmltlves and references BE the cornriler Each of the Java nles on this page represents a cOtIlplete source file. Your job is to play compiler and detel"llline whether each of these files will compile. If they wont cmqpile, how would rOll fIX them? A Bclass Books { class Hobbits { String title; String author; String name;} public static void main(String (J args) {class BooksTestDrive public static void main(String Ij args) Hobbits () h = new Hobbits[3]i int z = 0; Books () myBooks :: new Books(3); int x :: 0; while (z < 4) { myBooks{Oj.title :: "The Grapes of Java"; z = z + 1; myBooks(lj.title = ~The Java Gatsby"i hlz] :: new Hobbits(); myBooks(2).title :: ~The Java Cookbook"; h{z] .name = "bilbo"i myBooksIO).author = "bob"; if (z == I) { myBooksllj.author:: "sue"; hlz].name:: "frodo"; myBooks(2).author = "ian"; } if(z==2){ wbile (x < 3) { h[z).name = Usam"; System.ou t.print(myBookslxj.title)i System.out.print(" by U)i System.out.print (h{z).name + " is a H); System.out.println(rnyBooks[xj.author) ; System.out.println(Ugood Hobbit name"); x = x + 1; } } you are here. 63
  • 87. www.it-ebooks.infoexercise: Code Magnets Code Magnets Aworking Java program Is all scrambled up int Y == on the fridge. Can you reconstruct the code snippets to make a working Java program index(y) ; that produces the output listed below? Some of the curly braces fell on the floor and they were too small to pick up, so feel free to add as many of those as you need! int ref; while (y < 4) { System.out.print1n(islands{refj)i index(Ol .,. 1; index(ll " 3; index (21 == 0; index[31 .,. 2; ~ String (] islands new String(4)i System.out.print(Uisland ; U); int [1 index "" new int[4Ji y y + 1; class TestArrays { public static void main(Strin N ":J rJ args) {64 chapter 3
  • 88. www.it-ebooks.info primitives and references class Triangle double arear int height; pool puzzle iot length; public static void main(String [] args) Your Job is to take code snippets from the pool and place them into the blank lines in the code. You may use the same snippet more than while ( ) { once, and you wont need to use all the snippets .Your gOlll is to _______ .height (x + 1) * 2: make a class that will compile and run and produce the output listed. _______ .leogth x + 4: System.out.print( "triangle "+x+" I area"};Output System.out.println(" =" + .area): } x = 27: Triangle tS = ta[2]: ta[2J.area = 343: System.out.print(uy = U + y): System.out.println(", tS area = "+ tS.area};Bonus Questlonl } For extra bonus points, use snippets void setArea() {from the pool to fill in the missingoutput (above). (height * length) / 2; } } Note: Each lnlppet from the pool nn be used more than oncel yo u are here ~ 65
  • 89. www.it-ebooks.infopuzzle: Heap o Trouble class HeapQuiz { int id == 0;A Heap 0 Trouble public static void main(String [] argsl int x = 0;A short Java program is listed to the HeapQuiz ( ] hq = new HeapQuiz(S]iright. When /1 do stuff is reached, someobjects and some reference variables while ( x < 3 1 (will have been created. Your task Is hq[x) = new HeapQuiz();to determine which of the reference hq(x] . id == Xivariables refer to which objects. Not all x = X + 1ith e reference variables will be used, and }some objects might be referred to morethan once. Draw lines connecting the hq[3] == hq[l]ireference variables with their matching hq[4] hq[l] ;objects. hq[3] = null;Tip: Unless you re way smarter than us, hq (4) hq (0] ;you probably need to draw diagrams hq(Ol == hq(31ilike the ones on page 55 and 56 of th is hq(3] hq[2];chapter. Use a pencil so you can drawand then erase reference li nks (the hq[2] = hq [0] ;arrows goIng from a reference remote II do stuffcontrol to an object). Reference Variables: HeapQulz Objects: hq[O] hq[1] hq[2] 10 ~~ hq[3] hq[4] f til64 chapter 3
  • 90. www.it-ebooks.info primitives and referencesThe case of the pilfered references It was a clark and stormy night Tawny strolled into the programmers bullpen like sheowned the place. She knew that all the programmerswould still be hard at work, and shewanted help. She needed a new method added to the pivotal class that was to be loaded into theclients new top-secretJava-enabledcell phone. Heap space in the cell phones memory wasas tight as Tawnys top, and everyone knew it The normally raucous buzz in the bullpen fell tosilence as Tawny eased her way to the white board. She sketched a quick overview of the newmethods functionality and slowly scanned the room. Well boys, its cnmch time", she purred.Whoever creates the most memory efficientversion ofthis method is coming with me to theclients launch party on Maui tomorrow... to help me install the new software." The next morning Tawny glided into the bullpen wearing her short Aloha dress. "Gentlemen", she smiled, "the plane leaves in a few hours, show me what youve got!". Bob went first; as he began to sketch his design on the white board Tawny said, "Lets get to the point Bob, show me how you handled updating the list of con- tact objects." Bob quickly drew a code fragmenton the board: Contact I) ca = new Contact[10]; while ( x < 10 ) { II make 10 contact objects calx) new Contact()i x = x + 1; II do complicated Contact list updating stuff with ca "Tawny r know were tight on memory,but your spec said that we had to be able to accessindividualcontact informationfor all ten allowablecontacts, this was the best scheme I couldcookup", said Bob. Kent was next, already imagining coconut cocktails with Tawny, "Bob,"he said, "your solutions a bit kludgy dont you think?" Kent smirked,"Take a look at thisbaby": Contact. refc; while ( x < 10 ) { II make 10 contact. objects refe = new Cont.act()i x = x + 1; I II do complicated Contact list updating stuff with rete "I saved a bunch of reference variables worth ofmemory,Bob-o-rino, so put away yoursunscreen", mocked Kent "Not so fast Kent!", said Tawny, "youve saved a little memory, butBobs coming with me..Why did Tawny choose Bobs method over Kents, when Kents used Jess memory? you are here t 67
  • 91. www.it-ebooks.infoexercise solutions class Books { Exercise Solutions String title; String autbor; class BooksTestDrive ( public static void main{String I) args) Books II myBooks = new Books(3); int x = 0: A myBooks[O] :: ntw 9ooksO; IUrnanber: We hGvt toCode Magnets: myBooks[1] :: ntw BooksO: actuclily InQJc.e the BooI<s myBooks[2] :: new BooksO: objects I ~~----=- ----lclass TestArrays myBooksIO].title = uThe Grapes of Java; myBooksll] .title = "The Java Gatsby·; pUblic static void main(String () args) { myBooks[2].title = NThe Java Cookbook; int [) index = new int{4]: myBooks[O].author = Nbob; index[O) I: myBooks[l].author = Nsue"; Lndex] 1) 3: myBooks[2].author = "ian"; index[ 2) 0: while (x < 3) { index(3) 2; System.out.print(myBoOks(x).title)i String (] islands = new String[4]: System.out.print(" by ")j system.out.println(myBooks[x).author); islandslO] "Bermuda": x e X + 1; islandsjl] = "Fiji"; islands(2] "Azores H : islands{3] "Cozumel"; int y = 0: class Hobbits { int ref; String name: while (y < 4) { public static void main{String I) args) { ref = index(yl; Hobbits () h = ne_w=--H..:.ob::..:b7i:...:t..:.s~(3:....:)~: ~,....,....-, system.out.print("island = H); Int :z :: -1; I Remember: o.rrcys start with System.out.println(islandslref]l; whfle (z ( 2) ( element 0 ) y = y + 1; z = z + 1i ------------ } h[z] = new Hobbits{): B h[z].name = "bilbo; if (z == 1) {} b[z].name = "frodo"j ) if(z==2){ b[z].name = "sam"; } System.out.print(hlz).name + " is a H); system.out.println{"good 80bbit nameH)j68 chapter 3
  • 92. www.it-ebooks.info primitives and references Puzzle Solutions The case of the pilfered referencesclass Triangle Tawny could see that Kents method had a serious double area; flaw. Its true that he didnt use as many reference int height; variables as Bob , but there was no way to access any int length, but the last of the Contact objects that his method cre- public static void main(String [1 argB) { lnt x = 0: ated. With each trip through the loop, he was assign - Triangle [ ] tel = new Trlangle[4]; ing a new object to the one reference variable, so the while ( x • 4 ) { previously referenced object was abandoned on the tel[x] =new Tr/ClllglcQ; heap - unreachable. Without access to nine of the ten ~x].he19ht ~ (x + 1) * 2; objects created, Kents method was useless. talx]. length =x + 4; (The software was 8 huge success atKl the dlent gave Tawny and Bob anextra week talx) . set.Arec(); In Hawa~. wedlike to ~ you that byfinishing this book you too wil get stuff like IhaL) System.out.print(~triangle ~+X+". area"), System.ouLprintln(U - N + talx).area); x=x+1; HeapQulz Objects: Reference Variables: } Int I = x: x - 27; Triangle tS ~ ta[2J; ts[2J.area = 343; hq[O] Syatem.out.print(Ny = U + Y); System .out.println(", tS area " U+ tS.area); } void setArea() { ~ = (height· length) J 2; ~ ;, java Triangle triangle 0, area 4.0 triangle 1. area 10 .0 criangle 2 , area 19 .0 triangle 3 , area 28.0 i = 4, t5 arca = 343 you are here ~ 69
  • 93. www.it-ebooks.info4 methods use Instance variables How Objects Behave State affects behavior, behavior affects state. We know that objects have state and behavior, represented by Instance variables and methods. But until now, we havent looked at how state and behavior are related . We already know that each instance of a class (each object of a particular type) can have its own unique values for its instance variables. Dog A can have a name "Fido" and a weight of 70 pounds. Dog B Is"Killer" and weighs 9 pounds. And If the Dog class has a method makeNoiseO,well , dont you think a 70-pound dog barks a bit deeper than the little 9-pounder7 (Assuming that annoying ylppy sound can be considered a bark.) Fortunately, thats the whole point of an object-It has behavior that acts on its state. In other words, methods use /nstllnn vllt/llb/Ift values . Like,"if dog Is less than 14 pounds, make ylppy sound, else..." or "Increase weight by 5~ Lets go chllnge some stat«, this Is a new chap ter 71
  • 94. www.it-ebooks.infoobjects have state and behaviorRetMetMber: a class describes what anobject knows and what at1 object doesA class is the blueprint for an object. When you Songwrite a class, youre describing how theJVM lt1stat1ce title kt10wsshould make an object of that type. You already variables artistknow that every object of that type can have (state)different instance variable values. But what about setTItleOthe methods? Methods setArtlstO does (behavior) playOCa" every object of that type have dlfferetttlMethod behavior?Well... sort cif.*Every instance of a particular class has the samemethods, but the methods can behave differentlybased on the value of the instance variables.The Song class has two instance variables, titleand artist. The playO method plays a song. butthe instance you call playO on will play the songrepresented by the value of the title instancevariable for that instance. So, if you call the playOmethod on one instance youll hear the song"Politik", while another instance plays "Darkstar",The method code, however, is the same.void pla.y ( ) { soundPlayer.playSound(title);} SongSong t2 = new Song(); 83 .play () ;t2.setArtist("Travis");t2.setTitle("Sing");Song s3 = new Song(); I C-illi~ playO 0lI this iflSta~tes3.sstArtist("Sex Pistols"); will t4lASe "My W;Y:: to play.s3 . setTi tie ("My Way") ; (blAt PI~ the ~r.ab-a ~d·Yes. another stunningly clearanswerl72 chapter 4
  • 95. www.it-ebooks.info methods use instance variables esize affects the barkAtlD3cIJ Dogs bark is different from a big Dog s bark. og class has an instance variable size, that the me th od uses to decide what kind of bark sound Dog Dog ( s i ze ; size name ;;: =: ng name; bark() _:0 ba r k () { :.f (size> 60) System .out.println("Wooof! Wooof!"}; el s e i f (size> 14) { System ,out.println("RUff! Ruff!"); else ( System.out.println("Yip! Yip!-);~: = s s DogTestDrive { 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 = new Dog() ; 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 int W value 3 are delivered into the bark method. P~,"d_~," l:>. A V The bits land in the numOfBarks parameter (an int-stzec variable). ~ in void bark (int numO arks) { Use the numOfBarks while (numOfBarks > 0) { O parameter as a variable in the 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 value to the caller, such as: ~ giveSecret () return 42; declare a method to return a value, you must a 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 say II give back, you tter give back! t - life. giveSecret () ; giveSec et () { return 42- t,nis "~ ~it. } . tJ ill 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 = new T8Ststuff()i t.takeTwo(12, 34); lnt z = x void 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 is rr + z);76 chapter 4
  • 99. www.it-ebooks.info methods use instance variables Java is pass...by...value. = That tMea"s pass"by"copy. ----- int x = 7; int O the valuean7.in~nd assign7it Declare The bit pattern for goes into the variable named x.void go(int z){ }~ int A iii Declare a method with an int parameter named z. f t Call the goO method, passing W the variable x as the argument. The bits in x are copied, and the copy lands in z. int int foo.go(x) ; void qo(int z){ } liteVb dots,,f. ,~ ~ d~. • f thci 113 4:1 ., ~. . . . a.,.d ~~t~g L. j J.. dft":-: tf A V Change the value of z inside the method. The value of x doesnt change! The argument ><: ·.. · · · · ···0···.. · · · · ... passed to the z parameter was int void go(int z){ z = 0; mt --- only a copy of x. The method cant change the bits that were in the calling variable x. } you are here. 77
  • 100. www.it-ebooks.infoarguments and return values Q:What happens Ifthe argument you want to Reminder: Java pass Is an object Instead of II primitive? cares about type! A: Youll learn more about this In later chapters, but you already know the answer. Java passes You cant return a Giraffe when the return type Is declared everything by value. EverythIng. But... value means as a Rabbit. Same thing with bits Inside the vcrtable. And remem ber,you dont parameters. You cant pass a stuff objects Into variables; the variable Is a remote Giraffe Into a method that control-a reference to an object. So If you pass a takes a Rabbit. reference to an object into a method, youre passing a copy of the remote control. Stay tuned, though, well have lots more to say about this. Q..: Can a method declare multiple return values? Or Is there some way to return more than one value? • Classes define what an object knows and whal an object does. A: Sort of. A method can dec lare onIy one return value. BUT... If you want to return, say, three int values, • Things an object knows are its Instance variables (state). then the declared return type can be an Int orray. • Things an object does are its methods (behavior). Stuff those lnts into the array,and pass It on back. Its a little more involved to return multiple values with • Methods can use instance variables so that objects different types; well be talking about that in a later of the same type can behave differently. chapter when ~e talk about ArrayLlst. • Amethod can have parameters, which means you can pass one ormore values in to the method. Q :Do I have to return the exact type , declared? • The number and type ofvalues you pass inmust A.: You can return anything that can be implicitly promoted to that type. So, you can pass a byte where match the order and type of the parameters declared bythe method. an Int Is expected .The caller wont care,because the • Values passed inand out ofmethods can be byte fits Just fine Into the tnt the caller will use for implicitly promoted to a larger Iype orexplicitly cast assigning the result. You must use an explicit cast to a smaller type. when the declared type Is smaller than what youre trying to return. • The value you pass as an argument toa method can be a literal value (2, c, etc.) ora variable of Q..: Do I have to do something with the return the declared parameter type (for example, x where x is an intvariable) . (There are other things you value of a method? can IJust Ignore it? can pass as arguments, but were not there yet.) A :Java doesnt require you to acknowledge a return value. You might want to call a method with • Amethod must declare a retum type.Avoid retum type means the method doesnt return anything. a non-void return type, even though you dont care • Ifa method declares a non-void return type, it must about the return value. In this case, youre calling return a value compatible with the declared return the meth od for the work it does inside the method, rather than for what the method gives returns . In type. Java, you dont have to assign or use the return value.78 chapter 4
  • 101. www.it-ebooks.info methods use instance variables "ttgs you catt do with parameters returtt types_ _... .eve seen how parameters and return types work, its . ElectrlcGultar them to good use: Getters and Setters. If youre into rm al about it, you might prefer to call them ACC610TS brand.Jw.;ifO;OOIrl. But thats a waste of perfectly good syllables. numOfPickups Gc ters and Setters fits the java naming convention. so rockStarUsesl1~,wl:l2 l weIl call them. nd Setters let you, well, get and sa things. Instance van-1r:1_JeS. usually. A Getters sole purpose in life is to send back, getBrandO~az!lnl value, the value of whatever it is that particular Getter selBrandO".-as.:d to be Getting. And by now, its probably no surprise getNumOfPickuPSO1&3, ~ner lives and breathes for the chance to take an argu-.~1De and use it to set the value of an instance variable. setNumOfPickupsO getRockStarUsesltO setRockSlarUsesllO - i.DcJ brand i • numOfPiclcups; .an rockStarUs8sIt; Si:.:-.-nCJ qetBrand () return brand; id s8tBrand (String &Brand) ( brand = &Brand i • getNumOfPickups() { return numOfPickups; :.d setNumOfPickups (int num) numOfPickups = num; .an g8tRockStarusealt() =-~rn rockStarUseslt; setRockStaruseslt(boolean y&sOrNo) { ~tarU8eslt m yesOrNoi you a re he re. 79
  • 102. www.it-ebooks.inforeal developers encapsulate Et1capsulaffot1 00 It or risk hUlMlliatiot atd ridicule.Until this most important moment, wevebeen committing one of the worst 00faux pas (and were not talking minorviolation like showing up without the IBin BYOB). No, were talking Faux Pas witha capital F . And ·P.Our shameful transgression?Exposing our datalHere we are.just humming along withouta care in the world leaving our data outthere for anyoru to see and even touch.You may have already experienced thatvaguely unsettling feeling that comes withleaving your instance variables exposed.Exposed means reachable with the dotoperator, as in:theCat.height : 27;.T hink about this idea of using our remote control to make a direct change to the Cat objects size instance variable. In the hands of the wrong person, a reference variable (remote control) is quite a dangerous weapon. Because whats to prevent: ~l.ts~ Wt. t. eA" 1theCa t. height = 0; 1e-t ~i5. "ayYt".This would be a Bad Thing. We need to public void setBeight (int ht) {build setter methods for all the instancevariables, and find a way to force other if (ht > 9) {code to call the setters rather than access height: ht;the data directly. }80 chapter 4
  • 103. www.it-ebooks.info methods use Instance variables " thedata Java~ed it is that simple to go from This weeks Interview: implementation thats just An Object gets candid about encapsulation. . g for bad data to one HeadFirst Whats the big deal about encapsulation? protects your data and ects your right to modify Object: OK.,you know that dream where youre givinga talk to 500 people when you implementa tion later. suddenly realize- youre TUJkaP. so how exactly do you HeadFirst: Yeah, weve had that one. Its right up there with the one about the Nates the data? With the machine and... no, we wont go there. OK, so you feelnaked. But other than being a little lie and private exposed, is there any danger? ess modifiers. Youre Object Is there any danger? Is there any danger? [St3.I1S laughing] Hey, did all you other . iar with public-we use instances hear that, "Is lhert aT[! danger?" he asks? [falls on the floor laughing] rith every main method. HeadFirst: Whats funny about that? Seems like a reasonable question. res an encapsulation Object: OK, Ill explain it. Its [bWStS out laughing again, uncontrollably] nile of thumb (all stan- disclaimers about rules HeadFirst: Can I get you anything? Water? ~ thumb are in effect): mark Object: Whew! Oh boy. No Im fine, really. Ill be serious. Deep breath. OK, go on. instance variables privati! provide public getters HeadFirst: So what does encapsulation protect you from? setters for access control. Object Encapsulation puts a force-fieldaround my instance variables, so nobody can set you have more design them to, lets say, something inappropriaJ.e. codi ng savvyin Java, you HeadFirst Can you giveme an example? bably do things a little rently, but for now. this Object: Doesnt take a PhD here. Most instance variable values are coded with certainI!!!IlP:oach will keep you safe. assumptions about the boundaries of the values. Like, think of all the things that would break if negative numbers were allowed. Number of bathrooms in an office. Velocity of an airplane. Birthdays.Barbell weight Cellphone numbers. Microwaveoven powet HeadArst: I see what you mean . So how does encapsulation let you set boundaries? Object By forcing other code to go through setter methods. That way, the setter method can validate the parameter and decide if its do-able. Maybe the method will reject it and do nothing, or maybe itll throw an Exception (like if its a null social security number ark getters and for a credit card application), or maybe the method will round the panlITleter sent in to etters pUblic. the nearest acceptable value. The point is,you can do whatever you want in the setter method, whereas you cant do aT[!thing if your instance variables are public. HeadFirst: But sometimes I see setter methods that simplyset the value without check- ing anything: If you have an instance variable that doesnt have a boundary, doesnt that sener method create unnecessary overhead? A performance hit? ·Sodly. Bill forgot to CftCopsulQt~ his Cat class and Object: The point to setters (and getters, too) is that you can c1umge your mind later, ended up wltk Q flat cat . H without breaking any1Jo4y elses code! Imagine if half the people in your com- (overheard at the water cooler). pany used your classwith public instance variables, and one day you suddenly realized, "Oops- theres something I didnt plan for with that value, Im going to have to switchto a setter method." You break everyonescode. The cool thing about encapsulation is that you get to cJumgt)CUT mind. And nobody gets hurt The performance gain from using variables directly is so rniniscule and would rareIy--if DJn- be worth it you are here ~ 81
  • 104. www.it-ebooks.infohow objects behave class GoodDog (Ettcapsulatittg the GoodDogt}oodPog class /I .~.,.t,L private int size; size tJo¥-t. ..)t. . #. ,/ - ~o~ ,, l t. 0 ~ public int getSize () gelSize( } ~ ) r,turn ,i,e, selSize( ) bark( ) t). ~~ alG ~ public void setSi"le (int s) ( Ma¥.t. t..1...~~ ~. ~tt.~ ",CV size = s r void bark () ( i f (size > 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 a particular value can class GoodDogTestDrive I be 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.info methods use instance variablesHow do objects I" a" array have? like any other object. The only difference is . you get to them. In other words, how you get remote control. Lets try calling methods on objects 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 first two array elements. pets [0] = new Dog () ; pets[l] = new Dog(); Call methods on the two Dog objects. 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 variabe t,alll.t IIayia,es, still has a value! class PoorDog ( dttaCt t..,o i~ ~ IIalw. . . / } :l",t. d()t t. a~I~1 integers 0 private 1nt size; k~ private String name; floating points 0.0 What will -tnue: Cd!.,",?? booleans false P)ubliC int getsize () (~ return size; If references 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.info methods use instance variablesfhe differet1ce betwee" it1sfat1ceat1d local variables o Instance variables are declared inside a class but not within a method. Local variables do class 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 variables apply to them? A: e Local variables ~UST be initialized before usel Method parameters are virtually the same as local variables-theyre declared Inside the method (well, technically theyre declared 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 t x; deda ye Yo WI 0 b-1 nl.&t. as $CO¥ as f~ . but theyre still local variables as opposed to Instance variables). But method parameters Lrrt z = x + 3; to ~ it, ~e l.oft<~ tr will never be uninitialized, so youll never get "------- ~~ea~ ol.&-t. a complier error telling you that a parameter variable might not have been initialized. But thats because the compiler will give you an error if you try to invoke a method File Edit Window He! rlke6 without sending arguments that the method % javac Foo.java needs. So parameters are ALWAYS initialized, because the compiler guarantees that Foo.java:4: variable x might methods are always called with arguments not have been initialized that match the parameters declared for the method, and the arguments are assigned int z = x + 3; (automatically) to the parameters. 1 error you ar e he re . 85
  • 108. www.it-ebooks.infoobject equalityColttpari"Q variables (primitives or refere.,ces)Sometimes you want to know if two primitives are the same. Thats easyenough, just use the = operator. Sometimes you want to know if two Use ==to comparereference variables refer to a siogle object ~>n the heap. Easy as well, jusl use two 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 for references refer toobjects depends on the type of object. For example, if two different String the 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 again objects 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 those String 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 the operator ==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 ) Foo Foa86 chapter 4
  • 109. www.it-ebooks.info methods use Instance variables Make ,t st,tk Roses are red, this poem ischopPY, passing byvalue . ;s passing by copy, 1 it.Replace our can do better? rJ 8e~ryet. Oh,like yoU d llne with your ow" wn wOld~ dumb secon I thing with YOUl 0 theY/ho e replace forget it. a"d youll never int a " calcArea(7, 12); Whats legal?Given the method below, which KEEP short c " 7;of the method calls listed on theright ore legaltPut a checkmcrk next to the +- RIGHT calcArea (c,15) ; int d " calcArea(S7); calcArea (2,3) ;ones that are legal. (Somestatements are there to assign long 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 and determine whether each ofthese files will compile. If they wont compile. how would you rIX them, and if they do c011lpile. what would he their outputi A Bclass XCopy { class Clock { String time; public static void main(Strinq [) arqs) { void setTime(String t) int orig = 42; time = t j Xcopy 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 ) j String tad = c.getTime()i System.out.println(Utime: u + tod)j88 chapter 4
  • 111. www.it-ebooks.info methods 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 Messages Mixed 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, and Mix4 [) m4a =new Mix4[20lj some of the lines of output might be used int x = 0; more than once. Draw lines connecting the candidate blocks of code with their matching command-line output. while (I I) 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 ·< 9 public iot maybeNew(int index) index < 5 ,! if (I I) ( Mix4 m4 = new Mix4(); x < 20 m4.counter = m4.counter + 1; return 1; index < 5 .~ return 0; x <7 index < 1 x < 19 index < 1 •.90 chapter 4
  • 113. www.it-ebooks.info methods use Instance variables public class Puzzle4 { public static void main(Strinq [] arqs) { int y = I: int x = 0: int result = 0; Your Job is to take code snippets from the pool and place them Into the blank lines while (x < 6) { in the code. You may not use the same snippet more than once, and you wont need to use all the snippets. Your goal is to make a class that will compile and y y * 10; run and produce the output listed. } x = 6; while (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 Mystery Fast TImes in Stim-Clty When Buchanan jammed his twitch-gun into Jais side , Jai froze. Jai knew that Buchanan was as stupid lis he was ugly and he didnt want to spook the big guy. Buchanan ordered Jai into his bosss office, but Jaid done nothing wrong, (lately), so he figured a little chat with Buchanans boss Leveler couldnt be too bad. Hed been moving lots of neural-stimmers in the west side lately and he figured Leveler would be pleased. Black market stimmers werent the best money pump around, but they were pretty harmless. Most of the slim-junkies hed seen tapped out after a while and got back to life, maybe just a little less focused than before. Levelers office was a skungy looking skimmer, but once Buchanan shoved him in, Jai could see that itd been modified to provide aIL the extra speed and armor that a local boss like Leveler could hope for. "Jai my boy", hissed Leveler, "pleasure to see you again". "Likewise Im sure...", said Jai, sensing the malice behind Levelers greeting, "We should be square Leveler, have r missed something?" "Ha! Youre making it look pretty good Jai, your volume is 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, "No way 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, so what?". Jai responded feeling a little queasy. "Neural editions bow I let the stim-junkies know where the next drop will be", explained Leveler. "Trouble is, some srim-junkies stayed straight long enough to figure out how to hack into my WareHousing database." "I need a quick thinker like yourself Jai, to take a look at my StimDrop 137NE class; methods, instance variables, 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!" "Easy big guy", Jai saw his chance, "Im sure you did a top rate job with your access modi .. "Dont tell 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 methods private. 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 comer and take a cruise around the block", suggested Jai. Buchanan reached for his twitch-gun but Levelers 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.info methods 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 return XCopy compiles and runs as it stands I The type 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. returnI can be implicitly promoted. return. argumentprefer my instance variables private. encapsulationreally means make a copy. pass by value setters 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. method definition, , take one argument. setter se help create encapsulation. getter. s£tter, public. privatealways fly solo . return you are here. 93
  • 116. www.it-ebooks.infopuzzle answersPuzzle Solutions Answer to the 5-minute mystery...pUblic class Puzzle4 ( Jai knew that Buchanan wasnt the sharpest public static void main(String [] args) { pencil in the box. When J ai heard Buchanan Puzzle4b [ ] ebs =new Puzzle4b[6J; talk about his code, Buchanan never mentioned int y - 1; his instance variables. Jai suspected that int K .. 0, while Buchanan did in fact handle his methods int result = 0: correctly, he failed to mark his instance variables while (x < 6) ( private. That slip up could have easily cost obs[x) =new PU2zle4b( ): Leveler thousands. obs[x) . ivar =y; y - y .. 10; x=><+1; x = 6, while (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 < 20 if (ivar > 100) { return ivar * factor; index < 5 else { return ivor" (5 - factor); Output x < 7 q java Puzzle4 index < 7 result 543345 x < 19 index < 194 chapter 4
  • 117. www.it-ebooks.info5 writing a program Extra-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 COttt NIts 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, so mi s sthis version works at the command-line. The computerwill prompt you to enter a guess (a cell), that you U type Ent 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). When mi s syouve sent all three Dot Cams to that big 404 in the Ent 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 5• kill ~ e Enter a guess B4 D P4 ts.cc m miss E Enter a guess G3 F hit Enter a guess G4 G I Asi Me.c pm hit o 1 2 3 4 5 6 Enter 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 what uld they be? To answer that, we need more form ation about what the game should do.First, we need to figure out the general flow of thezame. Heres the basic idea: o User starts the game o Game set-up Game creates three Dot Coms o Game places the three Dot ColTlS onto a virtual grid Game play begins hit Repeat the following until there are no more Dot Coms: A Prompt user for a guess 1 W ("2, CO, etc.) . ) remove (0 Check he user guess oga;nst all Dot Coms to look for a hit, Dot Com miss, or kill. Take appropri- ate action : if a hit, delete cell AdiallOfd (A2, D4, etc.). If a kill, delete yt:f""~lb a Dot Com. dt:t.isiOl ~Olt Game finishes Give the user a rating based on display user the number of guesses. score/rating~ ow we have an idea of the kinds of things the rogram needs to do. The next step is figuring ut what kind of objects well need to do theloo·ork. 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 game Nfhe "SitMple Pot CO" .alltea get1tler it1troductiot1It looks like were gonna need at least two classes, aGame class and a DotCom class. But before we build o 6arM 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 Com 1,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 2 3 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 needs a guess, then check to see jf it hitto make a DotCom instance, assign it a location any 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 Game 6ame 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 one SlmpleDofCom guesses it took to sink the DotCom.working, we can scale it up tothe more complex one later. Inl 0localionCells voId mail Intnum01Hl1sIn this simple version, thegame class has no instancevariables, and all the game String 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.98 chapter 5
  • 121. www.it-ebooks.info writing a programPevelopit1Q aClass fhe 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. It t necessarily the way we (or you) write code in the World. In the Real World, of course, youll follow This bar Is displayed on the next set of pages to tell approach your personal preferences, project, or you which part youre working on. For example, if you ployer dictate. We, however, can do pretty much see 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 code D Write prepcode for the methods. (Youll see A form of pseudocode. to help you focus on this in Just a moment.) the logic without stressing about syntax. D Write test code for the methods. test code D Implement the class. A class or methods that will test the real code and 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 is o Express gratitude that we dont have to test _ _- - - -..... al Java code. our so-called learning experience app on To DO.: actuallJve users. smpeDotCOm claSS o write prep code o write test code o write final Java code s,mpeDotCOmoame Flex those dendrftes. cia•• How would you decide whIch class or classes o write prep code to build first, when youre writIng a program? write test code {nol Assuming that all but the tiniest programs need more than one class (If youre following o write final Java code good 00 principles and not having one class do 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: instance illl 0IocaIiooCelIs inlnumOft-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 parameter CONVERT the user guess to an int REPEAT with each of the location cells in the int array II COMPARf the user guess to the location cell IF 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 IF ELSE the user guess did not match, so RETURN "miss" END IF END REPEAT END METHOD METHOD: void setLocotJonCe//$(lnt[] eel/Locations) GET the cell locations as an in! array parameter ASSIGN the cell locations parameter to the cell locations instance variable END METHOD100 chapter 5
  • 123. www.it-ebooks.info writing a program Writing the tttethod hMpletM8ntations lets write the real ...ethod code ttOW, ittd get this puppy worklttg. Before we start coding the methods, though, lets back up and write some code to test the methods. Thats right, were writing the test code 1M/ore theres anything to testl The concept of writing the test code first is one of the 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 ~ XP future) .e erged In the late 90s and has been adopted by Write the test cod e first .•ompanies ranging from the two-person garage shop the Ford Motor Company. The thrust of XP is that the No killer schedules;work regular hours. sterner gets what he wants, when he wants It, even Refactor (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 that velop 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 parameter 2, 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 hits 5. 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 IF ELSE the user guess did not match, so RETURN "Miss" END IF END REPEAT END METHOD102 chapter 5
  • 125. www.it-ebooks.info • writing a program ~relare,..{l? " fest code for the SIIMpiePotCoIM class DiiJjjo ~uestl9ns Q..:Maybe Im missing some- public class SimpleDotComTestDrive ( ....sta"ba-tl. a here, but how exactly do ~....yeDa:.e,o... run a test on something public static void main (S trinq [ ] arqs) ( do~et,t. . . doesnt yet existI1 SimpleDotcom 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}; V J a Y°sJ. 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 ~ ake String 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.evod on ille dot to... objttt, a"d Pdss if. ill if (result. equals ("hi t") ) ( .f<ilr:e ~LAe.11. e : The act of th Inkl n9 th roug h writing) the test code helps. ...britv your thoughts about what " method Itself needs to do. ) soon as your implementation e is done, you already have code Just waiting to validate System.out.println(teStResult);~ Besides,you know If you dont f"in1: 0Ii01: the wf. reslOl t now, YOUll never do It. } (p-aued at" .f<iiledJl) t es always something more esting to do. } ~r.~~,!::~~" ally, write a little test code, write only the Implementa- code you need in order to that test. Then write a little of p••es w Implemem the S1mpleDoteom class, and then later we return to the test class. Looking at our test code e test code and write only above, what else shou Id be added 7 What are we not testi ng in this new implementation code code, that we should be testing for? Write your ideas (or lines of ed to pass that new test. At code) below: test lteratlo n, you TUn all preViously-written tests, so you always prove that your t code additions dont break iously-tested code. you are here ~ 103
  • 126. www.it-ebooks.infoSimpleDotCom classThe checkYourselfO tttethodThere isnt a perfect mapping from prepcode to javacode; youll see a fewadjustments. The prepcode gave us a much better idea of what the code needs todo, and now we have to find the Java code that can do the how.In the back of your mind, be thinking about parts of this code you might want(or need) to improve. The numbers (18 are for things (syntax and languagefeatures) you havent seen yet. Theyre explained on the opposite page.GET the user public String checkYourself(String stringGuess) {guess I) to"veri th &t CONVERT int guess = Integer.parselnt(stringGuess); L- ,--- w L all I•II~ e r9 1-the user guess t oan int String result = "miss"; ( a: - .... e a variable re~lAr" Plat II . " to hold the reslAlt well . . ""ss i" as the detalAlt (.e. we clsslA....e a ......iss")REPEAT witheach ceil in the intarrayIF the user guess • for (int cell : locationCells) {mat chesINCREMENTthe nUI1"lb er ofhits ~ 9d; QlAt o.f th I to te t e <><>p, no "eed ! I e nd i f s 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 ELSE return result; ("Miss", lAllless it was tha"ged to "I-hi;" or "Kill")RETURN t"-. retlAr" the reslAlt bade to } II end me thod the talli"9 ....ethod104 chapter 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 a String to an Int n ~ ++ ... taY1 add I to The post-increment operator ( WhaWtrS th&e (ill ~ Wc*d.s, int __ e",ent by ,). numOfHits++ roIArllOtl·hh++ i.s the sa...t (ill this ~) as sayi,,~ "...... O.f»its ::. """,o.f~hh +" e~rt sli9hUt ...~~ tHitient break statement break; ~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 class S~leDotComTestDrive {Q..: What happens InInteger.pa rselnt(l If the thing you publiC s t a t i c void main (S~ringl] args) {pau Isnt a number? And does It SimpleDotCom 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 ofthe pUblic void setLocationCells(intl] locs) (book, there was an exam pie of a locationCells = 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 of for (int cell : IocationCells)Java there has been a sIngle kind i 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 times I 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 enhancedfor System.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 o correctly, 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 can Java 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 the runs. 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.info writing 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 numOfGuesses row 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 line yo u are here. 107
  • 130. www.it-ebooks.infoSlmpleOotCom class Prepcode for the ShMpleUofCottttatMe class Everythfng happetts Itt Ittal..n There are some things youll have to take on faith. For example. we have one line of prepcode that says, wCET user input from command-line". Let me tell you, thats a little more than we want to implement from scratch right now, But happily, were using 00. And that means you get to ask some otherc1ass/object to do something for you, without worrying about how it does it. When you write prepcode, you should assume that somehoto youll be able to do whatever you need 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 instance COMPUTE a random number between 0 and that 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 instance DECLARE a boolean variable representing the state of the game. named isAhve. SET it to true WHILE 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 instance INCREMENT 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 WHILE END METHOD nl~ogn.itive ttl Dont 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 side of 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-step sequences, logical probem-solving, and analysis. while the right-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 the loop code.• Typically youll write three things when you create a new class: • Use the pre/post increment operator toadd 1 prepcode to a variable (x++;) testcode • Use the pre/post decrement tosubtract 1 from a variable (x-;) real (Java) code • Use Integer .parseInt() to get the int• Prepcode should describe what to do, not how value ofa String. todoit. Implementation comes later. • In teger . parseIn t () works only if the• Use the prepcode tohelp design the test String represents a digit ("0":1,"2", etc.) code. • Use break 10 leave a loop early (i.e. even if• Write test code before you implement the the boolean test condition is still true). methods. How many hits did you get last month? you are here) 109
  • 132. www.it-ebooks.info SimpleDotComGame 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 it GameBelper helper " new GameBelper (); e-r: this is a 1ft/.Ial t1ass role wv~ thdt hasto 0 t.he ...dhod +OY ~d±i,,~ ~ illf l< t.. +OY l""WlIG its part. ~ Java lO<II,MAKE a Simplefzot - SimpleDotCom t:.heDotCom " new SimpleDotcomO ; ~ .....lce the dot tOO>l objet+Com objec tCOMPUTE ,rando m num be rbe tween 0 and . int randomNum = (int) • (Mat:.h.random() ... 5) ;b--lft<1lce a ril,wf"", lI"",beY.toy the tell, and lUe it to ~ke the leU ~ lotdtiOt.! array .firstMAKE an int ar rayWIth the 3 cell loca- let(] locations • (randamNum, randOlllNum+l, rand0lllNUm+2);lions, and thaDotCom. IIstLocationCells (locations) ; . ~ ~,ve L1.. v>e dot tQtI ih lotdtiOtlS (th, C1Yril1)INVOKE seu.oca -[lonCells on the do tcorn ob ject boolean 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 main chap ter 5
  • 133. www.it-ebooks.info writing 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 GameHelper are at the end of this chapter. Make a random number (Math.random() " 5) t Atlau that tOfllts t A... rthoci ok the wit.h Java. Mat.h daS$. An l"rl,arU wt "<id.t tdrlieY, ok a t1ass that we bl/.ilt to Getting user input hell wit}, tnt ~...e. It s ~lItd using the GameHelper qaftt~tlfeY a"d feN haVbl t class set" it yd (fov wilD. ~ String guess = helper.getUserInput("enter a number"); i l A...ethod o..f the ~a...t!+eft"r tlau ~t asks the w.ser ~ot toow.",a"d- li"e i"flt, "ealb it in .»u.- -the 1ISer hits R~Tl).RN, ahli ~Ives batk the ytsl/.I-c clS a Sh-i,,~. you are here) 111
  • 134. www.it-ebooks.infoGameHelper class (Ready-bake)One last class: G-attteHelperWe made the dot CQtn class. Just copy* the code below and compile it into a class named GameHelper. Drop all threeWe made the game class. classes (SimpleDotCom, SimpleDotComGame,All thats left is the helper class- the one with the GameHelper) into the same directory. and make itgetUserInputO method . The code to get command- your working directory.line input is more than we want to explain right now.It opens up way too many topics best left for later. "Ready-IMke(Later, as in chapter 14.) Whenever you see the Bell de logo, youre see- ing code that you have to type as-is and take on faith . Trust it, YouIlleam how that code works later. import java.io.* ; public class GameBelper public String getOserlnput(String prompt) String inputLine = null; System.out.print(prompt +" "); try { Bu£feredReader is = new BufferedReader ( new InputStre~ader(SY8tem.in); inputLine = is.readLine(); if (inputLine. length () == 0) return null; } catch (IOException e) ( System.out.println("IOException: " + e); return inputLine; ) "We know how much you enjoy typing . bul for thoee rare moments When youd mlher do somehlng else , wevil mad II 11111 Ready-bake Code avallable on wlckedlyamart.com.112 chapter 5
  • 135. www.it-ebooks.info writing a programlefs play Whats this? Abug? Gaspl Heres what happens when we Heres what happens when we run it and enter the numbers enter 1.1,1. 1,2,3,4,5,6. Leckin good. Acoltlplete gatMll lltteractlolt Adlfferettf gaIMe h,teractlotl (your mileage may vary) (ylkes) %j a v a SimpleDotComGame %j ava SimpleDotComGame enter a number 1 enter a number 1 miss hit enter a number 2 enter a number 1 miss hit enter a number 3 enter a number 1 miss kill enter a number 4 lou took 3 guesses hit enter a number 5 hit enter a number 6 kill You took 6 guesses Its a cliff-hangerl Will we find the bug? Will we flxthe bug? Staytuned r the next chapter,where we answer these quest! ns and more... And In the meantime,see If you can come up with Ideasfor what went wrong and howto fix It. you are here. 113
  • 136. www.it-ebooks.infofor loopsMore about for loopsWeve covered all the game code for this chapter (but well pick it up againto finish the deluxe version of the game in the next chapter). We didntwant to interrupt your work with some of the details and background info,so we put it back here. WeU start with the details of for loops, and if yourea Ct+ programmer, you can just skim these last few pages ...legular bto"-e.,ha"ced] for loops repeat for 100 reps:What It means In plain English: ~Repeat 100 times ."How the complier sees It: • create a variable I and set It to O. -;. repeat while II siess tha n 100. • at the end of each loop IteratIon, add 1 to IPart One: InitializationUse this part to declare and Initialize a variable to use within the loop body.Youll most often use this variable as a counter.You can actually initialize morethan one variable here, but well get to that later In the book.Part Two: boolean testThis Is where the conditional test goes. Whatever s In there, It must resolve to aboolean value (you know, tru« or flllu) . You can have a test" like (x >= 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.114 chapter 5
  • 137. www.it-ebooks.info writing a program output: sthrough a loop ~ int i = 0; i < 8; i++) tem.out.println(i); enter loop body ++ Pre and Post Increment/Decrement Operator print the value of; The shortcut for adding or subtracting 1 from a variable. X++; Increment Is the same as: (the iteration expression) X = X + 1; They both mean the same thing in this context: "add 1 to the current value of x" or ·ncrement x by 1· And: p has only the boolean test; It doesnt have X--;I_!I!!I~-in in it ializat ion or Iteration expression. A while Is the same as: good when you dont know how many times to just want to keep going while some condl- X = X I- I ue. But If you know how many tl mes to loop Of course thats never the whole story.The placement of the • e length of an array, 7 times, etc.), a for loop Is operator (either before or after the variable) can affect the re- t , Heres the loop above rewritten using while: sult. Putting the operator before the variable (for example, ++x), means:!irst, increment x by 1, and then use this new value of x." This only matters when the ++x Is part of some larger expres- . . 11:lt 1. = 0; ~ "lII,<---~, jllitia/i~ ih lJe helv.. 1 d I et. ire dlld sion rather than just in a single statement. int x = 0; int z = ++x; while (i < 8) e lOlAlk produces: )( Is I, z Is 1 System.out.println(i); But putting the ++ after the x give you a different resuIt: i++; ~ , J..;t have to illl Ule lOlA;,k I"e"e,.,f int x " 0; int z c x++; produces: )( Is I, but z Is 01 z gets the value of x and then x is Incremented. you are he re 115
  • 138. www.it-ebooks.info .. enhanced forThe etthattced for loop Beginning with Java 5.0 (Tiger), the Java language has a second kind of Jor loop called the enhanced jM, that makes it easier to iterate over all the elements in an array or other kinds of collections (youll learn about othercollections in the next chapter). Thats really all that the enhanced for gives you-a simpler way to walk through all the elements in the collection, but since its the most common use of afor loop, it was worth adding it to the language. Well revisit the enhancedfor lMp in the next chapter, when we talk about collections that arent arrays.What It means In plain English: "For each element in nameArray, assign theelement to the narnevarlable, and run the body of the loop."How the complier sees It: ... Create a String varIable called name and set It to null. ... Assign the first value In nameArray to name. ... Run the body of the loop (the code block bounded by curly braces). ... Assign the next value In nameArray to name. ... Repeat while there are stili elements In the array.Part One: Iteration variable declarationUse this part to declare and Initialize a variable to use within the loop body, With eachIteration of the loop. this variable will hold a different element from the collection. Thetype of this variable must be compatible with the elements in the arrayl For example,you cant declare an lnt Iteration variable to use with a StrlngU array.Part Two: the actual collectionThis must be a reference to an array or other collection. Again, dont worry about theother non-array kinds of collections yet-youll see them in the next chapter.116 chapter 5
  • 139. www.it-ebooks.info writJng a program converting a String to an int CasthtgiDe quess = Int8qer .parseInt(strinqGuess); prhttftivesThe user types his guess at the command-line, when the game prompts hi m.Thatguess comes In as a String (M2;"0~ etc.) ,and the game passes that String into thecheckYourselfO method.But the cell locations are simply lnts In anarray,and you cant compare an Int to aString.For example, this wont work: long ~ short can be cast to. tx" 2;. (x = num) II horrible explosionl rying to compile that makes the complier but you mightlau gh and mock you: lose something o per a t o r == cannot be applied to int,java .lang .String In chapter 3 we talked about the sizes of the various primitives. and how you