Anda di halaman 1dari 701

Table of Contents

Dedication.............................................................................................................................. 2
What they're saying about Head First..................................................................................... 3
Praise for Head First Java............................................................................................................................................................................................................... 3
Praise for other Head First books co-authored by Kathy and Bert................................................................................................................................................ 3
Other related books from O'Reilly.................................................................................................................................................................................................. 3
Intro....................................................................................................................................... 7
Who is this book for?....................................................................................................................................................................................................................... 7
We know what you're thinking........................................................................................................................................................................................................ 7
And we know what your brain is thinking...................................................................................................................................................................................... 7
Metacognition: thinking about thinking......................................................................................................................................................................................... 7
Here's what WE did:........................................................................................................................................................................................................................ 7
Here's what YOU can do to bend your brain into submission........................................................................................................................................................ 7
What you need for this book:.......................................................................................................................................................................................................... 7
Last-minute things you need to know:............................................................................................................................................................................................ 7
Technical Editors............................................................................................................................................................................................................................. 7
Other people to credit:..................................................................................................................................................................................................................... 7
Just when you thought there wouldn't be any more acknowledgements....................................................................................................................................... 7
Chapter 1. Breaking the Surface............................................................................................ 19
Section 1.1. The Way Java Works.................................................................................................................................................................................................. 20
Section 1.2. What you'll do in Java................................................................................................................................................................................................ 21
Section 1.3. A very brief history of Java........................................................................................................................................................................................ 22
Section 1.4. Sharpen your pencil................................................................................................................................................................................................... 23
Section 1.5. Sharpen your pencil answers..................................................................................................................................................................................... 24
Section 1.6. Code structure in Java............................................................................................................................................................................................... 25
Section 1.7. Anatomy of a class...................................................................................................................................................................................................... 26
Section 1.8. Writing a class with a main........................................................................................................................................................................................ 27
Section 1.9. What can you say in the main method?.................................................................................................................................................................... 28
Section 1.10. Looping and looping and......................................................................................................................................................................................... 29
Section 1.11. there are no Dumb Questions.................................................................................................................................................................................. 30
Section 1.12. Conditional branching.............................................................................................................................................................................................. 31
Section 1.13. Coding a Serious Business Application.................................................................................................................................................................... 32
Section 1.14. Monday morning at Bob's........................................................................................................................................................................................ 33
Section 1.15. Phrase-O-Matic........................................................................................................................................................................................................ 35
Section 1.16. Fireside Chats........................................................................................................................................................................................................... 36
Section 1.17. Exercise: Code Magnets........................................................................................................................................................................................... 38
Section 1.18. Exercise: BE The compiler....................................................................................................................................................................................... 39
Section 1.19. JavaCross 7.0........................................................................................................................................................................................................... 40
Section 1.20. Mixed Messages....................................................................................................................................................................................................... 41
Section 1.21. Pool Puzzle................................................................................................................................................................................................................ 42
Section 1.22. Exercise Solutins: Code Magnets:........................................................................................................................................................................... 43
Chapter 2. A Trip to Objectville............................................................................................. 45
Section 2.1. Chair Wars................................................................................................................................................................................................................. 46
Section 2.2. Brain Power................................................................................................................................................................................................................ 51
Section 2.3. Making your first object............................................................................................................................................................................................ 54
Section 2.4. Making and testing Movie objects............................................................................................................................................................................. 55
Section 2.5. Quick! Get out of main!............................................................................................................................................................................................. 56
Section 2.6. Running the Guessing Game..................................................................................................................................................................................... 58
Section 2.7. Who am I?.................................................................................................................................................................................................................. 63
Chapter 3. Know Your Variables........................................................................................... 67
Section 3.1. Declaring a variable................................................................................................................................................................................................... 68
Section 3.2. "I'd like a double mocha, no, make it an int."........................................................................................................................................................... 69
Section 3.3. You really don't want to spill that............................................................................................................................................................................. 70
Section 3.4. Back away from that keyword!.................................................................................................................................................................................. 71
Section 3.5. This table reserved..................................................................................................................................................................................................... 71
Section 3.6. Controlling your Dog object...................................................................................................................................................................................... 72
Section 3.7. An object reference is just another variable value.................................................................................................................................................... 73
Section 3.8. There are no Dumb Question.................................................................................................................................................................................... 74
Section 3.9. Java Exposed............................................................................................................................................................................................................. 74
Section 3.10. Life on the garbage-collectible heap........................................................................................................................................................................ 75
Section 3.11. Life and death on the heap....................................................................................................................................................................................... 76
Section 3.12. An array is like a tray of cups................................................................................................................................................................................... 77
Section 3.13. Arrays are objects too............................................................................................................................................................................................... 77
Section 3.14. Make an array of Dogs............................................................................................................................................................................................. 78
Section 3.15. Control your Dog...................................................................................................................................................................................................... 79
Section 3.16. A Dog example......................................................................................................................................................................................................... 80
Section 3.17. Exercise: BE the compiler........................................................................................................................................................................................ 81
Section 3.18. Exercise: Code Magnets........................................................................................................................................................................................... 82
Section 3.19. Pool Puzzle............................................................................................................................................................................................................... 83
Section 3.20. A Heap o' Trouble................................................................................................................................................................................................... 84
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Section 3.21. Five-Minute Mystery............................................................................................................................................................................................... 85
Section 3.22. Exercise Solutions: Code Magnets.......................................................................................................................................................................... 86
Section 3.23. Puzzle Solutions....................................................................................................................................................................................................... 87
Chapter 4. How Objects Behave............................................................................................ 89
Section 4.1. Remember: a class describes what an object knows and what an object does........................................................................................................ 90
Section 4.2. The size affects the bark............................................................................................................................................................................................. 91
Section 4.3. You can send things to a method.............................................................................................................................................................................. 92
Section 4.4. You can get things back from a method.................................................................................................................................................................... 93
Section 4.5. You can send more than one thing to a method....................................................................................................................................................... 94
Section 4.6. there are no Dumb Questions................................................................................................................................................................................... 96
Section 4.7. Reminder: Java cares about type!............................................................................................................................................................................. 96
Section 4.8. Cool things you can do with parameters and return types....................................................................................................................................... 97
Section 4.9. Encapsulation............................................................................................................................................................................................................ 98
Section 4.10. Encapsulating the GoodDog class......................................................................................................................................................................... 100
Section 4.11. How do objects in an array behave?....................................................................................................................................................................... 101
Section 4.12. Declaring and initializing instance variables........................................................................................................................................................ 102
Section 4.13. The difference between instance and local variables............................................................................................................................................ 103
Section 4.14. there are no Dumb Questions................................................................................................................................................................................ 103
Section 4.15. Comparing variables (primitives or references).................................................................................................................................................... 104
Section 4.16. Exercise: BE the compiler...................................................................................................................................................................................... 106
Section 4.17. Who am I?............................................................................................................................................................................................................... 107
Section 4.18. Mixed Messages..................................................................................................................................................................................................... 108
Section 4.19. Pool Puzzle............................................................................................................................................................................................................. 109
Section 4.20. Five Minute Mystery.............................................................................................................................................................................................. 110
Section 4.21. Puzzle Solutions...................................................................................................................................................................................................... 112
Chapter 5. Extra-Strength Methods..................................................................................... 113
Section 5.1. Let's build a Battleship-style game: "Sink a Dot Com"............................................................................................................................................ 114
Section 5.2. First, a high-level design.......................................................................................................................................................................................... 115
Section 5.3. The "Simple Dot Com Game" a gentler introduction.............................................................................................................................................. 116
Section 5.4. Developing a Class.................................................................................................................................................................................................... 117
Section 5.5. BRAIN POWER........................................................................................................................................................................................................ 117
Section 5.6. There are no Dumb Questions................................................................................................................................................................................. 121
Section 5.7. There are no Dumb Questions................................................................................................................................................................................. 124
Section 5.8. Exercise: BE the JVM.............................................................................................................................................................................................. 136
Section 5.9. Exercise: Code Magnets........................................................................................................................................................................................... 137
Section 5.10. Java Cross............................................................................................................................................................................................................... 138
Section 5.11. Exercise Solutions................................................................................................................................................................................................... 140
Chapter 6. Using the Java Library....................................................................................... 143
Section 6.1. In our last chapter, we left you with the cliff-hanger. A bug................................................................................................................................... 144
Section 6.2. So what happened?.................................................................................................................................................................................................. 145
Section 6.3. How do we fix it?...................................................................................................................................................................................................... 146
Section 6.4. Option one is too clunky.......................................................................................................................................................................................... 147
Section 6.5. Option two is a little better, but still pretty clunky................................................................................................................................................. 147
Section 6.6. Wake up and smell the library................................................................................................................................................................................. 150
Section 6.7. Some things you can do with ArrayList................................................................................................................................................................... 151
Section 6.8. there are no Dumb Questions.................................................................................................................................................................................. 153
Section 6.9. Java Exposed............................................................................................................................................................................................................ 153
Section 6.10. Comparing ArrayList to a regular array................................................................................................................................................................ 154
Section 6.11. Comparing ArrayList to a regular array................................................................................................................................................................. 155
Section 6.12. Let's fix the DotCom code...................................................................................................................................................................................... 156
Section 6.13. New and improved DotCom class.......................................................................................................................................................................... 157
Section 6.14. Let's build the REAL game: "Sink a Dot Com"...................................................................................................................................................... 158
Section 6.15. What needs to change?........................................................................................................................................................................................... 159
Section 6.16. Who does what in the DotComBust game (and when)......................................................................................................................................... 160
Section 6.17. Prep code for the real DotComBust class............................................................................................................................................................... 162
Section 6.18. The final version of the Dotcom class.................................................................................................................................................................... 168
Section 6.19. Super Powerful Boolean Expressions.................................................................................................................................................................... 169
Section 6.20. Ready-bake Code................................................................................................................................................................................................... 170
Section 6.21. Ready-bake Code.................................................................................................................................................................................................... 171
Section 6.22. Using the Library (the Java API)........................................................................................................................................................................... 172
Section 6.23. You have to know the full name of the class you want to use in your code.......................................................................................................... 173
Section 6.24. there are no Dumb Questions................................................................................................................................................................................ 173
Section 6.25. there are no Dumb Questions................................................................................................................................................................................ 175
Section 6.26. How to play with the API....................................................................................................................................................................................... 176
Section 6.27. Code Magnets......................................................................................................................................................................................................... 179
Section 6.28. JavaCross 7.0......................................................................................................................................................................................................... 180
Section 6.29. Exercise Solutions.................................................................................................................................................................................................. 181
Section 6.30. JavaCross answers................................................................................................................................................................................................. 182
Chapter 7. Better Living in Objectville................................................................................. 183
Section 7.1. Chair Wars Revisited................................................................................................................................................................................................ 184
Section 7.2. BRAIN POWER........................................................................................................................................................................................................ 185
Section 7.3. there are no Dumb Questions.................................................................................................................................................................................. 194
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Section 7.4. there are no Dumb Questions.................................................................................................................................................................................. 198
Section 7.5. brain power.............................................................................................................................................................................................................. 206
Section 7.6. there are no Dumb Questions................................................................................................................................................................................. 207
Section 7.7. Exercise: Mixed Messages....................................................................................................................................................................................... 210
Section 7.8. Exercise BE the Compiler......................................................................................................................................................................................... 211
Section 7.9. Exercise Solutions: BE the Compiler....................................................................................................................................................................... 213
Chapter 8. Serious Polymorphism....................................................................................... 215
Section 8.1. Did we forget about something when we designed this?........................................................................................................................................ 216
Section 8.2. BRAIN POWER....................................................................................................................................................................................................... 220
Section 8.3. there are no Dumb Questions................................................................................................................................................................................. 243
Section 8.4. Pool Puzzle.............................................................................................................................................................................................................. 250
Section 8.5. Exercise Solutions.................................................................................................................................................................................................... 251
Chapter 9. Life and Death of an Object................................................................................ 253
Section 9.1. The Stack and the Heap: where things live............................................................................................................................................................. 254
Section 9.2. Methods are stacked................................................................................................................................................................................................ 255
Section 9.3. What about local variables that are objects?.......................................................................................................................................................... 256
Section 9.4. there are no Dumb Questions................................................................................................................................................................................. 256
Section 9.5. If local variables live on the stack, where do instance variables live?.................................................................................................................... 257
Section 9.6. The miracle of object creation................................................................................................................................................................................. 258
Section 9.7. Construct a Duck..................................................................................................................................................................................................... 260
Section 9.8. Initializing the state of a new Duck......................................................................................................................................................................... 261
Section 9.9. there are no Dumb Questions.................................................................................................................................................................................. 261
Section 9.10. Using the constructor to initialize important Duck state..................................................................................................................................... 262
Section 9.11. Make it easy to make a Duck.................................................................................................................................................................................. 263
Section 9.12. Doesn't the compiler always make a no-arg constructor for you? No!................................................................................................................. 264
Section 9.13. there are no Dumb Questions................................................................................................................................................................................ 266
Section 9.14. there are no Dumb Questions................................................................................................................................................................................ 267
Section 9.15. Wait a minute... we never DID talk about superclasses and inheritance and how that all fits in with constructors.......................................... 268
Section 9.16. Making a Hippo means making the Animal and Object parts too....................................................................................................................... 270
Section 9.17. How do you invoke a superclass constructor?....................................................................................................................................................... 271
Section 9.18. Can the child exist before the parents?................................................................................................................................................................. 272
Section 9.19. Superclass constructors with arguments............................................................................................................................................................... 273
Section 9.20. Invoking one overloaded constructor from another............................................................................................................................................ 274
Section 9.21. Now we know how an object is born, but how long does an object live?............................................................................................................. 276
Section 9.22. What about reference variables?........................................................................................................................................................................... 278
Chapter 10. Numbers Matter............................................................................................... 291
Section 10.1. MATH methods: as close as you'll ever get to a global method............................................................................................................................ 292
Section 10.2. The difference between regular (non-static) and static methods......................................................................................................................... 293
Section 10.3. What it means to have a class with static methods............................................................................................................................................... 294
Section 10.4. Static methods can't use non-static (instance) variables!.................................................................................................................................... 295
Section 10.5. Static methods can't use non-static methods, either!........................................................................................................................................... 296
Section 10.6. Static variable: value is the same for ALL instances of the class.......................................................................................................................... 297
Section 10.7. Initializing a static variable................................................................................................................................................................................... 299
Section 10.8. static final variables are constants........................................................................................................................................................................ 300
Section 10.9. final isn't just for static variables........................................................................................................................................................................... 301
Section 10.10. there are no Dumb Questions............................................................................................................................................................................. 302
Section 10.11. Math methods...................................................................................................................................................................................................... 304
Section 10.12. Wrapping a primitive........................................................................................................................................................................................... 305
Section 10.13. Before Java 5.0, YOU had to do the work........................................................................................................................................................... 306
Section 10.14. Autoboxing: blurring the line bet ween primitive and object............................................................................................................................. 307
Section 10.15. Autoboxing works almost everywhere................................................................................................................................................................ 308
Section 10.16. But wait! There's more! Wrappers have static utility methods too!................................................................................................................... 310
Section 10.17. And now in reverse... turning a primitive number into a String.......................................................................................................................... 311
Section 10.18. Number formatting.............................................................................................................................................................................................. 312
Section 10.19. Formatting deconstructed.................................................................................................................................................................................... 313
Section 10.20. The percent (%) says, "insert argument here" (and format it using these instructions)................................................................................... 314
Section 10.21. The format String uses its own little language syntax......................................................................................................................................... 315
Section 10.22. The format specifier............................................................................................................................................................................................. 316
Section 10.23. The only required specifier is for TYPE............................................................................................................................................................... 317
Section 10.24. What happens if I have more than one argument?............................................................................................................................................. 318
Section 10.25. So much for numbers, what about dates?........................................................................................................................................................... 319
Section 10.26. Working with Dates............................................................................................................................................................................................. 320
Section 10.27. Moving backward and for ward in time............................................................................................................................................................... 321
Section 10.28. Getting an object that extends Calendar............................................................................................................................................................. 322
Section 10.29. Working with Calendar objects........................................................................................................................................................................... 323
Section 10.30. Highlights of the Calendar API........................................................................................................................................................................... 324
Section 10.31. Even more Statics!... static imports..................................................................................................................................................................... 325
Section 10.32. Lunar Code Magnets........................................................................................................................................................................................... 330
Chapter 11. Risky Behavior.................................................................................................. 333
Section 11.1. Let's make a Music Machine................................................................................................................................................................................... 334
Section 11.2. We'll start with the basics....................................................................................................................................................................................... 335
Section 11.3. First we need a Sequencer...................................................................................................................................................................................... 336
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Section 11.4. Something's wrong!................................................................................................................................................................................................ 336
Section 11.5. What happens when a method you want to call (probably in a class you didn't write) is risky?......................................................................... 337
Section 11.6. Methods in Java use exceptions to tell the calling code, "Some thing Bad Happened. I failed."......................................................................... 338
Section 11.7. The compiler needs to know that YOU know you're calling a risky method........................................................................................................ 339
Section 11.8. An exception is an object of type Exception....................................................................................................................................................... 340
Section 11.9. If it's your code that catches the exception, then whose code throws it?.............................................................................................................. 341
Section 11.10. there are no Dumb Questions.............................................................................................................................................................................. 342
Section 11.11. Flow control in try/catch blocks........................................................................................................................................................................... 344
Section 11.12. Finally: for the things you want to do no matter what........................................................................................................................................ 345
Section 11.13. Sharpen your pencil:Flow Control....................................................................................................................................................................... 346
Section 11.14. Did we mention that a method can throw more than one exception?................................................................................................................ 347
Section 11.15. Exceptions are polymorphic................................................................................................................................................................................. 348
Section 11.16. Multiple catch blocks must be ordered from smallest to biggest........................................................................................................................ 350
Section 11.17. You can't put bigger baskets above smaller baskets............................................................................................................................................. 351
Section 11.18. Sharpen your pencil.............................................................................................................................................................................................. 352
Section 11.19. When you don't want to handle an exception................................................................................................................................................... 353
Section 11.20. Ducking (by declaring) only delays the inevitable.............................................................................................................................................. 354
Section 11.21. Getting back to our music code......................................................................................................................................................................... 356
Section 11.22. Code Kitchen......................................................................................................................................................................................................... 357
Section 11.23. Making actual sound............................................................................................................................................................................................ 358
Section 11.24. Your very first sound player app.......................................................................................................................................................................... 360
Section 11.25. Making a MidiEvent (song data).......................................................................................................................................................................... 361
Section 11.26. MIDI message: the heart of a MidiEvent............................................................................................................................................................. 362
Section 11.27. Anatomy of a message.......................................................................................................................................................................................... 362
Section 11.28. Version 2: Using command-line args to experiment with sounds...................................................................................................................... 364
Section 11.29. Exercise: True or False......................................................................................................................................................................................... 366
Section 11.30. Exercise: Code Magnets....................................................................................................................................................................................... 367
Section 11.31. JavaCross 7.0........................................................................................................................................................................................................ 368
Section 11.32. Exercise Solutions: True or False........................................................................................................................................................................ 369
Section 11.33. Code Magnets....................................................................................................................................................................................................... 369
Section 11.34. JavaCross Answers............................................................................................................................................................................................... 370
Chapter 12. A Very Graphic.................................................................................................. 371
Section 12.1. It all starts with a window...................................................................................................................................................................................... 372
Section 12.2. Your first GUI: a button on a frame...................................................................................................................................................................... 373
Section 12.3. Getting a user event............................................................................................................................................................................................... 375
Section 12.4. Getting a button's ActionEvent............................................................................................................................................................................. 378
Section 12.5. There are no Dumb Questions.............................................................................................................................................................................. 380
Section 12.6. Make your own drawing widget............................................................................................................................................................................ 382
Section 12.7. Because life's too short to paint the circle a solid color when there's a gradient blend waiting for you.............................................................. 385
Section 12.8. BULLET POINTS.................................................................................................................................................................................................. 386
Section 12.9. We can get an event............................................................................................................................................................................................... 387
Section 12.10. Let's try it with TWO buttons.............................................................................................................................................................................. 390
Section 12.11. Java Exposed: This weeks interview: Instance of an Inner Class....................................................................................................................... 398
Section 12.12. There are no Dumb Questions............................................................................................................................................................................. 400
Section 12.13. Code Kitchen........................................................................................................................................................................................................ 404
Section 12.14. Exercise: Who am I?............................................................................................................................................................................................. 412
Section 12.15. Exercise: BE the compiler..................................................................................................................................................................................... 413
Section 12.16. Pool Puzzle............................................................................................................................................................................................................ 414
Section 12.17. Exercise Solutions: Who am I?............................................................................................................................................................................. 415
Section 12.18. Pool Puzzle............................................................................................................................................................................................................ 416
Chapter 13. Work on Your Swing......................................................................................... 417
Section 13.1. Swing components.................................................................................................................................................................................................. 418
Section 13.2. Layout Managers.................................................................................................................................................................................................... 419
Section 13.3. How does the layout manager decide?.................................................................................................................................................................. 420
Section 13.4. The Big Three layout managers: border, flow, and box........................................................................................................................................ 421
Section 13.5. there are no Dumb Questions................................................................................................................................................................................ 430
Section 13.6. Playing with Swing components............................................................................................................................................................................ 431
Section 13.7. there are no Dumb Questions................................................................................................................................................................................ 434
Section 13.8. Code Kitchen.......................................................................................................................................................................................................... 436
Section 13.9. Making the BeatBox............................................................................................................................................................................................... 437
Section 13.10. Exercise: Which code goes with which layout?................................................................................................................................................... 442
Section 13.11. Code Fragments.................................................................................................................................................................................................... 443
Chapter 14. Saving Objects.................................................................................................. 447
Section 14.1. Capture the Beat..................................................................................................................................................................................................... 448
Section 14.2. Saving State............................................................................................................................................................................................................ 449
Section 14.3. Writing a serialized object to a file........................................................................................................................................................................ 450
Section 14.4. Data moves in streams from one place to another................................................................................................................................................ 451
Section 14.5. What really happens to an object when it's serialized?......................................................................................................................................... 452
Section 14.6. But what exactly IS an object's state? What needs to be saved?........................................................................................................................... 453
Section 14.7. If you want your class to be serializable, implement Serializable......................................................................................................................... 455
Section 14.8. There are no Dumb Questions.............................................................................................................................................................................. 458
Section 14.9. Deserialization: restoring an object...................................................................................................................................................................... 459
Section 14.10. What happens during deserialization?............................................................................................................................................................... 460
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Section 14.11. There are no Dumb Questions.............................................................................................................................................................................. 461
Section 14.12. Saving and restoring the game characters........................................................................................................................................................... 462
Section 14.13. The GameCharacter class..................................................................................................................................................................................... 463
Section 14.14. Object Serialization.............................................................................................................................................................................................. 464
Section 14.15. Writing a String to a Text File.............................................................................................................................................................................. 465
Section 14.16. Text File Example: e-Flashcards.......................................................................................................................................................................... 466
Section 14.17. Quiz Card Builder (code outline)......................................................................................................................................................................... 467
Section 14.18. The java.io.File class............................................................................................................................................................................................ 470
Section 14.19. The beauty of buffers............................................................................................................................................................................................ 471
Section 14.20. Reading from a Text File..................................................................................................................................................................................... 472
Section 14.21. Quiz Card Player (code outline)........................................................................................................................................................................... 473
Section 14.22. Parsing with String split()................................................................................................................................................................................... 476
Section 14.23. There are no Dumb Questions............................................................................................................................................................................. 477
Section 14.24. Version ID: A Big Serialization Gotcha............................................................................................................................................................... 478
Section 14.25. Using the serialVersionUID................................................................................................................................................................................. 479
Section 14.26. Code Kitchen....................................................................................................................................................................................................... 480
Section 14.27. Saving a BeatBox pattern..................................................................................................................................................................................... 481
Section 14.28. Restoring a BeatBox pattern............................................................................................................................................................................... 482
Section 14.29. Sharpen your pencil: Can they be saved?........................................................................................................................................................... 483
Section 14.30. Exercise: True or False........................................................................................................................................................................................ 484
Section 14.31. Code Magnets....................................................................................................................................................................................................... 485
Section 14.32. Exercise Solutions............................................................................................................................................................................................... 486
Chapter 15. Make a Connection........................................................................................... 488
Section 15.1. Real-time Beat Box Chat........................................................................................................................................................................................ 489
Section 15.2. Connecting, Sending, and Receiving..................................................................................................................................................................... 491
Section 15.3. Make a network Socket connection....................................................................................................................................................................... 492
Section 15.4. A TCP port is just a number: A 16-bit number that identifies a specific program on the server......................................................................... 493
Section 15.5. To read data from a Socket, use a BufferedReader............................................................................................................................................... 495
Section 15.6. To write data to a Socket, use a PrintWriter......................................................................................................................................................... 496
Section 15.7. DailyAdviceClient code.......................................................................................................................................................................................... 498
Section 15.8. Writing a simple server......................................................................................................................................................................................... 500
Section 15.9. DailyAdviceServer code.......................................................................................................................................................................................... 501
Section 15.10. Writing a Chat Client........................................................................................................................................................................................... 503
Section 15.11. Java has multiple threads but only one Thread class.......................................................................................................................................... 507
Section 15.12. What does it mean to have more than one call stack?........................................................................................................................................ 508
Section 15.13. Every Thread needs a job to do: A method to put on the new thread stack........................................................................................................ 510
Section 15.14. To make a job for your thread, implement the Runnable interface..................................................................................................................... 511
Section 15.15. The Thread Scheduler........................................................................................................................................................................................... 514
Section 15.16. there are no Dumb Questions............................................................................................................................................................................... 517
Section 15.17. Putting a thread to sleep....................................................................................................................................................................................... 518
Section 15.18. Using sleep to make our program more predictable........................................................................................................................................... 519
Section 15.19. Making and starting two threads......................................................................................................................................................................... 520
Section 15.20. What will happen?............................................................................................................................................................................................... 520
Section 15.21. Um, yes. There IS a dark side. Threads can lead to concurrency 'issues'............................................................................................................ 521
Section 15.22. The Ryan and Monica problem, in code.............................................................................................................................................................. 523
Section 15.23. The Ryan and Monica example........................................................................................................................................................................... 524
Section 15.24. We need the makeWithdrawal ( ) method to run as one atomic thing............................................................................................................... 527
Section 15.25. Using an object's lock........................................................................................................................................................................................... 528
Section 15.26. The dreaded "Lost Update" problem................................................................................................................................................................... 529
Section 15.27. Let's run this code................................................................................................................................................................................................ 530
Section 15.28. Make the increment() method atomic. Synchronize it!...................................................................................................................................... 531
Section 15.29. there are no Dumb Questions.............................................................................................................................................................................. 531
Section 15.30. The deadly side of synchronization..................................................................................................................................................................... 533
Section 15.31. New and improved SimpleChatClient.................................................................................................................................................................. 535
Section 15.32. Ready-bake Code: The really really simple Chat Server..................................................................................................................................... 537
Section 15.33. there are no Dumb Questions.............................................................................................................................................................................. 539
Section 15.34. Code Kitchen........................................................................................................................................................................................................ 540
Section 15.35. Exercise: Code Magnets....................................................................................................................................................................................... 541
Section 15.36. Exercise Solutions................................................................................................................................................................................................ 543
Section 15.37. Five-Minute Mystery............................................................................................................................................................................................ 544
Chapter 16. Data structures................................................................................................ 546
Section 16.1. Tracking song popularity on your jukebox............................................................................................................................................................ 547
Section 16.2. Here's what you have so far, without the sort:...................................................................................................................................................... 548
Section 16.3. But the ArrayList class does NOT have a sort() method!..................................................................................................................................... 549
Section 16.4. ArrayList is not the only collection........................................................................................................................................................................ 550
Section 16.5. You could use a TreeSet... Or you could use the Collections.sort() method......................................................................................................... 551
Section 16.6. Adding Collections.sort() to the Jukebox code..................................................................................................................................................... 552
Section 16.7. But now you need Song objects, not just simple Strings....................................................................................................................................... 553
Section 16.8. Changing the Jukebox code to use Songs instead of Strings................................................................................................................................ 554
Section 16.9. It won't compile!.................................................................................................................................................................................................... 555
Section 16.10. The sort() method declaration............................................................................................................................................................................. 555
Section 16.11. Generics means more type-safety......................................................................................................................................................................... 557
Section 16.12. Learning generics................................................................................................................................................................................................. 558
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Section 16.13. Using generic CLASSES....................................................................................................................................................................................... 559
Section 16.14. Using type parameters with ArrayList................................................................................................................................................................. 560
Section 16.15. Using generic METHODS..................................................................................................................................................................................... 561
Section 16.16. Here's where it gets weird.................................................................................................................................................................................... 562
Section 16.17. Revisiting the sort() method................................................................................................................................................................................ 564
Section 16.18. In generics, "extends" means "extends or implements"...................................................................................................................................... 565
Section 16.19. Finally we know what's wrong............................................................................................................................................................................. 566
Section 16.20. The new, improved, comparable Song class....................................................................................................................................................... 567
Section 16.21. We can sort the list, but....................................................................................................................................................................................... 568
Section 16.22. Using a custom comparator................................................................................................................................................................................. 569
Section 16.23. Updating the Jukebox to use a Comparator........................................................................................................................................................ 570
Section 16.24. Sharpen your pencil: Reverse Engineer.............................................................................................................................................................. 570
Section 16.25. Sharpen your pencil: Fill-in-the-blanks.............................................................................................................................................................. 572
Section 16.26. Uh-oh. The sorting all works, but now we have duplicates................................................................................................................................ 573
Section 16.27. We need a Set instead of a List............................................................................................................................................................................ 574
Section 16.28. The Collection API (part of it)............................................................................................................................................................................. 575
Section 16.29. Using a HashSet instead of ArrayList.................................................................................................................................................................. 576
Section 16.30. What makes two objects equal?........................................................................................................................................................................... 577
Section 16.31. How a HashSet checks for duplicates: hashCode() and equals()........................................................................................................................ 578
Section 16.32. The Song class with overridden hashCode() and equals().................................................................................................................................. 579
Section 16.33. there are no Dumb Questions............................................................................................................................................................................. 580
Section 16.34. And if we want the set to stay sorted, we've got TreeSet..................................................................................................................................... 581
Section 16.35. What you MUST know about TreeSet................................................................................................................................................................. 582
Section 16.36. TreeSet elements MUST be comparable............................................................................................................................................................. 583
Section 16.37. We've seen Lists and Sets, now we'll use a Map.................................................................................................................................................. 584
Section 16.38. Finally, back to generics...................................................................................................................................................................................... 585
Section 16.39. Using polymorphic arguments and generics...................................................................................................................................................... 586
Section 16.40. But will it work with ArrayList<Dog> ?.............................................................................................................................................................. 587
Section 16.41. What could happen if it were allowed................................................................................................................................................................. 588
Section 16.42. Wildcards to the rescue........................................................................................................................................................................................ 591
Section 16.43. Alternate syntax for doing the same thing.......................................................................................................................................................... 592
Section 16.44. there are no Dumb Questions.............................................................................................................................................................................. 592
Section 16.45. Exercise: BE the compiler, advanced.................................................................................................................................................................. 593
Section 16.46. Solution to the "Reverse Engineer" sharpen exercise......................................................................................................................................... 594
Section 16.47. Exercise Solution.................................................................................................................................................................................................. 595
Section 16.48. BE the compiler solution..................................................................................................................................................................................... 596
Chapter 17. Release Your Code............................................................................................ 598
Section 17.1. Deploying your application.................................................................................................................................................................................... 599
Section 17.2. Imagine this scenario............................................................................................................................................................................................ 600
Section 17.3. Separate source code and class files...................................................................................................................................................................... 601
Section 17.4. Put your Java in a JAR.......................................................................................................................................................................................... 602
Section 17.5. Running (executing) the JAR................................................................................................................................................................................ 603
Section 17.6. Put your classes in packages!................................................................................................................................................................................ 604
Section 17.7. Preventing package name conflicts....................................................................................................................................................................... 605
Section 17.8. Compiling and running with packages.................................................................................................................................................................. 607
Section 17.9. The -d flag is even cooler then we said.................................................................................................................................................................. 608
Section 17.10. Making an executable JAR with packages.......................................................................................................................................................... 609
Section 17.11. So where did the manifest file go?........................................................................................................................................................................ 610
Section 17.12. Java Web Start...................................................................................................................................................................................................... 614
Section 17.13. The .jnlp file.......................................................................................................................................................................................................... 616
Section 17.14. Steps for making and deploying a Java Web Start app........................................................................................................................................ 617
Section 17.15. What's First?......................................................................................................................................................................................................... 618
Section 17.16. True or False......................................................................................................................................................................................................... 619
Section 17.17. Summary-Cross 7.0.............................................................................................................................................................................................. 620
Chapter 18. Distributed Computing.................................................................................... 624
Section 18.1. Method calls are always bet ween two objects on the same heap......................................................................................................................... 625
Section 18.2. What if you want to invoke a method on an object running on another machine?............................................................................................. 626
Section 18.3. Object A, running on Little, wants to call a method on Object B, running on Big............................................................................................... 627
Section 18.4. But you can't do that.............................................................................................................................................................................................. 627
Section 18.5. The role of the 'helpers'......................................................................................................................................................................................... 629
Section 18.6. Java RMI gives you the client and service helper objects!.................................................................................................................................... 631
Section 18.7. How does the client get the stub object?............................................................................................................................................................... 637
Section 18.8. How does the client get the stub class?................................................................................................................................................................. 638
Section 18.9. Be sure each machine has the class files it needs................................................................................................................................................. 639
Section 18.10. Sharpen your pencil: What's First?..................................................................................................................................................................... 640
Section 18.11. Yeah, but who really uses RMI?........................................................................................................................................................................... 641
Section 18.12. What about Servlets?........................................................................................................................................................................................... 642
Section 18.13. A very simple Ser vlet........................................................................................................................................................................................... 644
Section 18.14. HTML page with a link to this servlet................................................................................................................................................................. 644
Section 18.15. There are no Dumb Questions............................................................................................................................................................................. 645
Section 18.16. Just for fun, let's make the Phrase-O-Matic work as a servlet............................................................................................................................ 646
Section 18.17. Phrase-O-Matic code, servlet-friendly................................................................................................................................................................. 647
Section 18.18. Enterprise JavaBeans: RMI on steroids.............................................................................................................................................................. 648
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Section 18.19. For our final trick... a little Jini........................................................................................................................................................................... 649
Section 18.20. Adaptive discovery in action............................................................................................................................................................................... 650
Section 18.21. Self-healing net work in action............................................................................................................................................................................ 652
Section 18.22. Final Project: the Universal Service browser...................................................................................................................................................... 653
Section 18.23. How it works:....................................................................................................................................................................................................... 654
Section 18.24. The classes and interfaces:.................................................................................................................................................................................. 656
Section 18.25. Sharpen your pencil............................................................................................................................................................................................. 661
Section 18.26. Congratulations!.................................................................................................................................................................................................. 665
Appendix A. Final Code Kitchen.......................................................................................... 666
Section A.1. Final BeatBox client program.................................................................................................................................................................................. 667
Appendix B. The Top Ten Topics that almost made it into the Real Book............................. 676
Section B.1. #10 Bit Manipulation............................................................................................................................................................................................... 677
Section B.2. #9 Immutability...................................................................................................................................................................................................... 678
Section B.3. #8 Assertions........................................................................................................................................................................................................... 679
Section B.4. #7 Block Scope........................................................................................................................................................................................................ 680
Section B.5. #6 Linked Invocations............................................................................................................................................................................................. 681
Section B.6. #5 Anonymous and Static Nested Classes............................................................................................................................................................. 682
Section B.7. #5 Anonymous and Static Nested Classes, continued........................................................................................................................................... 683
Section B.8. #4 Access Levels and Access Modifiers (Who Sees What).................................................................................................................................... 684
Section B.9. #4 Access Levels and Access Modifiers, cont......................................................................................................................................................... 684
Section B.10. #3 String and StringBuffer/StringBuilder Methods............................................................................................................................................ 686
Section B.11. #2 Multidimensional Arrays.................................................................................................................................................................................. 687
Section B.12. And the number one topic that didn't quite make it in... #1 Enumerations (also called Enumerated Types or Enums).................................. 688
Section B.13. Using "if" and "switch" with Enums..................................................................................................................................................................... 689
Section B.14. #1 Enumerations, completed................................................................................................................................................................................ 690
Section B.15. Five-Minute Mystery: A Long Trip Home............................................................................................................................................................. 691
Section B.16. Five-Minute Mystery Solution.............................................................................................................................................................................. 692
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java

8econd Edition
ly Kaihy Siciia anu Bcii Baics
Coyiighi 200S, 200 ly O`Rcilly Mcuia, Inc. All iighis icscivcu.
Piinicu in ihc Uniicu Siaics ol Amciica.
Pullishcu ly O`Rcilly Mcuia, Inc., 100 Giavcnsicin Highway Noiih, Sclasiool, CA 9472.
O`Rcilly Mcuia looIs may lc uichascu loi cuucaiional, lusincss, oi salcs iomoiional usc.
Onlinc cuiiions aic also availallc loi mosi iiilcs salaii.oicilly.com). Ioi moic inloimaiion,
coniaci oui coioiaic/insiiiuiional salcs ucaiimcni: S00) 99S-99SS oi coioiaicCoicilly.com.
Editor: MiIc IouIiucs
Cover Designer: Euic Iiccuman
nterior Designers: Kaihy Siciia anu Bcii Baics
Printing History:
May 200S: Iiisi Euiiion.
Icliuaiy 200: Scconu Euiiion.
You mighi wani io icI u a coy ol boL cuiiions... loi youi Iius. ThinI cBay)
Thc O`Rcilly logo is a icgisicicu iiaucmaiI ol O`Rcilly Mcuia, Inc. ]ava anu all ]ava-lascu
iiaucmaiIs anu logos aic iiaucmaiIs oi icgisicicu iiaucmaiIs ol Sun Miciosysicms, Inc., in ihc
Uniicu Siaics anu oihci couniiics. O`Rcilly Mcuia, Inc. is inuccnucni ol Sun Miciosysicms.
Many ol ihc ucsignaiions uscu ly manulaciuicis anu scllcis io uisiinguish ihcii iouucis aic
claimcu as iiaucmaiIs.
Whcic ihosc ucsignaiions acai in ihis looI, anu O`Rcilly Mcuia, Inc. was awaic ol a iiaucmaiI
claim, ihc ucsignaiions havc lccn iinicu in cas oi iniiial cas.
Whilc cvciy iccauiion has lccn iaIcn in ihc icaiaiion ol ihis looI, ihc ullishci anu ihc
auihois assumc no icsonsililiiy loi ciiois oi omissions, oi loi uamagcs icsuliing liom ihc usc ol
ihc inloimaiion coniaincu hcicin.
In oihci woius, il you usc anyihing in HenJ E:. Jn.n io, say, iun a nuclcai owci lani oi aii
iialhc coniiol sysicm, you`ic on youi own.
ISBN: 09600920S
]M|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
To oui liains, loi always lcing ihcic
ucsiic shaIy cviucncc)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
What they're saying about Head First
]ava icchnology is cvciywhcic-Il you ucvclo soliwaic anu havcn`i lcaincu ]ava, ii`s uchniicly
iimc io uivc in-Hcau Iiisi."
- Scott McNcaly, Sun Microsystcms Chairman, Prcsidcnt and CEO
Bcyonu ihc cngaging siylc ihai uiags you loiwaiu liom Inow-noihing inio cxalicu ]ava waiiioi siaius,
Hcau Iiisi ]ava covcis a hugc amouni ol iaciical maiicis ihai oihci icxis lcavc as ihc uicaucu cxcicisc
loi ihc icauci..." Ii`s clcvci, wiy, hi anu iaciical-ihcic aicn`i a loi ol icxilooIs ihai can maIc ihai claim
anu livc u io ii whilc also icaching you aloui ol|cci sciializaiion anu nciwoiI launch ioiocols. "
- Dr. Dan Russcll, Dircctor oI Uscr Scicnccs and Expcricncc Rcscarch
IBM Almadcn Rcscarch Ccntcr (and tcachcs Artihcial Intclligcncc at StanIord Univcrsity)
Kaihy anu Bcii`s Hcau Iiisi ]ava` iiansloims ihc iinicu agc inio ihc closcsi ihing io a GUI you`vc
cvci sccn. In a wiy, hi mannci, ihc auihois maIc lcaining ]ava an cngaging whai`ic ihcy gonna uo
ncxi.` cxciicncc."
- Warrcn KcuIIcl, SoItwarc Dcvclopmcnt Magazinc
Ii`s lasi, iiicvcicni, lun, anu cngaging. Bc caiclul-you mighi aciually lcain somcihing!"
- Kcn Arnold, Iormcr Scnior Enginccr at Sun Microsystcms
Co-author (with ]amcs Gosling, crcator oI ]ava), Thc ]ava Programming Languagc
Amazon namcu Hcau Iiisi ]ava
a To Tcn Euiioi`s Choicc loi
Comuici BooIs ol 200S
hisi cuiiion)
Soliwaic Dcvclomcni Magazinc namcu
Hcau Iiisi ]ava a hnalisi loi ihc 14ih Annual
]oli Cola/Piouuci Exccllcncc Awaius
...ihc only way io ucciuc ihc woiih ol a iuioiial is io ucciuc how wcll ii icachcs. Hcau Iiisi ]ava cxccls ai
icaching. OK, I ihoughi ii was silly... ihcn I icalizcu ihai I was ihoioughly lcaining ihc ioics as I wcni
ihiough ihc looI."
Thc siylc ol Hcau Iiisi ]ava mauc lcaining, wcll, casici."
- slashdot (honcstpuck's rcvicw)
Hcau Iiisi ]ava is liIc Moniy Pyihon mccis ihc gang ol loui... ihc icxi is lioIcn u so wcll ly uzzlcs
anu sioiics, quizzcs anu cxamlcs, ihai you covci giounu liIc no comuici looI lcloic."
- Douglas Rowc, Columbia ]ava Uscrs Group
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Rcau Hcau Iiisi ]ava anu you will oncc again cxciicncc lun in lcaining...Ioi colc who liIc io lcain
ncw iogiamming languagcs, anu uo noi comc liom a comuici scicncc oi iogiamming lacIgiounu,
ihis looI is a gcm... This is onc looI ihai maIcs lcaining a comlcx comuici languagc lun. I hoc
ihai ihcic aic moic auihois who aic willing io licaI oui ol ihc samc olu molu ol iiauiiional` wiiiing
siylcs. Icaining comuici languagcs shoulu lc lun, noi oncious."
- ]udith Taylor, Southcast Ohio Macromcdia Uscr Group
A lcw uays ago I icccivcu my coy ol Hcau Iiisi ]ava ly Kaihy Siciia anu Bcii Baics. I`m only aii way
ihiough ihc looI, lui whai`s amazcu mc is ihai cvcn in my slcc-uciivcu siaic ihai hisi cvcning, I lounu
myscll ihinIing, OK, |usi onc moic agc, ihcn I`ll go io lcu.`
- ]oc Litton
Il you`ic iclaiivcly ncw io iogiamming anu you aic inicicsicu in ]ava, hcic`s youi looI...Covciing
cvciyihing liom ol|ccis io cicaiing giahical usci inicilaccs GUI), cxcciion ciioi) hanuling io nci-
woiIing socIcis) anu muliiihicauing, cvcn acIaging u youi ilc ol classcs inio onc insiallaiion hlc,
ihis looI is quiic comlcic...Il you liIc ihc siylc...I`m cciiain you`ll lovc ihc looI anu, liIc mc, hoc
ihai ihc Hcau Iiisi sciics will cxanu io many oihci sul|ccis!"
- LinuxQucstions.org
I was ADDICTED io ihc looI`s shoii sioiics, annoiaicu couc, mocI inicivicws, anu liain cxciciscs."
- Michacl Yuan, author, Entcrprisc ]2ME
Praise for Head First Java
Hcau Iiisi ]ava`... givcs ncw mcaning io ihcii maiIciing hiasc `Thcic`s an O Rcilly loi ihai.` I
icIcu ihis u lccausc scvcial oihcis I icscci hau ucsciilcu ii in icims liIc icvoluiionaiy` anu a
ucsciilcu a iauically uillcicni aioach io ihc icxilooI. Thcy wcic aic) iighi... In iyical O`Rcilly
lashion, ihcy`vc iaIcn a scicniihc anu wcll consiucicu aioach. Thc icsuli is lunny, iiicvcicni, ioical,
iniciaciivc, anu liilliani...Rcauing ihis looI is liIc siiiing in ihc scaIcis loungc ai a vicw conlcicncc,
lcaining liom - anu laughing wiih - ccis... Il you wani io UNDERSTAND ]ava, go luy ihis looI."
- Andrcw Pollack, www.thcnorth.com
Il you wani io ]ava, looI no luiihci: wclcomc io ihc hisi GUI-lascu icchnical looI! This
cilccily-cxccuicu, giounu-licaIing loimai uclivcis lcnchis oihci ]ava icxis simly can`i...
Picaic youiscll loi a iiuly icmaiIallc iiuc ihiough ]ava lanu."
- Ncil R. Bauman, Captain & CEO, Gcck Cruiscs (www.GcckCruiscs.com)
Il anyonc in ihc woilu is lamiliai wiih ihc concci ol Hcau Iiisi,` ii woulu lc mc. This
looI is so goou, I`u maiiy ii on TV!"
- Rick Rockwcll, Comcdian
Thc original FOX Tclcvision Who Wants to Marry a Millionairc groom
This siull is so liicIing goou ii maIcs mc wanna WEEP! I`m siunncu."
- Floyd ]oncs, Scnior Tcchnical Writcr/Poolboy, BEA
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
IINAIIY - a ]ava looI wiiiicn ihc way I woulu`a wioic ii il I wcic mc.
Sciiously ihough - ihis looI alsoluicly llows away cvciy oihci soliwaic looI I`vc cvci icau...
A goou looI is vciy uilhculi io wiiic... you havc io iaIc a loi ol iimc io maIc ihings unlolu in a
naiuial, icauci oiicnicu" scqucncc. Ii`s a loi ol woiI. Mosi auihois clcaily aicn`i u io ihc challcngc.
Congiaiulaiions io ihc Hcau Iiisi E]B icam loi a hisi class |ol!
- Wally Flint
I coulu noi havc imagincu a cison smiling whilc siuuying an IT looI! Using Hcau Iiisi E]B
maiciials, I goi a gicai scoic 91%) anu sci a woilu iccoiu as ihc youngcsi SCBCD, 14 ycais."
- AIsah ShaIquat (world's youngcst SCBCD)
Praise for other Head First books co-authored by Kathy and Bert
I lccl liIc a ihousanu ounus ol looIs havc |usi lccn lilicu oll ol my hcau."
- Ward Cunningham, invcntor oI thc Wiki
and Ioundcr oI thc Hillsidc Group
I laughcu, I ciicu, ii movcu mc."
- Dan Stcinbcrg, Editor-in-ChicI, java.nct
My hisi icaciion was io ioll on ihc uooi laughing. Alici I icIcu myscll u, I icalizcu ihai noi only is ihc
looI icchnically accuiaic, ii is ihc casicsi io unucisianu iniiouuciion io ucsign aiicins ihai I havc sccn."
- Dr. Timothy A. Budd, Associatc ProIcssor oI Computcr Scicncc at Orcgon Statc Univcrsity
author oI morc than a dozcn books including C++ [or ]ovo Progrommers
]usi ihc iighi ionc loi ihc gccIcu-oui, casual-cool guiu couci in all ol us. Thc iighi iclcicncc loi iac-
iical ucvclomcni siiaicgics-gcis my liain going wiihoui having io slog ihiough a lunch ol iiicu
sialc iolcssoi-scaI."
- Travis Kalanick, Foundcr oI Scour and Rcd Swoosh
Mcmbcr oI thc MIT TR100
This Hcau Iiisi Scivlcis looI is as goou as ihc Hcau Iiisi E]B looI, which mauc mc laugh
AND gavc mc 97% on ihc cxam!"
- ]cI Cumps, ]2EE consultant, Cronos
Amazon namcu Hcau Iiisi Scivlcis
a To Tcn Euiioi`s Choicc loi
Comuici BooIs ol 2004
hisi cuiiion)
Soliwaic Dcvclomcni Magazinc namcu
Hcau Iiisi Scivlcis anu Hcau Iiisi Dcsign
Paiicins hnalisis loi ihc 1ih Annual
Piouuci Exccllcncc Awaius
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Other related books from OReilly
Ant: The Defnitive Guide
Better, Faster, Lighter Java
Enterprise JavaBeans 3.0
Hibernate: A Developer's Notebook
Java 1.5 Tiger: A Developer's Notebook
Java Cookbook
Java in a Nutshell
Java Network Programming
Java Servlet & JSP Cookbook
Java Swing
JavaServer Faces
JavaServer Pages
Programming Jakarta Struts
Tomcat: The Definitive Guide
Other books in OReillys Head First series
Head First Java
Head First Object-Oriented Analysis and Design (OOA&D)
Head Rush Ajax
Head First HTML with CSS and XHTML
Head First Design Patterns
Head First EJB
Head First PMP
Head First SQL
Head First Software Development
Head First C#
Head First JavaScript
Head First Programming (2008)
Head First Ajax (2008)
Head First Physics (2008)
Head First Statistics (2008)
Head First Ruby on Rails (2008)
Head First PHP & MySQL (2008)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
xxi

how to use this book


I con'f beIieve fhey
puf in o Jovo
progromming bookl
|- l: :-:l--, -- .-:--- l- ---- --:l--
-, -] l|l l-] -l l.l - . ).. ---.--- --'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
how to use this book
xxii intro
Whe |s !h|s |eek fer!
1
Have you done some programming?
2
Do you want to learn Java?
this book is Ior you.
Whe shee|4 pre|z||y |zrk zwzy frem !h|s |eek!
1
s your programming background limited
to HTML only, with no scripting language
experience?
Il you`vc uonc anyihing wiih looing, oi il/ihcn
logic, you`ll uo hnc wiih ihis looI, lui HTMI
iagging alonc mighi noi lc cnough.)
3
ihis looI is loi you.
Are you afraid to try something different?
Would you rather have a root canal than
mix stripes with plaid? Do you believe
than a technical book can't be serious if
there's a picture of a duck in the memory
management section?
Il you can answci ycs" io ol ihcsc:
Il you can answci ycs" io any ol ihcsc:
2
Are you a kick-butt C++ programmer
looking for a reference book?
|--l- --- -.--l- -- l-- --l l- .-l .--l -- l: -- : -- .-]--- -l . .| :--l :.- A- -.l .--l l.l 6- l- 6l - )..' -|.] ----l-- -- ::-::- ~|--1
3
Do you prefer stimulating dinner party
conversation to dry, dull, technical
lectures?
This is NOT a reference
book. Head First Java is a
book designed for learning,
not an encyclopedia of
Java facts.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
the intro
you are here xxiii
How can L. lc a sciious ]ava iogiamming looI."
Whai`s wiih all ihc giahics."
Can I aciually Ien.r ii ihis way."
Do I smcll izza."
Wc knew whz! yeerc !h|nk|n].
Youi liain ciavcs novcliy. Ii`s always scaiching, scanning, wn..r loi
somcihing unusual. Ii was luili ihai way, anu ii hcls you siay alivc.
Touay, you`ic lcss liIcly io lc a iigci snacI. Bui youi liain`s siill
looIing. You |usi ncvci Inow.
So whai uocs youi liain uo wiih all ihc iouiinc, oiuinaiy, noimal
ihings you cncounici. Evciyihing ii nr io sio ihcm liom
inicilciing wiih ihc liain`s .enI |ol-iccoiuing ihings ihai ne.. Ii
uocsn`i loihci saving ihc loiing ihings, ihcy ncvci maIc ii asi ihc
ihis is olviously noi imoiiani" hlici.
How uocs youi liain Irow whai`s imoiiani. Suosc you`ic oui loi
a uay hiIc anu a iigci |ums in lioni ol you, whai hacns insiuc youi
hcau.
Ncuions hic. Emoiions cianI u. CLe.nI u.e.
Anu ihai`s how youi liain Inows...
This must be importantl Don't forget itl
Bui imaginc you`ic ai homc, oi in a liliaiy. Ii`s a salc, waim, iigci-licc
zonc. You`ic siuuying. Gciiing icauy loi an cxam. Oi iiying io lcain
somc iough icchnical ioic youi loss ihinIs will iaIc a wccI, icn uays
ai ihc mosi.
]usi onc iollcm. Youi liain`s iiying io uo you a lig lavoi. Ii`s
iiying io maIc suic ihai ihis ob..ouI, non-imoiiani conicni
uocsn`i cluiici u scaicc icsouiccs. Rcsouiccs ihai aic lciici
scni sioiing ihc ically b. ihings. IiIc iigcis. IiIc ihc uangci ol
hic. IiIc how you shoulu ncvci again snowloaiu in shoiis.
Anu ihcic`s no simlc way io icll youi liain, Hcy liain, ihanI
you vciy much, lui no maiici how uull ihis looI is, anu how
liiilc I`m icgisiciing on ihc cmoiional iichici scalc iighi now, I
ically Jo wani you io Icc ihis siull aiounu."
n4 wc knew whz! yeer |rz|n |s !h|nk|n].
]--- -.- l-:
1
+| : ---l.-l
0reof. OnIy
o37 more duII, dry,
boring poges.
]--- -.- l-:
1
+| :-'l -
--l
:.-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
how to use this book
xxiv intro
So what does it take to Iearn something? First, you have to get it, then make sure
you don't forget it. It's not about pushing facts into your head. Based on the
Iatest research in cognitive science, neurobioIogy, and educationaI psychoIogy,
Iearning takes a Iot more than text on a page. We know what turns your brain on.
8ome of the Head First learning principles:
Make it visual. |mages are far more memorable than words
alone, and make learning much more effective (Up to 89%
improvement in recall and transfer studies). |t 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 tw|ce
as likely to solve problems related to the content.
Use a conversational and personalized style. |n recent studies,
students performed up to 40% better on post-learning tests if the content spoke
directly to the reader, using a first-person, conversational style rather than
taking a formal tone. Tell stories instead of lecturing. Use casual language. Don't
take yourself too seriously. which would you pay more attention to: a stimulating
dinner party companion, or a lectureI
Get the learner to think more deeply. |n 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-
provoking questions, and activities that involve both sides
of the brain, and multiple senses.
Get-and keep-the reader's attention. we've all
had the "| really want to learn this but | can't stay awake past
page one experience. our brain pays attention to things that are out
of the ordinary, interesting, strange, eye-catching, unexpected. Learning a new,
tough, technical topic doesn't have to be boring. our brain will learn much more quickly if it's not.
Touch their emotions. we now know that your ability to remember something is largely
dependent on its emotional content. ou remember what you care about. ou remember when
you feel something. No we're not talking heart-wrenching stories about a boy and his dog.
we're talking emotions like surprise, curiosity, fun, "what the...I , and the feeling of "| Pule!
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 8ob from engineering Joesnt.
y ([jn[ | z qz] Jj,( ]zvz z] z, z ]zn.
doCoIc()
refurn voIue
---: l- :.|| .
--l- -- l-
:----
M| ----l-
:--:-
If reoIIy sucks fo be on
obsfrocf mefhod. You
don'f hove o body.
abstract void roam();
N
- -
-l- -]
'
!
- l -
l . :--
:-|--
Does if moke sense fo
soy Tub IS-A 8ofhroom7
8ofhroom IS-A Tub7 Or is
if o HAS-A reIofionship7
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
the intro
you are here xxv
Il you ically wani io lcain, anu you wani io lcain moic quicIly anu moic uccly,
ay aiicniion io how you ay aiicniion. ThinI aloui how you ihinI. Icain how
you lcain.
Mosi ol us uiu noi iaIc couiscs on mciacogniiion oi lcaining ihcoiy whcn wc wcic
giowing u. Wc wcic e:eeJ io lcain, lui iaicly nuL io lcain.
Bui wc assumc ihai il you`ic holuing ihis looI, you wani io lcain ]ava. Anu you
iolally uon`i wani io scnu a loi ol iimc.
To gci ihc mosi liom ihis looI, oi nr, looI oi lcaining cxciicncc, iaIc
icsonsililiiy loi youi liain. Youi liain on Ln conicni.
Thc iiicI is io gci youi liain io scc ihc ncw maiciial you`ic lcaining
as Rcally Imoiiani. Ciucial io youi wcll-lcing. As imoiiani as
a iigci. Oihciwisc, you`ic in loi a consiani laiilc, wiih youi liain
uoing iis lcsi io Icc ihc ncw conicni liom siicIing.
Mc!zre]n| !|en: !h|nk|n] z|ee! !h|nk|n].
I wonder how I
con frick my broin
info remembering
fhis sfuff...
8o ]ust how DO you get your brain to treat Java like it
was a hungry tiger?
Thcic`s ihc slow, icuious way, oi ihc lasici, moic cllcciivc way. Thc
slow way is aloui shcci icciiiion. You olviously Inow ihai you n.e
allc io lcain anu icmcmlci cvcn ihc uullcsi ol ioics, il you Icc ounuing
on ihc samc ihing. Wiih cnough icciiiion, youi liain says, This uocsn`i eeI
imoiiani io him, lui hc Iccs looIing ai ihc samc ihing o.e. anu o.e. anu o.e., so
I suosc ii musi lc."
Thc lasici way is io uo onything thot increoses broin octivity, csccially uillcicni ,e
ol liain aciiviiy. Thc ihings on ihc icvious agc aic a lig aii ol ihc soluiion,
anu ihcy`ic all ihings ihai havc lccn iovcn io hcl youi liain woiI in youi lavoi.
Ioi cxamlc, siuuics show ihai uiiing woius w.L.r ihc iciuics ihcy ucsciilc as
ooscu io somcwhcic clsc in ihc agc, liIc a caiion oi in ihc louy icxi) causcs
youi liain io iiy io maIcs scnsc ol how ihc woius anu iciuic iclaic, anu ihis
causcs moic ncuions io hic. Moic ncuions hiing moic chanccs loi youi liain
io e ihai ihis is somcihing woiih aying aiicniion io, anu ossilly iccoiuing.
A convcisaiional siylc hcls lccausc colc icnu io ay moic aiicniion whcn ihcy
ciccivc ihai ihcy`ic in a convcisaiion, sincc ihcy`ic cxccicu io lollow along anu
holu u ihcii cnu. Thc amazing ihing is, youi liain uocsn`i ncccssaiily n.e ihai
ihc convcisaiion" is lciwccn you anu a looI! On ihc oihci hanu, il ihc wiiiing
siylc is loimal anu uiy, youi liain ciccivcs ii ihc samc way you cxciicncc lcing
lcciuicu io whilc siiiing in a ioomlul ol assivc aiicnuccs. No nccu io siay awaIc.
Bui iciuics anu convcisaiional siylc aic |usi ihc lcginning.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
how to use this book
xxvi intro
Wc uscu pictures, lccausc youi liain is iuncu loi visuals, noi icxi. As lai as youi
liain`s conccincu, a iciuic ically . woiih 1024 woius. Anu whcn icxi anu iciuics
woiI iogcihci, wc cmlcuucu ihc icxi .r ihc iciuics lccausc youi liain woiIs
moic cllcciivcly whcn ihc icxi is w.L.r ihc ihing ihc icxi iclcis io, as ooscu io in
a caiion oi luiicu in ihc icxi somcwhcic.
Wc uscu repetition, saying ihc samc ihing in uillcicni ways anu wiih uillcicni mcuia
iycs, anu uI.Ie ere, io incicasc ihc chancc ihai ihc conicni gcis coucu coucu
inio moic ihan onc aica ol youi liain.
Wc uscu conccis anu iciuics in unexpected ways lccausc youi liain is iuncu loi
novcliy, anu wc uscu iciuics anu iucas wiih ai lcasi oe emotionoI orer, lccausc
youi liain is iuncu io ay aiicniion io ihc liochcmisiiy ol cmoiions. Thai which
causcs you io eeI somcihing is moic liIcly io lc icmcmlcicu, cvcn il ihai lccling is
noihing moic ihan a liiilc humor, surprise, oi interest.
Wc uscu a cisonalizcu, conversotionoI styIe, lccausc youi liain is iuncu io ay moic
aiicniion whcn ii lclicvcs you`ic in a convcisaiion ihan il ii ihinIs you`ic assivcly
lisicning io a icscniaiion. Youi liain uocs ihis cvcn whcn you`ic .enJ.r.
Wc incluucu moic ihan 0 exercises , lccausc youi liain is iuncu io lcain anu
icmcmlci moic whcn you do ihings ihan whcn you .enJ aloui ihings. Anu wc
mauc ihc cxciciscs challcnging-yci-uo-allc, lccausc ihai`s whai mosi eoIe iclci.
Wc uscu muItipIe Ieorning styIes, lccausc ,ou mighi iclci sic-ly-sic ioccuuics,
whilc somconc clsc wanis io unucisianu ihc lig iciuic hisi, whilc somconc clsc
|usi wanis io scc a couc cxamlc. Bui icgaiulcss ol youi own lcaining iclcicncc,
e.e.,ore lcnchis liom sccing ihc samc conicni icicscnicu in muliilc ways.
Wc incluuc conicni loi both sides o[ your broin, lccausc ihc moic ol youi liain you
cngagc, ihc moic liIcly you aic io lcain anu icmcmlci, anu ihc longci you can
siay locuscu. Sincc woiIing onc siuc ol ihc liain olicn mcans giving ihc oihci siuc
a chancc io icsi, you can lc moic iouuciivc ai lcaining loi a longci ciiou ol
iimc.
Anu wc incluucu stories anu cxciciscs ihai icscni more thon one point o[ view,
lccausc youi liain is iuncu io lcain moic uccly whcn ii`s loiccu io maIc
cvaluaiions anu |uugcmcnis.
Wc incluucu choIIenges, wiih cxciciscs, anu ly asIing questions ihai uon`i always havc
a siiaighi answci, lccausc youi liain is iuncu io lcain anu icmcmlci whcn ii has
io wo.I ai somcihing |usi as you can`i gci youi boJ, in shac ly waiching colc
ai ihc gym). Bui wc uiu oui lcsi io maIc suic ihai whcn you`ic woiIing haiu, ii`s
on ihc ..L ihings. Thai you`re not spending one extro dendrite ioccssing a haiu-io-
unucisianu cxamlc, oi aising uilhculi, |aigon-laucn, oi cxiicmcly icisc icxi.
Wc uscu an S0,20 aioach. Wc assumc ihai il you`ic going loi a PhD in ]ava,
ihis won`i lc youi only looI. So wc uon`i ialI aloui e.e.,L.r. ]usi ihc siull you`ll
aciually ue.
Hcrcs whz! WI 4|4:
P
u
z
z
|eY
i||e
1his is

8f8l 88f00ll
1a-a
spese3
] ge eomgj|e;
Dog
D
og ob
j
e
c
f

size

inf
lide
Dog
8ll P0lk5
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
the intro
you are here xxvii
So, wc uiu oui aii. Thc icsi is u io you. Thcsc iis aic a
siaiiing oini, Iisicn io youi liain anu hguic oui whai woiIs
loi you anu whai uocsn`i. Tiy ncw ihings.
Hcrcs whz! Y00 rzn 4e !e |cn4 yeer
|rz|n |n!e se|m|ss|en.
1
8low down. The more you understand,
the less you have to memorize.
Don`i |usi .enJ. Sio anu ihinI. Whcn ihc
looI asIs you a qucsiion, uon`i |usi sIi io
ihc answci. Imaginc ihai somconc ically .
asIing ihc qucsiion. Thc moic uccly you
loicc youi liain io ihinI, ihc lciici chancc
you havc ol lcaining anu icmcmlciing.
2
Do the exercises. Write your own notes.
Wc ui ihcm in, lui il wc uiu ihcm loi you,
ihai woulu lc liIc having somconc clsc
uo youi woiIouis loi you. Anu uon`i |usi
IooI ai ihc cxciciscs. Usc a pcncil. Thcic`s
lcniy ol cviucncc ihai hysical aciiviiy
whilc lcaining can incicasc ihc lcaining.
3
Read the There are No Dumb Ouestions
Thai mcans all ol ihcm. Thcy`ic noi
oiional siuc-lais-ihcy`ic aii ol ihc coic
conicni! Somciimcs ihc qucsiions aic moic
usclul ihan ihc answcis.
4
Don't do all your reading in one place.
Sianu-u, siicich, movc aiounu, changc
chaiis, changc iooms. Ii`ll hcl youi liain
eeI somcihing, anu Iccs youi lcaining liom
lcing ioo connccicu io a aiiiculai lacc.
5
Make this the last thing you read before
bed. Or at least the last challenging thing.
Paii ol ihc lcaining csccially ihc iianslci
io long-icim mcmoiy) hacns alici you ui
ihc looI uown. Youi liain nccus iimc on
iis own, io uo moic ioccssing. Il you ui in
somcihing ncw uuiing ihai ioccssing-iimc,
somc ol whai you |usi lcaincu will lc losi.
6
Drink water. Lots of it.
Youi liain woiIs lcsi in a nicc laih ol uuiu.
Dchyuiaiion which can hacn lcloic you
cvci lccl ihiisiy) uccicascs cogniiivc lunciion.
7
Talk about it. Out loud.
ScaIing aciivaics a uillcicni aii ol
ihc liain. Il you`ic iiying io unucisianu
somcihing, oi incicasc youi chancc ol
icmcmlciing ii laici, say ii oui louu. Bciici
siill, iiy io cxlain ii oui louu io somconc
clsc. You`ll lcain moic quicIly, anu you mighi
uncovci iucas you haun`i Inown wcic ihcic
whcn you wcic icauing aloui ii.
8
Listen to your brain.
Pay aiicniion io whcihci youi liain is gciiing
ovciloaucu. Il you hnu youiscll siaiiing io sIim
ihc suilacc oi loigci whai you |usi icau, ii`s
iimc loi a licaI. Oncc you go asi a cciiain
oini, you won`i lcain lasici ly iiying io shovc
moic in, anu you mighi cvcn huii ihc ioccss.
10
Type and run the code.
Tyc anu iun ihc couc cxamlcs. Thcn you
can cxciimcni wiih changing anu imioving
ihc couc oi licaIing ii, which is somciimcs
ihc lcsi way io hguic oui whai`s ically
hacning). Ioi long cxamlcs oi Rcauy-laIc
couc, you can uownloau ihc souicc hlcs liom
hcauhisi|ava.com
:-l l: --l .- :l: l
-- ]--- -----.l--

9
Feel somethingl
Youi liain nccus io Inow ihai ihis ne.. Gci
involvcu wiih ihc sioiics. MaIc u youi own
caiions loi ihc hoios. Gioaning ovci a lau
|oIc is .II lciici ihan lccling noihing ai all.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
xxviii intro
You uo ro nccu any oihci ucvclomcni iool, such as an Inicgiaicu
Dcvclomcni Enviionmcni IDE). Wc siiongly iccommcnu ihai you ro
usc anyihing lui a lasic icxi cuiioi uniil you comlcic ihis looI anu
ee.nII, noi uniil alici chaici 16). An IDE can ioicci you liom somc ol
ihc uciails ihai ically maiici, so you`ic much lciici oll lcaining liom ihc
commanu-linc anu ihcn, oncc you ically unucisianu whai`s hacning,
movc io a iool ihai auiomaics somc ol ihc ioccss.
Whz! yee ncc4 fer !h|s |eek:
5lk6 P lkk
ll you dor'l a|ready |ave a 1.5 or realer Java 2 8tandard Ed|t|on 80K (3ollWare
0eve|oprerl K|l), you reed |l. ll you're or L|rux, w|rdoWs, or 3o|ar|s, you car el |l lor lree
lror java.sur.cor (3ur's Weos|le lor Java deve|opers). ll usua||y la|es ro rore l|ar lWo c||c|s
lror l|e ra|r pae lo el lo l|e J23E doWr|oads pae. 0el l|e |alesl non-oera vers|or posled.
T|e 30K |rc|udes everyl||r you reed lo corp||e ard rur Java.
ll you're rurr|r Vac 03 X 10.1, l|e Java 30K |s a|ready |rsla||ed. ll's parl ol 03 X, ard you
dor'l |ave lo do anyrn|ng e|se. ll you're or ar ear||er vers|or ol 03 X, you |ave ar ear||er
vers|or ol Java l|al W||| Wor| lor 95 ol l|e code |r l||s ooo|.
Nole: T||s ooo| |s oased or Java 1.5, oul lor slurr|r|y urc|ear rar|el|r reasors, s|orl|y
oelore re|ease, 3ur rerared |l Java 5, W|||e sl||| |eep|r '1.5 as l|e vers|or ruroer lor l|e
deve|oper's ||l. 3o, |l you see Java 1.5 or Java 5 or Java 5.0, or T|er (vers|or 5's or||ra|
code-rare), rney a|| mean rne same rn|ng. T|ere Was rever a Java 3.0 or 1.0|l jurped lror
vers|or 1.1 lo 5.0, oul you W||| sl||| l|rd p|aces W|ere |l's ca||ed 1.5 |rslead ol 5. 0or'l as|.
(0|, ard jusl lo ra|e |l rore erlerla|r|r, Java 5 ard l|e Vac 03 X 10.1 Were ool| |ver l|e
sare code-rare ol 'T|er, ard s|rce 03 X 10.1 |s l|e vers|or ol l|e Vac 03 you reed lo rur
Java 5, you'|| |ear peop|e la|| aooul 'T|er or T|er. ll jusl rears Java 5 or 03 X 10.1).
T|e 30K does nor |rc|ude l|e AP| documentat|on, ard you reed l|all 0o oac| lo java.sur.
cor ard el l|e J23E APl docurerlal|or. You car a|so access l|e APl docs or||re, W|l|oul
doWr|oad|r l|er, oul l|al's a pa|r. Trusl us, |l's Worl| l|e doWr|oad.
You reed a text ed|tor. v|rlua||y ary lexl ed|lor W||| do (v|, eracs, p|co), |rc|ud|r l|e 0ul ores
l|al core W|l| rosl operal|r syslers. Nolepad, wordpad, TexlEd|l, elc. a|| Wor|, as |or as
you ra|e sure l|ey dor'l apperd a '.lxl or lo l|e erd ol your source code.
0rce you've doWr|oaded ard urpac|ed/z|pped/W|alever (deperds or W||c| vers|or ard lor
W||c| 03), you reed lo add ar erlry lo your PATh erv|rorrerl var|ao|e l|al po|rls lo l|e /o|r
d|reclory |rs|de l|e ra|r Java d|reclory. For exarp|e, |l l|e J230K puls a d|reclory or your
dr|ve ca||ed 'j2sd|1.5.0, |oo| |rs|de l|al d|reclory ard you'|| l|rd l|e 'o|r d|reclory W|ere l|e
Java o|rar|es (l|e loo|s) ||ve. T|a o|r d|reclory |s l|e ore you reed a PATl lo, so l|al W|er you
lype:

al l|e corrard-||re, your lerr|ra| W||| |roW |oW lo l|rd l|e javao corp||er.
Nole: |l you |ave lrouo|e W|l| you |rsla||al|or, We recorrerd you o lo javararc|.cor, ard jo|r
l|e Java-8e|rr|r lorurl Aclua||y, you s|ou|d do l|al W|el|er you |ave lrouo|e or rol.
Note: much of the code from this book is available at wickedlysmart.com
how to use this book
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
the intro
you are here xxix
This is a lcaining cxciicncc, noi a iclcicncc looI. Wc uclilciaicly
siiicu oui cvciyihing ihai mighi gci in ihc way ol Ien.r.r whaicvci ii
is wc`ic woiIing on ai ihai oini in ihc looI. Anu ihc hisi iimc ihiough,
you nccu io lcgin ai ihc lcginning, lccausc ihc looI maIcs assumiions
aloui whai you`vc alicauy sccn anu lcaincu.
We use simple UML-like diagrams.
Il wc`u uscu u.e UMI, you`u lc sccing somcihing ihai IooI liIc ]ava, lui
wiih syniax ihai`s |usi lain w.or. So wc usc a simlihcu vcision ol UMI
ihai uocsn`i conuici wiih ]ava syniax. Il you uon`i alicauy Inow UMI, you
won`i havc io woiiy aloui lcaining ]ava nrJ UMI ai ihc samc iimc.
We don't worry about organizing and packaging your own
code until the end of the book.
In ihis looI, you can gci on wiih ihc lusincss ol lcaining ]ava, wiihoui
siicssing ovci somc ol ihc oiganizaiional oi auminisiiaiivc uciails ol
ucvcloing ]ava iogiams. You w.II, in ihc ical woilu, nccu io Inow-anu
usc-ihcsc uciails, so wc covci ihcm in ucih. Bui wc savc ihcm loi ihc cnu
ol ihc looI chaici 17). Rclax whilc you casc inio ]ava, gcnily.
The end-of-chapter exercises are mandatory; puzzles are
optional. Answers for both are at the end of each chapter.
Onc ihing you nccu io Inow aloui ihc uzzlcs-Le,`.e u..Ie. As in logic
uzzlcs, liain icascis, ciosswoiu uzzlcs, cic. Thc e:e..e aic hcic io hcl
you iaciicc whai you`vc lcaincu, anu you shoulu uo ihcm all. Thc uzzlcs
aic a uillcicni sioiy, anu somc ol ihcm aic quiic challcnging in a u..Ie
way. Thcsc uzzlcs aic mcani loi u..Ie., anu you iolally alicauy Inow il
you aic onc. Il you`ic noi suic, wc suggcsi you givc somc ol ihcm a iiy, lui
whaicvci hacns, uon`i lc uiscouiagcu il you nr` solvc a uzzlc oi il you
simly can`i lc loihcicu io iaIc ihc iimc io woiI ihcm oui.
The 8harpen Your Pencil' exercises don't have answers.
Noi iinicu in ihc looI, anyway. Ioi somc ol ihcm, ihcic . no iighi
answci, anu loi ihc oihcis, aii ol ihc lcaining cxciicncc loi ihc Shaicn
aciiviiics is loi ,ou io ucciuc il anu whcn youi answcis aic iighi. Somc ol
oui ueeJ answcis aic availallc on wicIculysmaii.com)
The code examples are as lean as possible
Ii`s liusiiaiing io wauc ihiough 200 lincs ol couc looIing loi ihc iwo lincs
you nccu io unucisianu. Mosi cxamlcs in ihis looI aic shown wiihin ihc
smallcsi ossillc conicxi, so ihai ihc aii you`ic iiying io lcain is clcai anu
simlc. So uon`i cxcci ihc couc io lc iolusi, oi cvcn comlcic. Thai`s
,ou. assignmcni loi alici you hnish ihc looI. Thc looI cxamlcs aic
wiiiicn sccihcally loi Ien.r.r, anu aicn`i always lully-lunciional.
Izs!-m|ne!c !h|n]s yee ncc4 !e knew:

s|ze
oar|()
eal()
c|aseCal()
w
- -:- . :-|--,
--- .-~cM
|
/-- :--| - A||
- l- .--- ]---
--:|' .:ll-:
+,-+ :+ ,-+:.|
A:ll-: -.-- -l l-
!--::- |----- :--` |--
.-- -.-.l--]' l--'l :
l-- ]--'-- :----: .--l
|-.--- )..
| ]-- :-- l- |---|- |--, l-
.:ll] : -l--.|, .- ]--
--'l |- l-:l] |-: -- :--::~
--- ---|-:, ]-- ---'l |- l-:-
-l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
xxx intro
Icrhn|rz| I4| !ers
]css woiIs ai Hcwlcii-PacIaiu on ihc Scll-
Hcaling Sciviccs Tcam. Shc has a Bachcloi`s
in Comuici Engincciing liom Villanova
Univcisiiy, has hci SCP] 1.4 anu SCWCD
cciiihcaiions, anu is liicially monihs away
liom iccciving hci Masicis in Soliwaic
Engincciing ai Dicxcl Univcisiiy whcw!)
Whcn shc`s noi woiIing, siuuying oi
moioiing in hci MINI Cooci S, ]css can
lc lounu hghiing hci cai loi yain as shc
comlcics hci laicsi Iniiiing oi ciochci
io|cci anylouy wani a hai.) Shc is
oiiginally liom Sali IaIc Ciiy, Uiah no,
shc`s noi Moimon... ycs, you wcic ioo
going io asI) anu is cuiicnily living ncai
Philauclhia wiih hci huslanu, Mcnuia, anu
iwo cais: Chai anu SaIc.
You can caich hci mouciaiing icchnical
loiums ai |avaianch.com.
Valcntin Valcniin Ciciiaz has a Masicis ucgicc
in Inloimaiion anu Comuici Scicncc liom
ihc Swiss Icucial Insiiiuic ol Tcchnology in
Iausannc EPII). Hc has woiIcu as a soliwaic
cngincci wiih SRI Inicinaiional Mcnlo PaiI,
CA) anu as a iincial cngincci in ihc Soliwaic
Engincciing Ialoiaioiy ol EPII.
Valcniin is ihc co-lounuci anu CTO ol Conuiis
Tcchnologics, a comany sccializing in ihc
ucvclomcni ol soliwaic aichiicciuic soluiions.
His icscaich anu ucvclomcni inicicsis
incluuc ascci-oiicnicu icchnologics, ucsign
anu aichiicciuial aiicins, wcl sciviccs, anu
soliwaic aichiicciuic. Bcsiucs iaIing caic ol
his wilc, gaiucning, icauing, anu uoing somc
soii, Valcniin mouciaics ihc SCBCD anu
SCD]WS loiums ai ]avaianch.com. Hc holus
ihc SC]P, SC]D, SCBCD, SCWCD, anu SCD]WS
cciiihcaiions. Hc has also hau ihc ooiiuniiy
io scivc as a co-auihoi loi Whizlals SCBCD
Exam Simulaioi.
Wc`ic siill in shocI liom sccing him in a .)
)-:::. .-l
)-:::.': M
|N|
Cicuii gocs io all, lui misiaIcs aic ihc solc iconsililiiy ol ihc
auihoi...". Docs anyonc ically lclicvc ihai. Scc ihc iwo colc on
ihis agc. Il you hnu icchnical iollcms, ii`s iolally lauli. : )
/.|--l- c--ll.-
/.|--l-': l-
tech editing: Jessica and VaIentin
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
the intro
you are here xxxi
0!hcr pcep|c !e ||zmc:
At O`ReiIIy:
Oui liggcsi ihanIs io Mikc Loukidcs ai O`Rcilly, loi iaIing a
chancc on ihis, anu hcling io shac ihc Hcau Iiisi concci inio
a looI anu e..e). As ihis scconu cuiiion gocs io iini ihcic
aic now hvc Hcau Iiisi looIs, anu hc`s lccn wiih us all ihc way.
To Tim O'Rcilly, loi his willingncss io launch inio somcihing
oIeeI, ncw anu uillcicni. ThanIs io ihc clcvci Kylc Hart loi
hguiing oui how Hcau Iiisi his inio ihc woilu, anu loi launching
ihc sciics. Iinally, io Edic Frccdman loi ucsigning ihc Hcau Iiisi
cmhasizc ihc LenJ" covci.
Our intrepid beto testers ond reviewer teom:
Oui io honois anu ihanIs go io ihc uiiccioi ol oui |avaianch
icch icvicw icam, ]ohanncs dc ]ong. This is youi hlih iimc aiounu
wiih us on a Hcau Iiisi looI, anu wc`ic ihiillcu you`ic siill scaIing
io us. ]cII Cumps is on his ihiiu looI wiih us now anu iclcnilcss
aloui hnuing aicas whcic wc nccucu io lc moic clcai oi coiicci.
Corcy McGlonc, you iocI. Anu wc ihinI you givc ihc clcaicsi
cxlanaiions on |avaianch. You`ll iolally noiicc wc siolc onc oi
iwo ol ihcm. ]ason Mcnard savcu oui icchnical luiis on moic
ihan a lcw uciails, anu Thomas Paul, as always, gavc us cxcii
lcculacI anu lounu ihc sulilc ]ava issucs ihc icsi ol us misscu.
]anc Griscti has hci ]ava chos anu Inows a ihing oi iwo aloui
w...r) anu ii was gicai io havc hci hcling on ihc ncw cuiiion
along wiih long-iimc |avaianchci Barry Gaunt.
Marilyn dc Quciroz gavc us cxccllcni hcl on boL cuiiions ol ihc
looI. Chris ]oncs, ]ohn Nyquist, ]amcs Cubcta, Tcrri Cubcta,
anu Ira Bcckcr gavc us a ion ol hcl on ihc hisi cuiiion.
Sccial ihanIs io a lcw ol ihc Hcau Iiisicis who`vc lccn hcling
us liom ihc lcginning: Angclo Cclcstc, Mikalai Zaikin, anu
Thomas DuII iwuull.com). Anu ihanIs io oui iciiihc agcni, Daviu
Rogcllcig ol SiuuioB lui sciiously, whai aloui ihc o..e iighis.)
:--l
--- - --- )..
---l ------:
M.-|]- -
6-----
)-- N]-:l
|-. B-:--
---] )
w----
1--- c--l.
).--: c--l.
)-.---: - )--
)- c--:
c---] M:6|---
c-: )---:
1--.: |.-|
).:-- M
--.-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
xxxii intro
1es! whcn yee !hee]h! !hcrc wee|4n! |c zny
merc zrknew|c4]cmcn!s'.
More ]ovo technicoI experts who heIped out on the frst edition )in pseudo-rondom order;:
EmiIo Hoii, Michacl Tauiiz, MiIc Gallihugh, Manish Haiwalnc, ]amcs Chcgwiuucn,
Shwcia Maihui, Mohamcu Mazahim, ]ohn Pavciu, ]osch Bih, SIuliai Paianavanich,
Sunil Palicha, Suuuhasaiwa Ghosh, RamIi Siinivasan, Allicu Raoul, Angclo Cclcsic,
MiIalai ZaiIin, ]ohn Zociclici, ]im Plcgci, Baiiy Gauni, anu MaiI Diclcn.
The frst edition puzzIe teom:
DiiI SchiccImann, Maiy ]avaCioss Chamion" Icncis, Rouncy ]. Woouiull, Gavin Bong,
anu ]ason Mcnaiu. ]avaianch is lucIy io havc you all hcling oui.
Other co-conspirotors to thonh:
Paul Whcaton, ihc |avaianch Tiail Boss loi suoiiing ihousanus ol ]ava lcaincis.
Solvcig Haugland, misiicss ol ]2EE anu auihoi ol Daiing Dcsign Paiicins".
Auihois Dori Smith anu Tom Ncgrino (backupbrain.com), loi hcling us navigaic ihc
icch looI woilu.
Oui Hcau Iiisi aiincis in ciimc, Eric Frccman and Bcth Frccman auihois ol Hcau Iiisi
Dcsign Paiicins), loi giving us ihc Bawls io hnish ihis on iimc.
Shcrry Dorris, loi ihc ihings ihai ically maiici.
Brove EorIy Adopters o[ the Heod First series:
]oc Iiiion, Ross P. Golulcig, Dominic Da Silva, honcsiucI, Danny Biomlcig, Sichcn
Ic, Elion Hughcs, Eiic Chiisicnscn, Vulinh Nguycn, MaiI Rau, Aluulhal, Naihan
Olihani, Michacl Biauly, Alcx Daiiow, Michacl Iischci, Saiah Noiiingham, Tim Allcn,
Bol Thomas, anu MiIc Billy ihc hisi).
stiII more acknowIedgements
*The large number of acknowledgements is because we're testing the theory that everyone mentioned in
a book acknowledgement will buy at least one copy, probably more, what with relatives and everything. f
you'd like to be in the acknowledgement of our book, and you have a large family, write to us.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 1
Java takes you to new pIaces. Prom its humble release to the public as the
(wimpy) version l.02, 1ava seduced programmers with its friendly syntax, ob|ect-oriented features,
memory management, and best of all the promise of portability. The lure of write-once/run-
anywhere is |ust too strong. A devoted following exploded, as programmers fought against bugs,
limitations, and, oh yeah, the fact that it was dog slow. 8ut that was ages ago. |f you're |ust starting in
1ava, you're Iucky. Some of us had to walk ve miles in the snow, uphill both ways (barefoot), to
get even the most trivial applet to work. 8ut , why, get to ride the sIeeker, faster, much
more powerfuI 1ava of today.
B
re
a
kin
g
th
e

8
ur
f
a
ce
Come on, fhe wofer's
greofl We'II dive righf in ond
wrife some code, fhen compiIe ond
run if. We're foIking synfox, Iooping
ond bronching, ond o Iook of whof
mokes Jovo so cooI. You'II be
coding in no fime.
1 dive in A Quick Dip
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
2 chapter 1
Ieu 8eI
5heeI Me
Ihc Wzy 1zvz Werks
source code lor
l|e |rleracl|ve
parly |rv|lal|or.
Vel|od Parly()
0 a|oad_0
1 |rvo|espe-
c|a| #1 <Vel|od
java.|ar.0ojecl()>
1 relurr
Create a source
document. Use an
established protocol
(in this case, the 1ava
language).
8eerrc

0emp||cr
0e!pe!
|re4cI
V|r!ez|
Mzrh|ncs
The goal is to write one application {in this
example, an interactive party invitation} and have
it work on whatever device your friends have.
Pun your document
through a source code
compiler. The compiler
checks for errors and
won't let you compile
until it's satised that
everything will run
correctly.

The compiler creates a


new document, coded
into 1ava byreceJe.
Any device capable of
running 1ava will be able
to interpret/translate
this le into something
it can run. The compiled
bytecode is platform-
independent.

our friends don't have


a physical 1ava Machine,
but they all have a
virrunl 1ava machine
(implemented in
software) running inside
their electronic gadgets.
The virtual machine reads
and the bytecode.

the way Java works


Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
dive In A Quick Dip
3
Whz! yee|| 4e |n 1zvz
|rporl java.aWl.,
|rporl java.aWl.everl.,
c|ass Parly {
puo||c vo|d ou||dlrv|le() {
Frare l = reW Frare(),
Laoe| | = reW Laoe|('Parly al T|r's),
8ullor o = reW 8ullor('You oel),
8ullor c = reW 8ullor('3|ool re),
Pare| p = reW Pare|(),
p.add(|),
// rore code |ere...

File Edit Window Help Plead


%javac Party.java
Compile the Pnrry.jnvn
le by running
(the compiler application).
|f you don't have errors,
you'll get a second docu-
ment named Pnrry.clnss
The compiler-generated
Party.class le is made up
of oytecoJes.
Type your source code.
Save as: Pnrry.jnvn
Vel|od Parly()
0 a|oad_0
1 |rvo|espec|a| #1 <Vel|od
java.|ar.0ojecl()>
1 relurr
Vel|od vo|d ou||dlrv|le()
0 reW #2 <C|ass java.aWl.Frare>
3 dup
1 |rvo|espec|a| #3 <Vel|od
java.aWl.Frare()>
Pun the program by
starting the 1ava virtual
Machine (1vM) with the
Pnrry.clnss le. The 1vM
translates the oytecoJe
into something the
underlying platform
understands, and runs
your program.
Compiled code: Pnrry.clnss
File Edit Window Help Swear
%java Party
8eerrc

0emp||cr
0e!pe!
|re4cI
V|r!ez|
Mzrh|ncs

You'll type a source code hle, compile it using the


]avac compiler, then run the compiled bytecode
on a Java virtual machine.
|N-l- l: : --l --.-l l- - . l-l--.| ]--'|| -
--l- --.| :-- - . -----l, -l -- ---, -- -:l
-.-l ]-- l- -l . --| -- -- l .|| l: l--l--`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
4

c
h
a
p
t
e
r

1
h
i
s
t
o
r
y

o
f

J
a
v
a

vcry |r|cf h|s!ery ef 1zvz
1zvz 1.02
250 classes
5lew.
Cute name and logo.
Pun to use. Lots of
bugs. Alers are
the 8ig Thing.
1zvz 1.1
500 classes
A lirrle faster.
More capable, IrienJlier.
8ecoming very eulnr.
8etter GU| code.
1zvz 2
|vcrs|ens 1.2 - 1.1I
2300 classes
Much Insrer.
Can (sometimes) run at
native speeds. Serious,
ewerIul. Comes in three
navors: Micro Ldition (12ML),
Standard Ldition (12SL) and
Lnterprise Ldition (12LL).
8ecomes the lnngunge eI
cheice for new enterprise
(especially web-based) and
mobile applications.
C
l
a
s
s
e
s

i
n

t
h
e

J
a
v
a

s
t
a
n
d
a
r
d

l
i
b
r
a
r
y

1zvz 5.0
|vc rs|ens 1.5 zn4 epI
3500 classes
Mere ewer, ensier re
Jevele wirh.
8esides adding more than a
thousand additional classes,
1ava 5.0 (known as "Tiger)
added ma|or changes to
the language itself, making
it easier (at least in theory)
for programmers and giving
it new features that were
popular in other languages.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
5
int size = 27,
String name = "Fido",
Dog myDog = new Dog{name, size|,
x = size ~ 5,
if {x < l5| myDog.bark{8|,
while {x > 3| {
myDog.play{|,
}
int numList = {2,4,6,8},
System.out.print{"Hello"|,
System.out.print{"Dog: " + name|,
String num = "8",
int z = Integer.parseInt{num|,
try {
readTheFile{"myFile.txt"|,
}
catch{FileNotFoundException ex| {
System.out.print{"File not found."|,
}
+,-+ :+ ,-+:.|
-:|.-- .- -l--- .-.|- -.-- ':--' .- - l l- .|-- i7
Try to guess what each line of code is doing...
(answers are on the next page).
Ieek hew czsy | !
|s !e wr| !c 1zvz.

I see 1ava 2 and 1ava 5.0, but was there a 1ava 3
and 4! And why is it 1ava 5.0 but not 1ava 2.0!
The |oys of marketing... when the version of 1ava
shifted from l.l to l.2, the changes to 1ava were so
dramatic that the marketers decided we needed a whole
new "name, so they started calling it Jnvn 2, even though
the actual version of 1ava was l.2. 8ut versions l.3 and l.4
were still considered Jnvn 2. There never a 1ava 3 or
4. 8eginning with 1ava version l.5, the marketers decided
once again that the changes were so dramatic that a
new name was needed (and most developers agreed), so
they looked at the options. The next number in the name
sequence would be "3, but calling 1ava l.5 Jnvn 3 seemed
more confusing, so they decided to name it Jnvn 5.0 to
match the "5 in version "l.5.
So, the original 1ava was versions l.02 (the first official
release) through l.l were |ust "1ava. versions l.2, l.3, and
l.4 were "1ava 2. And beginning with version l.5, 1ava is
called "1ava 5.0. 8ut you'll also see it called "1ava 5 (without
the ".0) and "Tiger (its original code-name). we have no
idea what will happen with the release...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
why Java is cooI
6 chapter 1
int size = 27,
String name = "Fido",
Dog myDog = new Dog{name, size|,
x = size ~ 5,
if {x < l5| myDog.bark{8|,
while {x > 3| {
myDog.play{|,
}
int numList = {2,4,6,8},
System.out.print{"Hello"|,
System.out.print{"Dog: " + name|,
String num = "8",
int z = Integer.parseInt{num|,
try {
readTheFile{"myFile.txt"|,
}
catch{FileNotFoundException ex| {
System.out.print{"File not found."|,
}
+,-+ :+ ,-+:.|
-:|.-- .- -l--- .-.|- -.-- ':--' .- - l l- .|-- i7
enr werry nbeur wherher yeu unJersrnnJ nny eI rhis yerl
Lverything here is explained in great detail in the book, most
within the rst 40 pages). |f 1ava resembles a language you've
used in the past, some of this will be simple. |f not, don't worry
about it. well et thete...
Ieek hew czsy | !
|s !e wr| !c 1zvz.
-:|.-- . :l-- - :.-.:l--: .-.|- -.-- '-.--' .- - l l- .|-- |-'
-:|.-- . --- l- .-.|- '-]l-' .- -.- l- --- l- -:- '-.--' .- ':--'
:-l-.:l - --- i7 |.|-- - ':--'` .- .::- l l- . .-.|- -.-- ''
|.|-- - ii` : |-:: l.- |-, l-|| l- - l- .- l--:
-- |--- .: |-- .: : --.l-- l.- ?
l-|| l- - l- |.] |-.l--- 1+A1 --.-: l- . -`
l: |--: |- l- -- - l- |-- ~~ ---]l- - ! : --- - l- |--
-:|.-- . |:l - -l---: .-.|- '---|:l', .- -l i,+,|, -l- l- |:l
--l --l +-||-' --.|] .l l- :---.-~|--
--l --l +-||- |-' |l- .|-- - '-.--' : |-'` .l l- :---.-~|--
-:|.-- . :.-.:l-- :l-- .-.|- '---' .- - l l- .|-- - '
:----l l- :l-- - :.-.:l--: ' -l- .- .:l-.| -----: .|--
l-] l- - :---l--.]- l- l- --'-- l-]- :-'l -.-.-l-- l- ---
--. . l-l |- -.-- -]||-ll' |-- .l |-.:l 1/ l- --. l- |-`
--:l - l- -- - l- l-: l- l-]', :- | --:: ]-- :--| l-] -.-] l-:
l: --:l - ---- ]-- - --l l- l- ]-- l-- -'l ---
l- l- -- l-- .|-, --l ||- --l ---' --l .l l- :---.-~|--
|--: |- ---]l- - l- ! : -.l l- - l- 'l-]' -'l ---

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
7
What goes in a
source file?
public class Dog {
}
What goes in a
class?
public class Dog {
void bark() {
}
}
What goes in a
method?
public class Dog {
void bark() {
statement1;
statement2;
}
}
A souicc couc hlc wiih ihc .n.n
cxicnsion) holus onc cIoss uchni-
iion. Thc class icicscnis a .ee
ol youi iogiam, alihough a vciy
iiny alicaiion mighi nccu |usi
a singlc class. Thc class musi go
wiihin a aii ol cuily liaccs.
A class has onc oi moic methods.
In ihc Dog class, ihc borh mcihou
will holu insiiuciions loi how ihc
Dog shoulu laiI. Youi mcihous
musi lc ucclaicu .r.Je a class
in oihci woius, wiihin ihc cuily
liaccs ol ihc class).
r|zss
mc!he4
Wiihin ihc cuily liaccs ol a
mcihou, wiiic youi insiiuciions
loi how ihai mcihou shoulu lc
ciloimcu. Mcihou oJe is lasi-
cally a sci ol siaicmcnis, anu loi
now you can ihinI ol a mcihou
Iinu ol liIc a lunciion oi iocc-
uuic.
0e4c s!rer!erc |n 1zvz
s!z!cmcn!s
Put a class in a source hle.
Put methods in a class.
Put statements in a method.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
8 chapter 1
---- -.:- -
l
- -
-l
-
public class MyFirstApp {
public static void main (String[] args) {
System.out.print(I Rule!);

nz!emy ef z r|zss
Whcn ihc ]VM siaiis iunning, ii looIs loi ihc class you givc ii ai ihc com-
manu linc. Thcn ii siaiis looIing loi a sccially-wiiiicn mcihou ihai looIs
cxacily liIc:
public static void main (String[] args) {
// your code goes here
}
Ncxi, ihc ]VM iuns cvciyihing lciwccn ihc cuily liaccs [ } ol youi main
mcihou. Evciy ]ava alicaiion has io havc ai lcasi onc , anu ai lcasi
onc mcihou noi onc main ci In, |usi onc main ci nI.n.or).
-|: :- ---]---
:.- .::-:: l
l: : .
:|.:: |-`
l- -.-- -
l: :|.::
---- :--|] -.:-
- l- :|.::
|--'|| :--- l:
--- |.l--`
l- --l--- l]-
- --.-: l---':
-- --l--- .|--
l- -.-- -
l: --l-
.-----l: l- l- --l-
1: --l- --:l - --
.- .--.] - l--:, .- l-
.--.] -|| - :.||- '.-:'
l: :.]: --l l- :l.-.- --l-l
|-.-|l: l- :---.-~|--`
l- l-- ]--
-.-l l- --l
---] :l.l----l Mc1
-- - . :--:-|--''
:|-:- -.:- - l- -.- --l-
:|-:- -.:- - l- M]|-:lA :|.::
}
}
a Java cIass
l--'l ----] .--l ------- .-]l- -l ---
l: :.l-- : -:l l- -l ]-- :l.-l-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
9
MyFirstApp.class
Wr| !|n] z r|zss w| !h z
In ]ava, cvciyihing gocs in a class. You`ll iyc youi souicc couc hlc wiih a
.n.n cxicnsion), ihcn comilc ii inio a ncw class hlc wiih a .In cxicnsion).
Whcn you iun youi iogiam, you`ic ically iunning a In.
Running a iogiam mcans iclling ihc ]ava Viiiual Machinc ]VM) io Ioau ihc
Hello class, ihcn siaii cxccuiing iis main() mcihou. Kcc iunning iil all ihc
couc in main is hnishcu."
In chaici 2, wc go uccci inio ihc wholc In ihing, lui loi now, all you nccu io
ihinI is, how do I write ]ovo code so thot it wiII run Anu ii all lcgins wiih main().
Thc main() mcihou is whcic youi iogiam siaiis iunning.
No maiici how lig youi iogiam is in oihci woius, no maiici how many Ine
youi iogiam uscs), ihcic`s goi io lc a main() mcihou io gci ihc lall iolling.
public class MyFirstApp {
public static void main (String[] args) {
System.out.println(I Rule!);
System.out.println(The World);
}
}
Save
MyFirstApp.java
CompiIe
javac MyFirstApp.java
Run
puo||c c|ass VyF|rslApp {
puo||c slal|c vo|d ra|r
(3lr|r[| ars) {
3ysler.oul.pr|rl('l Ru|el),

MyFirstApp.]ava
Vel|od Parly() 0 a|oad_0 1
|rvo|espec|a| #1 <Vel|od
java.|ar.0ojecl()>
1 relurr
Vel|od vo|d
ra|r(java.|ar.3lr|r[|)
0 elslal|c #2 <F|e|d
File Edit Window Help Scream
%java MyFirstApp
I Rule!
The World

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
10 chapter 1
Oncc you`ic insiuc main oi mcihou), ihc lun
lcgins. You can say all ihc noimal ihings ihai you say
in mosi iogiamming languagcs io mohe the computer
do something.
Youi couc can icll ihc ]VM io:

4e semc!h|n]
Statements: declarations, assignments,
method calls, etc.
int x = 3;
String name = Dirk;
x = x * 17;
System.out.print(x is + x);
double d = Math.random();
// this is a comment

4e semc!h|n] z]z|n zn4 z]z|n


Loops: lot and wh|le
while (x > 12) {
x = x -1;
}
for (int x = 0; x < 10; x = x + 1) {
System.out.print(x is now + x);
}

4e semc!h|n] en4cr !h|s ren4| !|en


ranching: |l/else tests
if (x == 10) {
System.out.print(x must be 10);
} else {
System.out.print(x isn't 10);
}
if ((x < 3) & (name.equals(Dirk))) {
System.out.println(Gently);
}
System.out.print(this line runs no matter what);

Lach statement must end in a


semicolon.
x = x + 1;

A single-line comment begins


with two forward slashes.
x = 22;
// this line disturbs me

Most white space doesn't matter.


x = 3 ;

variables are declared with a


name and a type (you'll learn about
all the 1ava tyes in chapter 3).
int weight;
// int, weight

Classes and methods must be


defined within a pair of curly braces.
public void go() {
// amazing code here
}
Whz! rzn yee szy |n !hc mz|n mc!he4!
|--:
-.-:-
:
l
.
l
-
-
-
-
l
:
yn(zy
Jan
statements, Iooping, branching
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
11
Ieep|n] zn4 |eep|n] zn4...
]ava has ihicc sianuaiu looing consiiucis: wL.Ie,
Jo-wL.Ie, anu o.. You`ll gci ihc lull loo scoo laici
in ihc looI, lui noi loi awhilc, so lci`s uo wL.Ie loi
now.
Thc syniax noi io mcniion logic) is so simlc
you`ic iolally aslcc alicauy. As long as somc
conuiiion is iiuc, you uo cvciyihing insiuc ihc
loo bIoI. Thc loo llocI is lounucu ly a aii ol
cuily liaccs, so whaicvci you wani io iccai nccus
io lc insiuc ihai llocI.
Thc Icy io a loo is ihc orJ..ornI e. In ]ava, a
conuiiional icsi is an cxicssion ihai icsulis in a
booIenr valuc -in oihci woius, somcihing ihai is
ciihci true oi [oIse.
Il you say somcihing liIc, Whilc .eC.enIrTLeTub
. .ue, Icc scooing", you havc a clcai loolcan
icsi. Thcic ciihci . icc cicam in ihc iul oi ihcic
.r`. Bui il you wcic io say, Whilc Bob Icc
scooing", you uon`i havc a ical icsi. To maIc
ihai woiI, you`u havc io changc ii io somcihing
liIc, Whilc Bol is snoiing..." oi Whilc Bol is ro
wcaiing laiu..."
8|mp|c |ee|czn !cs!s
You can uo a simlc loolcan icsi ly chccIing
ihc valuc ol a vaiiallc, using a on..or oe.no.
incluuing:
lcss ihan)
gicaici ihan)
cqualiiy) ycs, ihai`s wo cquals signs)
Noiicc ihc uillcicncc lciwccn ihc n.rer
ociaioi a .rIe cquals sign) anu ihc equnI
ociaioi wo cquals signs). Iois ol iogiammcis
acciucnially iyc = whcn ihcy wnr ==. Bui noi
you.)
int x = 4; // assign 4 to x
while (x > 3) {
// loop code run because
// x greater than 3
x = x - 1; // or we'd loop forever
}
int z = 27; //
while (z == 17) {
// loop code will run because
// z is equal to 17
}
whiIe (more8oIIs ~~ frue) {
keepJuggIing( ) ,
}
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
12 chapter 1
public class Loopy {
public static void main (String[] args) {
int x = 1;
System.out.println(Before the Loop);
while (x < 4) {
System.out.println(In the loop);
System.out.println(Value of x is + x);
x = x + 1;
}
System.out.println(This is after the loop);
}
}
% java Loopy
Before the Loop
In the loop
Value of x is 1
In the loop
Value of x is 2
In the loop
Value of x is 3
This is after the loop
8ll P0lk5
3lalererls erd |r a ser|co|or ;
Code o|oc|s are del|red oy a pa|r ol cur|y oraces { }
0ec|are ar |nr var|ao|e W|l| a rare ard a lype: |nt x;
T|e ass|gnment operalor |s one equa|s s|r =
T|e equa|s operalor uses ruo equa|s s|rs ==
A un||e |oop rurs everyl||r W|l||r |ls o|oc| (del|red oy cur|y
oraces) as |or as l|e oono|r|ona| resr |s .
ll l|e cord|l|ora| lesl |s , l|e un||e |oop code o|oc| Wor'l
rur, ard execul|or W||| rove doWr lo l|e code |rred|ale|y
alrer l|e |oop o|oc|.
Pul a ooo|ear lesl |rs|de parerl|eses:
while (x == 4) { }
Irzmp|c ef z while |eep
(-,- a,- |
oa|| qa--(:|-

Why does everything have
to be in a cIass!
1ava is an ob|ect-oriented
(OO) language. |t's not like the
old days when you had steam-
driven compilers and wrote one
monolithic source file with a pile
of procedures. |n chapter 2 you'll
learn that a class is a blueprint for
an ob|ect, and that nearly every-
thing in 1ava is an ob|ect.
Do I have to put a main in
every cIass I write!

Nope. A 1ava program
might use dozens of classes (even
hundreds), but you might only
have one with a main method
the one that starts the program
running. ou might write test
classes, though, that have main
methods for testing your othet
classes.

In my other Ianguage I can
do a booIean test on an integer.
In 1ava, can I say something Iike:
int x = 1;
while (x){ }

No. A oooleon and an
|nteet are not compatible types in
1ava. Since the result of a condi-
tional test must be a boolean, the
only variable you can directly test
(without using a comparison op-
erator) is a Por example,
you can say:
boolean isHot = true;
while(isHot) { }
l
: : l
- --l
-l
Java basics
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
dive In A Quick Dip
13
0en4| !|enz| |rznrh|n]
In ]ava, an . icsi is lasically ihc samc as ihc loolcan icsi in a
wL.Ie loo - cxcci insicau ol saying, ihcic`s siill lcci...",
you`ll say, ihcic`s siill lcci..."
class IfTest {
public static void main (String[] args) {
int x = 3;
if (x == 3) {
System.out.println(x must be 3);
}
System.out.println(This runs no matter what);
}
}
% java IfTest
x must be 3
This runs no matter what
:-- --l-l
Thc couc alovc cxccuics ihc linc ihai iinis x musi lc S" only
il ihc conuiiion : is cqual io S) is iiuc. Rcgaiulcss ol whcihci
ii`s iiuc, ihough, ihc linc ihai iinis, This iuns no maiici whai"
will iun. So uccnuing on ihc valuc ol :, ciihci onc siaicmcni
oi iwo will iini oui.
Bui wc can auu an eIe io ihc conuiiion, so ihai wc can
say somcihing liIc, I ihcic`s siill lcci, Icc couing, eIe
oihciwisc) gci moic lcci, anu ihcn coniinuc on..."
class IfTest2 {
public static void main (String[] args) {
int x = 2;
if (x == 3) {
System.out.println(x must be 3);
} else {
System.out.println(x is NOT 3);
}
System.out.println(This runs no matter what);
}
}
% java IfTest2
x is NOT 3
This runs no matter what
--- --l-l
+,-+ :+ ,-+:.|
Civen rhe eurur:
% java DooBee
DooBeeDooBeeDo
lill in rhe missing ceJe:
public class Doo8ee }
public static void main (String|| args) }
int x l,
while (x < _____ ) }
System.out._________("Doo),
System.out._________("8ee),
x x + l,
}
if (x ______ ) }
System.out.print("Do),
}
}
}

8ys!cm.ee!.pr|n! vs.
8ys!cm.ee!.pr|n!|n
|f you've been paying attention (of
course you have) then you've noticed us
switching between print and printIn.
Did you spot the difference!
System.out.rinrln inserts a newline
(think of println as printnewIine while
System.out.rinr keeps printing to
the line. |f you want each thing
you print out to be on its own line, use
printIn. |f you want everything to stick
together on one line, use print.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
14 chapter 1
0e4|n] z 8cr|ees Bes|ncss
pp||rz!|en
Ici`s ui all youi ncw ]ava sIills io goou usc wiih
somcihing iaciical. Wc nccu a class wiih a n.r(), an .r
anu a S..r vaiiallc, a wL.Ie loo, anu an . icsi. A liiilc
moic olish, anu you`ll lc luiluing ihai lusincss lacI-
cnu in no iimc. Bui beo.e you looI ai ihc couc on ihis
agc, ihinI loi a momcni aloui how ,ou woulu couc ihai
classic chiluicn`s lavoiiic, 99 loiilcs ol lcci."
public class BeerSong {
public static void main (String[] args) {
int beerNum = 99;
String word = bottles;
while (beerNum > 0) {
if (beerNum == 1) {
word = bottle; // singular, as in ONE bottle.
}
System.out.println(beerNum + + word + of beer on the wall);
System.out.println(beerNum + + word + of beer.);
System.out.println(Take one down.);
System.out.println(Pass it around.);
beerNum = beerNum - 1;
if (beerNum > 0) {
System.out.println(beerNum + + word + of beer on the wall);
} else {
System.out.println(No more bottles of beer on the wall);
} // end else
} // end while loop
} // end main method
} // end class
There's still one little flaw in our
code. |t compiles and runs, but the
output isn't l00% perfect. See if
you can spot the flaw , and fix it.
serious Java app
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
15
Bob`s alarm clock rings at 8:30 Monoay morning, just like every other weekoay.
But Bob hao a wilo weekeno, ano reaches lor the SNOOZE button.
Ano that`s when the action starts, ano the Java-enableo appliances
come to lile.
Iirst, the alarm clock senos a message to the collee maker* Hey, the geek`s
sleeping in again, oelay the collee 12 minutes.
The collee maker senos a message to the Motorola
toaster, Holo the toast, Bob`s snoozing.
The alarm clock then senos a message to Bob`s
Nokia Navigator cell phone, Call Bob`s 9
o`clock ano tell him we`re running a little late.
Iinally, the alarm clock senos a message to
Sam`s ,Sam is the oog, wireless collar, with the too-lamiliar signal that
means, Get the paper, but oon`t expect a walk.
A lew minutes later, the alarm goes oll again. Ano ooio Bob
hits SNOOZE ano the appliances start chattering. Iinally,
the alarm rings a thiro time. But just as Bob reaches lor the
snooze button, the clock senos the jump ano bark signal to Sam`s
collar. Shockeo to lull consciousness, Bob rises, gratelul that his Java
skills ano a little trip to Raoio Shack have enhanceo the oaily
routines ol his lile.
HIs toast Is toasted.
HIs coffee steans.
HIs aer auaIts.
Just another wonoerlul morning in The Juzu-EnuhIed Houoe
You can havc a java-cnahIcd honc. Stick with a sensible solution using Java,
Ethernet, ano Jini technology. Beware ol imitations using other so-calleo plug
ano play ,which actually means plug ano play with it lor the next three oays
trying to get it to work, or portable platlorms. Bob`s sister Betty trieo one ol
those t/.r, ano the results were, well, not very appealing, or sale.
Bit ol a shame about her oog, too...
).. -:-
).. --- l--

.-
': :-||.-
.: )
..
-ll-- ---
)
..
l-.:l--
Men4zy mern|n] z! Be|s
Could this story be trueI es and no. while there ote versions of 1ava running in de-
vices including PDAs, cell phones (esec|olly cell phones), pagers, rings, smart cards,
and more -you might not find a 1ava toaster or dog collar. 8ut even if you can't
find a 1ava-enabled version of your favorite gadget, you can still run it as if it wete a
1ava device by controlling it through some other interface (say, your laptop) that |s
running 1ava. This is known as the 1ini suttoote otch|tectute. es you con have that
geek dream home.

`lP mult|cost if you're gonna be all picky about protocol


Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
16 chapter 1
Iet's write a program
Try my new
phrose-o-mofic ond
you'II be o sIick foIker
jusf Iike fhe boss or
fhose guys in morkefing.
public class PhraseOMatic {
public static void main (String[] args) {
// muke Ihree seIs el werds Ie theese lrem. kdd yeur ewnl
String[] wordListOne = {24/7,multi-
Tier,30,000 foot,B-to-B,win-win,front-
end, web-based,pervasive, smart, six-
sigma,critical-path, dynamic};
String[] wordListTwo = {empowered, sticky,
value-added, oriented, centric, distributed,
clustered, branded,outside-the-box, positioned,
networked, focused, leveraged, aligned,
targeted, shared, cooperative, accelerated};
String[] wordListThree = {process, tipping-
point, solution, architecture, core competency,
strategy, mindshare, portal, space, vision,
paradigm, mission};
// nd euI hew muny werds ure in euth lisI
int oneLength = wordListOne.length;
int twoLength = wordListTwo.length;
int threeLength = wordListThree.length;
// generuIe Ihree rundem numbers
int rand1 = (int) (Math.random() * oneLength);
int rand2 = (int) (Math.random() * twoLength);
int rand3 = (int) (Math.random() * threeLength);
// new build u phruse
String phrase = wordListOne[rand1] + +
wordListTwo[rand2] + + wordListThree[rand3];
// prinI euI Ihe phruse
System.out.println(What we need is a + phrase);
}
}

OK, so the beer song wasn't a serious


business application. Still need something
practical to show the bossI Check out the
Phrase-O-Matic code.
--l- --- ]-- l]- l: -l- .- -l--, |-l
l- :-- - l: --- ---/|--~--.-'
N--- l l- --l--- -] --- ]--'-- l]-
. l-- |. l- -l---- --l-:'` -- l
---'l :--|- - l- ]--: ]-- :-- --
l: .- .-- --.|, .- ]-- :.- l]- l--,
-l --'l l l- --l--- -] --l| A|1!
]--'- :|-:- . l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
17
|hrzsc-0-Mz!|r
Hew | ! werks.
In a nuishcll, ihc iogiam maIcs ihicc lisis ol woius, ihcn ianuomly icIs onc woiu
liom cach ol ihc ihicc lisis, anu iinis oui ihc icsuli. Don`i woiiy il you uon`i unuci-
sianu e:nI, whai`s hacning in cach linc. Ioi gosh saIcs, you`vc goi ihc wholc looI
ahcau ol you, so iclax. This is |usi a quicI looI liom a S0,000 looi ouisiuc-ihc-lox
iaigcicu lcvciagcu aiauigm.
Thc hisi sic is io cicaic ihicc Siiing aiiays - ihc coniaincis ihai will holu all ihc
woius. Dcclaiing anu cicaiing an aiiay is casy, hcic`s a small onc:
String[] pets = {Fido, Zeus, Bin};
Each woiu is in quoics as all goou Siiings musi lc) anu scaiaicu ly commas.
Ioi cach ol ihc ihicc lisis aiiays), ihc goal is io icI a ianuom woiu, so wc havc
io Inow how many woius aic in cach lisi. Il ihcic aic 14 woius in a lisi, ihcn wc nccu
a ianuom numlci lciwccn 0 anu 1S ]ava aiiays aic zcio-lascu, so ihc hisi woiu is ai
osiiion 0, ihc scconu woiu osiiion 1, anu ihc lasi woiu is osiiion 1S in a 14-clcmcni
aiiay). Quiic hanuily, a ]ava aiiay is moic ihan hay io icll you iis lcngih. You |usi
havc io asI. In ihc cis aiiay, wc`u say:
int x = pets.length;
anu x woulu now holu ihc valuc S.
Wc nccu ihicc ianuom numlcis. ]ava shis oui-ol-ihc-lox, oll-ihc-shcll, shiinI-
wiacu, anu coic comcicni wiih a sci ol maih mcihous loi now, ihinI ol ihcm as
lunciions). Thc random() mcihou iciuins a ianuom numlci lciwccn 0 anu noi-
quiic-1, so wc havc io muliily ii ly ihc numlci ol clcmcnis ihc aiiay lcngih) in ihc
lisi wc`ic using. Wc havc io loicc ihc icsuli io lc an inicgci no uccimals allowcu!) so
wc ui in a casi you`ll gci ihc uciails in chaici 4). Ii`s ihc samc as il wc hau any uoai-
ing oini numlci ihai wc wanicu io convcii io an inicgci:
int x = (int) 24.6;
Now wc gci io luilu ihc hiasc, ly icIing a woiu liom cach ol ihc ihicc lisis,
anu smooshing ihcm iogcihci also insciiing saccs lciwccn woius). Wc usc ihc +"
ociaioi, which ornerne wc iclci ihc moic icchnical ooLe`) ihc Siiing ol|ccis
iogcihci. To gci an clcmcni liom an aiiay, you givc ihc aiiay ihc inucx numlci osi-
iion) ol ihc ihing you wani using:
String s = pets[0]; // s is now the String Fido
s = s + + is a dog; // s is now Fido is a dog
Iinally, wc iini ihc hiasc io ihc commanu-linc anu... voila! Ve`.e .r n.Ie.r.
what we need
here is a...
pervasive targeted
process
dynamic outside-
the-box tipping-
point
smart distributed
core competency
24/7 empowered
mindshare
30,000 foot win-win
vision
six-sigma net-
worked portaI
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
18 chapter 1
The ava Virtaal Nachine
Whai, aic you Iiuuing. . I n ]ava.
I`m ihc guy who aciually maIcs a iogiam
.ur. Thc comilci |usi givcs you a Ie. Thai`s
ii. ]usi a hlc. You can iini ii oui anu usc ii
loi wall aci, Iinuling, lining ihc liiu cagc
whaie.e., lui ihc hlc uocsn`i Jo anyihing un-
lcss I`m ihcic io iun ii.
Anu ihai`s anoihci ihing, ihc comilci has
no scnsc ol humoi. Thcn again, il ,ou hau io
scnu all uay chccIing nii-icIy liiilc syniax
violaiions...
I`m noi saying you`ic, liIc, oIeeI, usclcss.
Bui ically, whai is ii ihai you uo. Sciiously. I
havc no iuca. A iogiammci coulu |usi wiiic
lyiccouc ly hanu, anu I`u iaIc ii. You mighi
lc oui ol a |ol soon, luuuy.
I icsi my casc on ihc humoi ihing.) Bui you
siill uiun`i answci my qucsiion, whai Jo you
aciually uo.
The 0empiler
I uon`i aicciaic ihai ionc.
Excusc mc, lui wiihoui e, whai cxacily
woulu you iun. Thcic`s a .enor ]ava was
ucsigncu io usc a lyiccouc comilci, loi youi
inloimaiion. Il ]ava wcic a uicly iniciicicu
languagc, whcic-ai iuniimc-ihc viiiual
machinc hau io iianslaic siiaighi-liom-a-icxi-
cuiioi souicc couc, a ]ava iogiam woulu
iun ai a luuiciously glacial acc. ]ava`s hau a
challcnging cnough iimc convincing colc
ihai ii`s hnally lasi anu owcilul cnough loi
mosi |ols.
Excusc mc, lui ihai`s quiic an ignoiani noi
io mcniion n..onr) ciscciivc. Whilc ii
. iiuc ihai-Leo.e.nII,-you can iun any
iocily loimaiicu lyiccouc cvcn il ii uiun`i
comc oui ol a ]ava comilci, in iaciicc ihai`s
alsuiu. A iogiammci wiiiing lyiccouc ly
hanu is liIc uoing youi woiu ioccssing ly
wiiiing iaw osisciii. Anu I woulu aicciaic
ii il you woulu ro iclci io mc as luuuy."
1cnih|`s 1alk: The cempiler and
the VN battle ever the qaestien,
whe's mere impertant?"
the compiIer and the JVM
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
19
Bui somc siill gci ihiough! I can ihiow Class-
CasiExcciions anu somciimcs I gci colc
iiying io ui ihc wiong iyc ol ihing in an
aiiay ihai was ucclaicu io holu somcihing
clsc, anu-
OK. Suic. Bui whai aloui eu..,. IooI ai all
ihc sccuiiiy siull I uo, anu you`ic liIc, whai,
chccIing loi e.oIor. Oooohhh lig sccuiiiy
iisI! ThanI goouncss loi you!
Whaicvci. I havc io uo ihai samc siull oo,
ihough, |usi io maIc suic nolouy snucI in
alici you anu changcu ihc lyiccouc lcloic
iunning ii.
Oh, you can couni on ii. BuJJ,.
Rcmcmlci ihai ]ava is a siiongly-iycu lan-
guagc, anu ihai mcans I can`i allow vaiiallcs
io holu uaia ol ihc wiong iyc. This is a
ciucial salciy lcaiuic, anu I`m allc io sio ihc
vasi ma|oiiiy ol violaiions lcloic ihcy cvci gci
io you. Anu I also-
Excusc mc, lui I wasn`i uonc. Anu ycs, ihcic
n.e somc uaiaiyc cxcciions ihai can cmcigc
ai iuniimc, lui somc ol ihosc havc io lc
allowcu io suoii onc ol ]ava`s oihci imoi-
iani lcaiuics-uynamic linuing. Ai iuniimc,
a ]ava iogiam can incluuc ncw ol|ccis ihai
wcicn`i cvcn Irowr io ihc oiiginal iogiam-
mci, so I havc io allow a cciiain amouni ol
ucxililiiy. Bui my |ol is io sio anyihing ihai
woulu ncvci-ouIJ ncvci-succccu ai iun-
iimc. Usually I can icll whcn somcihing won`i
woiI, loi cxamlc, il a iogiammci acciucn-
ially iiicu io usc a Buiion ol|cci as a SocIci
conncciion, I woulu ucicci ihai anu ihus
ioicci him liom causing haim ai iuniimc.
Excusc mc, lui I am ihc hisi linc ol uclcnsc,
as ihcy say. Thc uaiaiyc violaiions I icvious-
ly ucsciilcu coulu wicaI havoc in a iogiam
il ihcy wcic allowcu io manilcsi. I am also
ihc onc who icvcnis acccss violaiions, such
as couc iiying io invoIc a iivaic mcihou, oi
changc a mcihou ihai - loi sccuiiiy icasons
- musi ncvci lc changcu. I sio colc liom
iouching couc ihcy`ic noi mcani io scc,
incluuing couc iiying io acccss anoihci class`
ciiiical uaia. Ii woulu iaIc houis, cihas uays
cvcn, io ucsciilc ihc signihcancc ol my woiI.
Ol couisc, lui as I inuicaicu icviously, il I
uiun`i icvcni whai amounis io cihas 99%
ol ihc oicniial iollcms, you woulu giinu io
a hali. Anu ii looIs liIc wc`ic oui ol iimc, so
wc`ll havc io icvisii ihis in a laici chai.
The Java VIrtuaI machIne The 0cmpIIer
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
20 chapter 1
if {x == l| { System.out.print{"d"|,
x = x ~ l, }
if {x == 2| {
System.out.print{"b c"|,
}
if {x > 2| {
System.out.print{"a"|,
}
int x = 3,
x = x ~ l,
System.out.print{"~"|,
while {x > 0| {
class Shuf el {
public static void main{String args| {
File Edit Window Help Sleep
% java Shuffle1
a-b c-d

CaJe Kagaets
A working 1ava program is all scrambled up
on the fridge. Can you rearrange the code
snippets to make a working 1ava program
that produces the output listed belowI
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!

exercise: Code Magnets


Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
21

class Exerciselb {
int x = 5,
while { x > l | {
x = x ~ l,
if { x < 3| {
System.out.println{"small x"|,
}
}
}

class Exerciselb {
public static void main{String args| {
int x = l,
while { x < l0 | {
if { x > 3| {
System.out.println{"big x"|,
}
}
}
}

public static void main{String args| {
int x = 5,
while { x > l | {
x = x ~ l,
if { x < 3| {
System.out.println{"small x"|,
}
}
}
[ze[ | ([ ]zvz |j], n ([j, zg
,n(, z e]( ,ae |j].
(a j j, ( ]zy ej] zn]
](jn w[([ ze[ | ([,
|j], wj]] ej]. ]| ([y
wn'( ej], [w
wa]] ya |jy ([/
] ge eomgj|e;

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
22 chapter 1
l 2 3
4 5 6
7
8 9 l0 ll
l2
l3
l4 l5 l6
l7
l8 l9
20
2l
Let's give your right brain something to do.
|t's your standard crossword, but almost all
of the solution words are from chapter l. 1ust
to keep you awake, we also threw in a few
(non-1ava) words from the high-tech world.

4. Command-line invoker
6. 8ack againI
8. Can't go both ways
9. Acronym for your laptop's power
l2. number variable type
l3. Acronym for a chip
l4. Say something
l8. Quite a crew of characters
l9. Announce a new class or method
2l. what's a prompt good forI

l. Not an integer (or _____ your boat)


2. Come back empty-handed
3. Open house
5. 'Things' holders
7. Until attitudes improve
l0. Source code consumer
ll. Can't pin it down
l3. Dept. of LAN |ockeys
l5. Shocking modier
l6. 1ust gotta have one
l7. How to get things done
20. 8ytecode consumer
]||(iss ).c
puzzIe: crossword
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
dive In A Quick Dip
23
A short 1ava program is listed below. One block of the program
is missing. our challenge is to match the candidate bIock of
code (on the left), with the output that you'd 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).
:.-.l- :--
--: ---

-.l: -.:
:.-.l- -l
--- - l-
-::|- --l-l:
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;
}
}
}
y = x ~ y,
y = y + x,
y = y + 2,
if{ y > 4 | {
y = y ~ l,
}
x = x + l,
y = y + x,
if { y < 5 | {
x = x + l,
if { y < 3 | {
x = x ~ l,
}
}
y = y + 2,
22 46
ll 34 59
02 l4 26 38
02 l4 36 48
00 ll 2l 32 42
ll 2l 32 42 53
00 ll 23 36 4l0
02 l4 25 36 47
Candidates: PossibIe output:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
24 chapter 1
System.out.print(" ),
System.out.print("a "),
System.out.print("n "),
System,out,print("an"),
x x + l,
x x + 2,
x x - 2,
x x - l,
x > 0
x < l
x > l
x > 3
x < 4
System.out.print("noys "),
System.out.print("oise "),
System.out.print(" oyster "),
System.out.print("annoys),
System.out.print("noise),

our is to take code snippets from the
pool and place them into the blank
lines in the code. ou may not use the
same snippet more than once, and
you won't need to use all the snip-
pets. our is to make a class that
will compile and run and produce the
output listed. Don't be fooledthis one's
harder than it looks.
class PoolPuzzleOne {
public static void main{String args| {
int x = 0,
while { __________ | {
_____________________________
if { x < l | {
___________________________
}
_____________________________
if { __________ | {

____________________________

___________
}
if { x == l | {
____________________________
}
if { ___________ | {
____________________________
}
System.out.println{""|,
____________
}
}
}
Note: ach snippet
from the pooI can be
used onIy oncel
File Edit Window Help Cheat
%java PoolPuzzleOne
a noise
annoys
an oyster
Dutput
puzzIe: PooI PuzzIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
25
File Edit Window Help Poet
% java Shuffle1
a-b c-d
class Shufel {
public static void main{String args| {
int x = 3,
while {x > 0| {
if {x > 2| {
System.out.print{"a"|,
}
x = x ~ l,
System.out.print{"~"|,
if {x == 2| {
System.out.print{"b c"|,
}
if {x == l| {
System.out.print{"d"|,
x = x ~ l,
}
}
}
}
class Exerciselb {
public static void main{String args| {
int x = l,
while { x < l0 | {
x ~ x + I,
if { x > 3| {
System.out.println{"big x"|,
}
}
} This wiII compiIe ond run (no oufpuf), buf
} wifhouf o Iine odded fo fhe progrom, if
wouId run forever in on infnife 'whiIe' Ioopl
cIoss Foo {
public static void main{String args| {
int x = 5,
while { x > l | {
x = x ~ l,
if { x < 3| {
System.out.println{"small x"|,
}
} This fIe won'f compiIe wifhouf o
} cIuss decIurution und don't forget
} fhe mofching curIy broce l
class Exerciselb {
pubIic sfofic void moin(Sfring [] orgs) {
int x = 5,
while { x > l | {
x = x ~ l,
if { x < 3| {
System.out.println{"small x"|,
}
}
}
}
A

C
Code Mognefs:
]e;ejze o|ajoz
The 'whiIe' Ioop code musf be in-
side o mefhod. If con'f jusf be
honging ouf inside fhe cIoss.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
26 chapter 1
l 2 3
4 5 6
7
8 9 l0 ll
l2
l3
l4 l5 l6
l7
l8 l9
20
2l
J A V A
P
P
A
Y
S
8 A M C H
S
T
A
T
I
C
M
A
I
M
Y T E O U T P P I M T
W
I
L
M T
S P I 0 D E C L A P E
C O M M A M D
J
V
M
T
H
O
I C
P
U
8
L
I
V
A
P
A
8
E
C
O
M
I
L
P
V
O
I
D
F
L
O
A
O P
class PoolPuzzleOne {
public static void main{String args| {
int x = 0,
while { X - 4 | {
System,out,print{"u"};
if { x < l | {
System,out,print{" "};
}
System,out,print{"n"};
if { X > 1 | {

System,out,print{" oyster"};
= + Z;
}
if { x == l | {
System,out,print{"noys"};
}
if { X - 1 | {
System,out,print{"oise"};
}
System.out.println{""|,
X = X + 1;
}
}
}
File Edit Window Help Cheat
%java PoolPuzzleOne
a noise
annoys
an oyster
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;
}
}
}
y = x ~ y,
y = y + x,
y = y + 2,
if{ y > 4 | {
y = y ~ l,
}
x = x + l,
y = y + x,
if { y < 5 | {
x = x + l,
if { y < 3 | {
x = x ~ l,
}
}
y = y + 2,
22 46
ll 34 59
02 l4 26 38
02 l4 36 48
00 ll 2l 32 42
ll 2l 32 42 53
00 ll 23 36 4l0
02 l4 25 36 47
Candidates: PossibIe output:
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
2 cIasses and objects
this is a new chapter 27
I was toId there wouId be objects. |n chapter l, we put all of our code in the
main() method. That's not exactly ob|ect-oriented. |n fact, that's not ob|ect-oriented ot oll. well,
we did use a few ob|ects, like the String arrays for the Phrase-O-Matic, but we didn't actually
develop any of our own ob|ect tyes. So now we've got to leave that procedural world behind,
get the heck out of main(), and start making some ob|ects of our own. we'll look at what makes
ob|ect-oriented (OO) development in 1ava so much fun. we'll look at the difference between
a closs and an ooject. we'll look at how ob|ects can give you a better life (at least the program-
ming part of your life. Not much we can do about your fashion sense). warning: once you get
to Ob|ectville, you might never go back. Send us a postcard.
A Trip to Ob]ectville
We're going fo
ObjecfviIIel We're
Ieoving fhis dusfy oI'
proceduroI fown for good.
I'II send you o posfcord.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
once upon a time in ObjectviIIe
28 chapter 2
!hc spcr

ncc uon a iimc in a soliwaic sho, iwo
iogiammcis wcic givcn ihc samc scc anu iolu io
luilu ii". Thc Rcally Annoying Pio|cci Managci
loiccu ihc iwo coucis io comcic,
ly iomising ihai whocvci uclivcis
hisi gcis onc ol ihosc cool Acion
chaiis all ihc Silicon Vallcy guys havc.
Iaiiy, ihc ioccuuial iogiammci, anu
Biau, ihc OO guy, loih Incw ihis woulu
lc a iccc ol caIc.
Iaiiy, siiiing in his culc, ihoughi io
himscll, Whai aic ihc ihings ihis iogiam
has io Jo. Whai procedures uo wc nccu.".
Anu hc answcicu himscll , rotatc anu
playSound." So oll hc wcni io luilu ihc
ioccuuics. Alici all, whai . a iogiam il noi
a ilc ol ioccuuics.
Biau, mcanwhilc, IicIcu lacI ai ihc calc
anu ihoughi io himscll, Whai aic ihc things
in ihis iogiam... who aic ihc Icy In,e.." Hc
hisi ihoughi ol Thc Shapcs. Ol couisc, ihcic
wcic oihci ol|ccis hc ihoughi ol liIc ihc Usci, ihc Sounu,
anu ihc ClicIing cvcni. Bui hc alicauy hau a liliaiy ol couc
loi ihosc icccs, so hc locuscu on luiluing Shacs. Rcau
on io scc how Biau anu Iaiiy luili ihcii iogiams, anu
loi ihc answci io youi luining qucsiion, So, who got the
Aeron`
0hz|r Wzrs
|er Hew 0|jcr!s 0zn 0hzn]c Yeer I|fcI
!hc rhz|r
! Brz4s |zp!ep z! !hc rzfc
Biau wioic a cIoss loi cach ol ihc ihicc shacs
|n Izrrys re|c
As hc hau uonc a gazillion iimcs lcloic, Iaiiy
sci aloui wiiiing his Important Proccdurcs.
Hc wioic rotatc anu playSound in no iimc.
rotate(shapeNum) {
// make the shape rotate 360
}
playSound(shapeNum) {
// use shapeNum to lookup which
// AIF sound to play, and play it
}

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
29
1here
w
ill re
an
an
cera
shae
cn
|he
screen, w
i|h
|he
c|hers.
T
hen
|he
user
clicks
cn
|he
an
cera, i| w
ill rc|a|e
like
|he
c|hers, ana
lay
a
.hil scuna
lile
Be! wz| !| Ihcrcs |ccn z spcr rhzn]c.
OK, eLr.nII, you wcic hisi, Iaiiy," saiu ihc Managci, lui wc havc io auu |usi onc
iiny ihing io ihc iogiam. Ii`ll lc no iollcm loi ciacI iogiammcis liIc you iwo."
I I LnJ n J.e o. e.e., .e I`.e Len.J Ln ore`, ihoughi Iaiiy, Inowing ihai scc-
changc-no-iollcm was a laniasy. ArJ ,e B.nJ IooI .nreI, e.ere. VLn` u w.L
Ln:` Siill, Iaiiy hclu iighi io his coic lclicl ihai ihc OO way, whilc cuic, was |usi
slow. Anu ihai il you wanicu io changc his minu, you`u havc io iy ii liom his colu,
ucau, caial-iunncllcu hanus.
Izrry !hee]h! hc4 nz||c4 | !. Hc ree|4 z|mes! fcc| !hc re||c4
s!cc| ef !hc cren |cncz!h h|s...
whz! ]e! z44c4 !e !hc spcr
Bzrk |n Izrrys re|c
Thc ioiaic ioccuuic woulu siill woiI, ihc couc uscu
a looIu iallc io maich a shacNum io an aciual
shac giahic. Bui pIoySound wouId hove to chonge.
Anu whai ihc hccI is a .hil hlc.
playSound(shapeNum) {
// if the shape is not an amoeba,
// use shapeNum to lookup which
// AIF sound to play, and play it
// else
// play amoeba .hif sound
}
Ii iuincu oui noi io lc such a lig ucal, lui it stiII
mode him queosy to touch previousIy-tested code. Ol
nII colc, Le shoulu Inow ihai no maiici whai ihc
io|cci managci says, the spec oIwoys chonges.
! Brz4s |zp!ep z! !hc |czrh
Biau smilcu, sicu his maigaiiia, anu w.oe ore
rew In. Somciimcs ihc ihing hc lovcu mosi
aloui OO was ihai hc uiun`i havc io iouch couc
hc`u alicauy icsicu anu uclivcicu. Ilcxililiiy,
cxicnsililiiy,..." hc muscu, icucciing on ihc
lcnchis ol OO.

rolale() {
// code lo rolale ar aroeoa

p|ay3ourd() {
// code lo p|ay l|e reW
// .||l l||e lor ar aroeoa

.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
once upon a time in ObjectviIIe
30 chapter 2
An
ecra
rc|a|icn
cin| in
Iarry
ana
Braa`s
versicn:
T
here
|he
an
era
rc|a|icn
cin| shcula
re:
Whz! !hc spcr renvcn|cn!| y
fer]e! !e mcn!|en
Hah! So much loi ihai looly OO nonscnsc). Bui ihc smiiI on Iaiiy`s lacc mclicu whcn ihc
Rcally Annoying Pio|cci Managci saiu wiih ihai ionc ol uisaoinimcni), Oh, no, Ln` noi
how ihc amocla is suoscu io ioiaic..."
Tuins oui, loih iogiammcis hau wiiiicn ihcii ioiaic couc liIc ihis:
1} determine the rectangle that surrounds the shape
2} calculate the center of that rectangle, and rotate the shape around that point.
Bui ihc amocla shac was suoscu io ioiaic aiounu a oini on onc erJ, liIc a clocI hanu.
I`m ioasi." ihoughi Iaiiy, visualizing chaiicu Wonucilicau. Alihough, hmmmm. I coulu
|usi auu anoihci il/clsc io ihc ioiaic ioccuuic, anu ihcn |usi haiu-couc ihc ioiaiion oini
couc loi ihc amocla. Thai iolally won`i licaI anyihing." Bui ihc liiilc voicc ai ihc lacI ol
his hcau saiu, B. A.nIe. Do ,ou LoreI, L.rI Le e wor` Lnre nn.r:`
Izrry snerk |n jes! memcn!s zhcz4 ef Brz4.
Bzrk |n Izrrys re|c
Hc hguicu hc lciici auu ioiaiion oini aigumcnis
io ihc ioiaic ioccuuic. A Iot o[ code wos o[[ected.
Tcsiing, iccomiling, ihc wholc ninc yaius all ovci
again. Things ihai uscu io woiI, uiun`i.
rotate(shapeNum, xPt, yPt) {
// if the shape is not an amoeba,
// calculate the center point
// based on a rectangle,
// then rotate
// else
// use the xPt and yPt as
// the rotation point offset
// and then rotate
}
! Brz4s |zp!ep en h|s |zwn
rhz|r z! !hc Ic||er|4c B|ec]rzss Ics!| vz|
Wiihoui missing a lcai, Biau mouihcu ihc ioiaic
mcthod, lui only in ihc Amocla class. He never
touched the tested, worhing,
compiIed code loi ihc oihci
aiis ol ihc iogiam. To
givc ihc Amocla a ioia-
iion oini, hc auucu an
attributc ihai all Amoclas
woulu havc. Hc moui-
hcu, icsicu, anu uclivcicu
wiiclcssly) ihc icviscu
iogiam uuiing a singlc
Bcla IlccI sci.

|rl xPo|rl
|rl yPo|rl
rolale() {
// code lo rolale ar aroeoa
// us|r aroeoa's x ard y

p|ay3ourd() {
// code lo p|ay l|e reW
// .||l l||e lor ar aroeoa

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
31
8e, Brz4 !hc 00 ]ey ]e! !hc rhz|r, r|]h! !
Not so [ost. Iaiiy lounu a uaw in Biau`s aioach. Anu,
sincc hc was suic ihai il hc goi ihc chaii hc`u also gci Iucy
in accouniing, hc hau io iuin ihis ihing aiounu.
LARRY: You`vc goi uulicaicu couc! Thc ioiaic
ioccuuic is in all loui Shac ihings.
BRAD: Ii`s a method, noi a .oeJu.e. Anu ihcy`ic cIosses,
noi L.r.
LARRY: Whaicvci. Ii`s a siuiu ucsign. You havc io
mainiain ou. uillcicni ioiaic mcihous". How can ihai
cvci lc goou.
BRAD: Oh, I gucss you uiun`i scc ihc hnal ucsign. Ici mc
show you how OO inhcritancc woiIs, Iaiiy.
Whz! Izrry wzn!c4
|f|]erc4 !hc rhz|r wee|4 |mprcss hcrI
Ihcyrc 8hzpcs, zn4 !hcy z| | re!z!c zn4
p|zy8een4. 8e | z|s!rzr!c4 ee! !hc
remmen fcz!ercs zn4 pe! !hcm |n!e z
ncw r|zss rz| |c4 8hzpc.
3|ape
rolale()
p|ay3ourd()
Tr|ar|e 3quare C|rc|e Aroeoa
3|ape
rolale()
p|ay3ourd()
sepcrr|zss
se|r|zsscs
Ihcn | ||nkc4 !hc e!hcr
feer shzpc r|zsscs !e
!hc ncw 8hzpc r|zss,
|n z rc|z!|ensh|p rz||c4
|nhcr| !znrc.
Tr|ar|e
rolale()
p|ay3ourd()
3quare
rolale()
p|ay3ourd()
C|rc|e
rolale()
p|ay3ourd()
| |eekc4 z! whz! z|| feer
r|zsscs hzvc |n remmen.
Aroeoa
rolale()
p|ay3ourd()

You car read l||s as, "8quare |nher|ts from 8hape",


"6|rc|e |nher|ts from 8hape", ard so or. l reroved
rolale() ard p|ay3ourd() lror l|e ol|er s|apes, so roW
l|ere's or|y ore copy lo ra|rla|r.
T|e 3|ape c|ass |s ca||ed l|e superc|ass ol l|e ol|er lour
c|asses. T|e ol|er lour are l|e subc|asses ol 3|ape. T|e
suoc|asses |r|er|l l|e rel|ods ol l|e superc|ass. lr ol|er
Words, |l rne $nae o|ass nas rne lunor|ona||ry, rnen rne
suoo|asses auromar|oa||y ger rnar same lunor|ona||ry.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
once upon a time in ObjectviIIe
32 chapter 2
Whz! z|ee! !hc mec|z re!z!c|I!
LARRY: Wasn`i ihai ihc wholc iollcm hcic - ihai ihc amocla shac
hau a comlcicly uillcicni ioiaic anu laySounu ioccuuic.
BRAD: Mcthod.
LARRY: Whaicvci. How can amocla uo somcihing uillcicni il
ii inhciiis" iis lunciionaliiy liom ihc Shac class.
BRAD: Thai`s ihc lasi sic. Thc Amocla class ovcrridcs ihc
mcihous ol ihc Shac class. Thcn ai iuniimc, ihc ]VM Inows cxacily
which ioiaic) mcihou io iun whcn somconc iclls ihc Amocla io ioiaic.
O
v
e
r
ride
N
o
w
A
s
k
Me
H
o
w
| mz4c !hc mec|z r|zss evcrr|4c
!hc re!z!c|I mc!he4 ef !hc
sepcrr|zss 8hzpc.
0vcrr|4|n] jes! mczns !hz! z
se|r|zss rc4cf|ncs enc ef | !s
|nhcr| !c4 mc!he4s whcn | ! ncc4s
!e rhzn]c er cr!cn4 !hc |chzv|er
ef !hz! mc!he4.

Tr|ar|e 3quare C|rc|e Aroeoa


rotate(}
// aroeoa-spec|l|c
// rolale code
p|ay8ound(}
// aroeoa-spec|l|c
// sourd code
3|ape
rolale()
p|ay3ourd()
sepcrr|zss
|merc z|s!rzr!I
se|r|zsscs
|merc spcr|f|rI
0vcrr|4|n] mc!he4s
LARRY: How uo you icll" an Amocla io
uo somcihing. Don`i you havc io call ihc
ioccuuic, soiiy-eLoJ, anu ihcn icll ii
wL.L ihing io ioiaic.
BRAD: Thai`s ihc ically cool ihing aloui OO.
Whcn ii`s iimc loi, say, ihc iiianglc io ioiaic,
ihc iogiam couc invoIcs calls) ihc ioiaic)
mcihou or Le ..nrIe obe. Thc icsi ol ihc
iogiam ically uocsn`i Inow oi caic Low ihc
iiianglc uocs ii. Anu whcn you nccu io auu
somcihing ncw io ihc iogiam, you |usi wiiic
a ncw class loi ihc ncw ol|cci iyc, so ihc ncw
objccts will havc thcir own bchavior.
I con foke
core of myseIf.
I know how on Amoebo
is supposed fo rofofe
ond pIoy o sound.
I know how o Shope is
supposed fo behove. Your
job is fo feII me fo
do, ond my job is fo moke if hoppen.
Don'f you worry your IiffIe progrom-
mer heod obouf I do if.
| mz4c !hc mec|z r|zss evcrr|4c
!hc re!z!c|I zn4 p|zy8een4|I
mc!he4s ef !hc sepcrr|zss 8hzpc.
0vcrr|4|n] jes! mczns !hz! z
se|r|zss rc4cf|ncs enc ef | !s
|nhcr| !c4 mc!he4s whcn | ! ncc4s
!e rhzn]c er cr!cn4 !hc |chzv|er
ef !hz! mc!he4.
{
{
{
{
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
cIasses and objects
33
oetaceitive ti
ll you're sluc| or ar exerc|se, lry la|||r aooul
|l oul |oud. 3pea||r (ard |ear|r) acl|vales
a d|llererl parl ol your ora|r. A|l|ou| |l
Wor|s oesl |l you |ave arol|er persor lo
d|scuss |l W|l|, pels Wor| loo. T|al's |oW
our do |earred po|yrorp||sr.
Ihc sespcnsc |s k|| ||n] mc.
Whe ]e! !hc rhz| r!
Amy Irom thc sccond oor.
unlcInownsi io all, ihc Pio|cci
Managci hau givcn ihc scc io
iogiammcis.)
"If heIps me design in o more nofuroI woy. Things
hove o woy of evoIving."
-Joy, Z7, soffwore orchifecf
"Mof messing oround wifh code I've oIreody
fesfed, jusf fo odd o new feofure."
-8rod, 3Z, progrommer
"I Iike fhof fhe dofo ond fhe mefhods fhof oper-
ofe on fhof dofo ore fogefher in one cIoss."
-Josh, ZZ, beer drinker
"Peusing code in ofher oppIicofions. When I wrife
o new cIoss, I con moke if exibIe enough fo be
used in somefhing new, Iofer."
-Chris, 39, projecf monoger
"I con'f beIieve Chris jusf soid fhof. He hosn'f
wriffen o Iine of code in b yeors."

-DoryI, 44, works for Chris
"8esides fhe choir7"
-Amy, 34, progrommer
Whz! 4e yee ||kc z|ee! 00!
7ime to pump some neurons.
ou |ust read a story bout a procedural
programmer going head-to-head with an OO
programmer. ou got a quick overview of some
key OO concepts including classes, methods, and
attributes. we'll spend the rest of the chapter
looking at classes and ob|ects ( we'll return to
inheritance and overriding in later chapters).
8ased on what you've seen so far (and what you
may know from a previous OO language you've
worked with), take a moment to think about
these questions:
what are the fundamental things you need to
think about when you design a 1ava classI what
are the questions you need to ask yourselfI
|f you could design a checklist to use when
you're designing a class, what would be on the
checklistI
WWkm
Qw&W
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
34 chapter 2
thinking about objects
3|opp|rCarl
cart6ontents
addTo6art(}
removeFrom6art(}
check0ut(}
knews
4ecs
8ullor
|abe|
co|or
set6o|or(}
setLabe|(}
dePress(}
un0epress(}
knews
4ecs
A|arr
a|armT|me
a|armHode
setA|armT|me(}
setA|arm(}
|sA|arm8et(}
snooze(}
knews
4ecs
Whcn yee 4cs|]n z r| zss, !h| nk z|ee! !hc e|jcr!s !hz!
w| | | |c rrcz!c4 frem !hz! r| zss ! ypc. Ih| nk z|ee!:
things the object knows
things the object does
Ih| n]s zn e|jcr! knews z|ee! | !sc|f zrc rz| |c4
|nstance var|ab|es
Ih| n]s zn e|jcr! rzn 4e zrc rz| |c4
methods
3or
t|t|e
art|st
setT|t|e(}
setArt|st(}
p|ay(}
| ns!znrc
vzr| z||cs
(state}
mc!he4s
(behav|or}
knews
4ecs
Things an ol|cci aloui iiscll aic callcu instancc
variablcs. Thcy icicscni an ol|cci`s siaic ihc uaia), anu
can havc uniquc valucs loi cach ol|cci ol ihai iyc.
Th|nk of instance as another way of say|ng ob]ect.
Things an ol|cci can aic callcu mcthods. Whcn you
ucsign a class, you ihinI aloui ihc uaia an ol|cci will nccu
io Inow aloui iiscll, anu you also ucsign ihc mcihous
ihai ociaic on ihai uaia. Ii`s common loi an ol|cci io
havc mcihous ihai icau oi wiiic ihc valucs ol ihc insiancc
vaiiallcs. Ioi cxamlc, Alaim ol|ccis havc an insiancc
vaiiallc io holu ihc alaimTimc, anu iwo mcihous loi
gciiing anu sciiing ihc alaimTimc.
So ol|ccis havc insiancc vaiiallcs anu mcihous, lui ihosc
insiancc vaiiallcs anu mcihous aic ucsigncu as aii ol ihc
class.
+,-+ :+ ,-+:.|
Pill in what a television ob|ect
might need to know and do.
A|arr
a|armT|me
a|armHode
setA|armT|me(}
getA|armT|me(}
|sA|arm8et(}
snooze(}
knews
4ecs
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
35
What's the difference between
a class and an ob]ect?
A class is a bIueprint Ior an objcct. Ii iclls ihc
viiiual machinc io maIc an ol|cci ol ihai
aiiiculai iyc. Each ol|cci mauc liom ihai
class can havc iis own valucs loi ihc
insiancc vaiiallcs ol ihai class. Ioi
cxamlc, you mighi usc ihc Buiion
class io maIc uozcns ol uillcicni
luiions, anu cach luiion mighi havc
iis own coloi, sizc, shac, lalcl, anu so on.
r|zss |s ne! zn e|jcr!.
||e! | !s esc4 !e rens!rer! !hcmI

j[ z( j( ([j, wzy...
One analogy for ob|ects is a packet of unused Polodex cards.
Lach card has the same blank fields (the instance variables). when
you fill out a card you are creating an instance (ob|ect), and the
entries you make on that card represent its state.
The methods of the class are the things you do to a particular card,
getName( ), changeName( ), setName( ) could all be methods for
class Polodex.
So, each card can the same things (getName( ), changeName( ),
etc.), but each card things unique to that particular card.
An object is Iike one entry in your address book.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
36 chapter 2
class DogTestDrive {
public static void main (String[] args) {
Dog d = new Dog();
d.size = 40;
d.bark();
}
}
000
s|ze
oreed
rare
oar|()
making objects
class Dog {
int size;
String breed;
String name;
void bark() {
System.out.println(Ruff! Ruff!);
}
}
Mzk|n] yeer f|rs! e|jcr!
So whai uocs ii iaIc io cicaic anu usc an ol|cci. You nccu wo classcs. Onc
class loi ihc iyc ol ol|cci you wani io usc Dog, AlaimClocI, Tclcvision,
cic.) anu anoihci class io e youi ncw class. Thc ee. class is whcic you ui
ihc main mcihou, anu in ihai main) mcihou you cicaic anu acccss ol|ccis
ol youi ncw class iyc. Thc icsici class has only onc |ol: io ., ou ihc mcih-
ous anu vaiiallcs ol youi ncw ol|cci class iyc.
Iiom ihis oini loiwaiu in ihc looI, you`ll scc iwo classcs in many ol
oui cxamlcs. Onc will lc ihc .enI class - ihc class whosc ol|ccis wc
ically wani io usc, anu ihc oihci class will lc ihc ee. class, which wc
call <wLne.e.You.CInNneI> TestDrive. Ioi cxamlc, il wc maIc a
Bungee class, wc`ll nccu a BungeeTestDrive class as wcll. Only ihc
<oeCInNne>TestDrive class will havc a main) mcihou, anu iis solc
uiosc is io cicaic ol|ccis ol youi ncw iyc ihc noi-ihc-icsici class), anu
ihcn usc ihc uoi ociaioi .) io acccss ihc mcihous anu vaiiallcs ol ihc ncw
ol|ccis. This will all lc mauc siunningly clcai ly ihc lollowing cxamlcs.
Write your cIuss
class DogTestDrive {
public static void main (String[] args) {
// Dog test code goes here
}
}

Write u tester {TestDrive} cIuss

In your tester muke un object und uccess


the object's vuriubIes und methods
-:l.-:- .-.|-:
. --l-
-:l
. -
.- -
-l
-
|-
-'-- ---. -l
:-
-
- l
- l
- --
l
:l
-`
-.- . l- --:l
-:- l- -l ---.l-- |`
l- :-l l- :-- - l- l-
.- l- :.|| l: .-|` --l-

-l
---.l
--
7he dot operator (.) gives
you access to an object's
state and behavior (instance
variabIes and methods).
// make a new object
Dog d = new Dog(),
// teII it to bark by using the
// dot operator on the
// variabIe to caII bark()
d.bark(),
// set its size using the
// dot operator
d.size = 40,
The Dot Operutor {,}
If you oIreody hove some OO sovvy,
you'II know we're nof using encopsuIofion.
We'II gef fhere in chopfer 4.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
37
+,-+ :+ ,-+:.|
oojecl 1
oojecl 2
oojecl 3
l|l|e
erre
ral|r
l|l|e
erre
ral|r
l|l|e
erre
ral|r
V0vlE
l|l|e
erre
ral|r
p|ayll()
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;
}
}
Mzk|n] zn4 !cs!|n] Mev|c e|jcr!s
The MovieTestDrive class creates ob|ects (instances) of
the Movie class and uses the dot operator (.) to set the
instance variables to a specific value. The MovieTestDrive
class also invokes (calls) a method on one of the ob|ects.
Pill in the chart to the right with the values the three
ob|ects have at the end of main().
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
38 chapter 2
CuessCame
p1
p2
p3
slarl0are()
get the heck out of main
0e|rk| 0c! ee! ef mz|n|
As long as you`ic in main), you`ic noi ically in Ol|ccivillc. Ii`s hnc loi a icsi
iogiam io iun wiihin ihc main mcihou, lui in a iiuc OO alicaiion, you
nccu ol|ccis ialIing io oihci ol|ccis, as ooscu io a siaiic main) mcihou
cicaiing anu icsiing ol|ccis.
Ihc ! we escs ef mz|n:
to test your reaI cIass
to launch/start your Java application
A ical ]ava alicaiion is noihing lui ol|ccis ialIing io oihci ol|ccis. In ihis
casc, nII.r mcans ol|ccis calling mcihous on onc anoihci. On ihc icvious
agc, anu in chaici 4 , wc looI ai using a main) mcihou liom a scaiaic
TcsiDiivc class io cicaic anu icsi ihc mcihous anu vaiiallcs ol anoihci class. In
chaici 6 wc looI ai using a class wiih a main) mcihou io siaii ihc lall iolling
on a .enI ]ava alicaiion ly maIing ol|ccis anu ihcn iuining ihosc ol|ccis
loosc io iniciaci wiih oihci ol|ccis, cic.)
As a sncaI icvicw`, ihough, ol how a ical ]ava alicaiion mighi lchavc,
hcic`s a liiilc cxamlc. Bccausc wc`ic siill ai ihc cailicsi siagcs ol lcaining ]ava,
wc`ic woiIing wiih a small ioolIii, so you`ll hnu ihis iogiam a liiilc clunIy
anu inclhcicni. You mighi wani io ihinI aloui whai you coulu uo io imiovc
ii, anu in laici chaicis ihai`s cxacily whai wc`ll uo. Don`i woiiy il somc ol ihc
couc is conlusing, ihc Icy oini ol ihis cxamlc is ihai ol|ccis ialI io ol|ccis.
Ihc 0ecss|n] 0zmc
Summary:
The guessing game involves a 'game' ob|ect and three 'player' ob|ects. The game gen-
erates a random number between 0 and 9, and the three player ob|ects try to guess
it. (we didn't say it was a really game.)
CIasses:
GuessGame.class Player.class GameLauncher.class
7he Logic:
l) The GameLauncher class is where the application starts, it has the main) method.
2) |n the main) method, a GuessGame ob|ect is created, and its startGame() method
is called.
3) The GuessGame ob|ect's startGame() method is where the entire game plays out.
|t creates three players, then "thinks of a random number (the target for the players
to guess). |t then asks each player to guess, checks the result, and either prints out
information about the winning player(s) or asks them to guess again.
P|ayer
ruroer
uess()
-:l.-:-
.-.|-:

--l- l--- |.]--:


l

-
-
-
-

-
- l

:
|.
]
-
-
-
-
::-

-
-
l


-
- -
.

-
-
::
CameLauncher
ra|r(3lr|r[| ars)
-
.

-
: .

6
-
-
::6
.
-
- -

-
:
l
.
-
l
-
||: l
l
- :l
.
-
l
6
.
-
-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
39
public class {
Player p1;
Player p2;
Player p3;
public void startGame() {
p1 = new Player();
p2 = new Player();
p3 = new Player();

int guessp1 = 0;
int guessp2 = 0;
int guessp3 = 0;
boolean p1isRight = false;
boolean p2isRight = false;
boolean p3isRight = false;
int targetNumber = (int) (Math.random() * 10);
System.out.println(I'm thinking of a number between 0 and 9...);
while(true) {
System.out.println(Number to guess is + targetNumber);
p1.guess();
p2.guess();
p3.guess();
guessp1 = p1.number;
System.out.println(Player one guessed + guessp1);
guessp2 = p2.number;
System.out.println(Player two guessed + guessp2);
guessp3 = p3.number;
System.out.println(Player three guessed + guessp3);

if (guessp1 == targetNumber) {
p1isRight = true;
}
if (guessp2 == targetNumber) {
p2isRight = true;
}
if (guessp3 == targetNumber) {
p3isRight = true;
}
if (p1isRight || p2isRight || p3isRight) {

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
} else {
// we must keep going because nobody got it right!
System.out.println(Players will have to try again.);
} // end if/else
} // end loop
} // end method
} // end class
6--::6.-- .: l--- -:l.-:-
.-.|-: -- l- l--- ||.]--
--:l:
:--.l- l--- ||.]-- --:l: .-
.::- l-- l- l- l--- ||.]--
-:l.-:- .-.|-:
-:|.-- l--- .-.|-: l- -| l-
l--- --::-: l- ||.]--: -.-
-:|.-- l--- .-.|-: l- -| . l--- --
.|:- .:- -- l- |.]--': .-:---
-.- . 'l.--l' ----- l.l l-
|.]--: .- l- --::
:.|| -.: |.]--': --::|` --l-
-l -.: |.]--': --:: |l- --:-|l - l--
--::|` --l- -----` ] .::-::- l-
----- .-.|- - -.: |.]--
:-: -.: |.]--': --:: l- :-- l -.l:-:
l- l.--l ----- | . |.]-- : -l,
l-- :-l l.l |.]--': .-.|- l- - l---
|-------, -- :-l l .|:- ] -.-|l`
|.]-- --- 6 |.]-- l-- 6 |.]-- l--- : -l
|l- || ---.l-- --.-: 6`
-l---:-, :l.] - l- |-- .- .: l-
|.]--: -- .--l-- --::
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
40 chapter 2
File Edit Window Help Explode
%java GameLauncher
I'm thinking of a number between 0 and 9...
Number to guess is 7
I'm guessing 1
I'm guessing 9
I'm guessing 9
Player one guessed 1
Player two guessed 9
Player three guessed 9
Players will have to try again.
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.
Dutput (it wiII be different each time you run it)
Kenn| n] !hc 0ecss| n] 0zmc
Guessing Game
public class Player {
int number = 0; // where the guess goes

public void guess() {
number = (int) (Math.random() * 10);
System.out.println(I'm guessing
+ number);
}
}
public class GameLauncher {
public static void main (String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
Juvu tukes out the
Surbuge
Lach time an ob|ect is created
in 1ava, it goes into an area of
memory known as 7he Heap.
All ob|ectsno matter when, where,
or how they're created - live on the
heap. 8ut it's not |ust any old memory
heap, the 1ava heap is actually called the
Carbage-CoIIectibIe Heap. when you
create an ob|ect, 1ava allocates memory
space on the heap according to how
much that particular ob|ect needs. An
ob|ect with, say, l5 instance variables,
will probably need more space than an
ob|ect with only two instance variables.
8ut what happens when you need to
reclaim that spaceI How do you get an
ob|ect out of the heap when you're done
with itI 1ava manages that memory
for you! when the 1vM can 'see' that an
ob|ect can never be used again, that
ob|ect becomes el||ole lot otooe
collect|on. And if you're running low on
memory, the Garbage Collector will run,
throw out the unreachable ob|ects, and
free up the space, so that the space can
be reused. |n later chapters you'll learn
more about how this works.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
41
8ll P0lk5
0ojecl-or|erled prorarr|r |els you exlerd
a prorar W|l|oul |av|r lo louc| prev|ous|y-
lesled, Wor||r code.
A|| Java code |s del|red |r a c|ass.
A c|ass descr|oes |oW lo ra|e ar oojecl ol
l|al c|ass lype. A c|ass |s ||ke a b|uepr|nt.
Ar oojecl car la|e care ol |lse|l, you dor'l
|ave lo |roW or care nou l|e oojecl does |l.
Ar oojecl knows l||rs ard does l||rs.
T||rs ar oojecl |roWs aooul |lse|l are ca||ed
|nstance var|ab|es. T|ey represerl l|e srare
ol ar oojecl.
T||rs ar oojecl does are ca||ed methods.
T|ey represerl l|e oenav|or ol ar oojecl.
w|er you creale a c|ass, you ray a|so Warl
lo creale a separale lesl c|ass W||c| you'||
use lo creale oojecls ol your reW c|ass lype.
A c|ass car |nher|t |rslarce var|ao|es ard
rel|ods lror a rore aoslracl superc|ass.
Al rurl|re, a Java prorar |s rol||r rore
l|ar oojecls 'la|||r' lo ol|er oojecls.
(-,- a,- |
oa|| qa--(:|-

What if I need gIobaI
variabIes and methods! How
do I do that if everything has to
go in a cIass!

There isn't a concept of
'global' variables and methods in
a 1ava OO program. |n practical
use, however, there are times
when you want a method (or
a constant) to be available
to any code running in any
part of your program. Think
of the random() method in
the Phrase-O-Matic app, it's a
method that should be callable
from anywhere. Or what about
a constant like |I ou'll learn
in chapter l0 that marking
a method as public and
static makes it behave much
like a 'global'. Any code, in any
class of your application, can
access a public static method.
And if you mark a variable as
public, static, and h nal
- you have essentially made a
globally-available constont.

7hen how is this object-
oriented if you can stiII make
gIobaI functions and gIobaI
data!

Pirst of all, everything
in 1ava goes in a class. So the
constant for | and the method
for random(), although both
public and static, are defined
within the Math class. And you
must keep in mind that these
static (global-like) things are the
exception rather than the rule
in 1ava. They represent a very
special case, where you don't
have multiple instances/ob|ects.

What is a 1ava program!
What do you actuaIIy Jeliver!

A 1ava program is a pile
of classes (or at least one class).
|n a 1ava application, one of
the classes must have a main
method, used to start-up the
program. So as a programmer,
you write one or more classes.
And those classes are what you
deliver. |f the end-user doesn't
have a 1vM, then you'll also
need to include that with
your application's classes,
so that they can run your
program. There are a number
of installer programs that
let you bundle your classes
with a variety of 1vM's (say, for
different platforms), and put it all
on a CD-POM. Then the end-user
can install the correct version of
the 1vM (assuming they don't
already have it on their machine.)

What if I have a hundred
cIasses! Dr a thousand! Isn't
that a big pain to deIiver
aII those individuaI Ies!
Can I bundIe them into one
Alicnrien 7hing!

es, it would be a big
pain to deliver a huge bunch of
individual files to your end-users,
but you won't have to. ou can
put all of your application files
into a 1ava Archive - o .jot l|le -
that's based on the pkzip format.
|n the |ar file, you can include
a simple text file formatted as
something called a mon|lest, that
defines which class in that |ar
holds the main() method that
should run.

A cIass is Iike a recipe.


Dbjects are Iike
cookies.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
42 chapter 2

class TapeDeck {
boolean canRecord = false,
void playTape{| {
System.out.println{"tape playing"|,
}
void recordTape{| {
System.out.println{"tape recording"|,
}
}
class TapeDeckTestDrive {
public static void main{String args| {
t.canRecord = true,
t.playTape{|,
if {t.canRecord == true| {
t.recordTape{|,
}
}
}

class DVDPlayer {
boolean canRecord = false,
void recordDVD{| {
System.out.println{"DVD recording"|,
}
}
class DVDPlayerTestDrive {
public static void main{String args| {
DVDPlayer d = new DVDPlayer{|,
d.canRecord = true,
d.playDVD{|,
if {d.canRecord == true| {
d.recordDVD{|,
}
}
}
[ze[ | ([ ]zvz |j], n ([j, zg
,n(, z e]( ,ae |j].
(a j j, ( ]zy ej] zn]
](jn w[([ ze[ |
([, |j], wj]] ej].
]| ([y wn'( ej],
[w wa]] ya |jy ([,
zn] j| ([y ] ej],
w[z( wa]] ([j a(a(/
] ge eomgj|e;

exercise: Be the CompiIer


Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
cIasses and objects
43
A 1ava program is all scrambled up on
the fridge. Can you reconstruct the
code snippets to make a working 1ava
program that produces the output listed
belowI 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.
boolean topHat = true,
boolean snare = true,
void playSnare{| {
System.out.println{"bang bang ba~bang"|,
}
if {d.snare == true| {
d.playSnare{|,
}
d.snare = false,
class DrumKitTestDrive {
d.playTopHat{|,
public static void main{String args| {
File Edit Window Help Dance
% java DrumKitTestDrive
bang bang ba-bang
ding ding da-ding
void playTopHat {| {
System.out.println{"ding ding da~ding"|, }
class DrumKit {
DrumKit d = new DrumKit{|,
CaJe Kagaets
d.playSnare{|,

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
44 chapter 2
x 3
x 4
x < 4
x < 5
x > 0
x > l

our is to take code snippets from
the pool and place them into the
blank lines in the code. ou may
use the same snippet more than
once, and you won't need to use
all the snippets. our is to
make classes that will compile and
run and produce the output listed.
public class EchoTestDrive {
public static void main{String args| {
Echo el = new Echo{|,
_________________________
int x = 0,
while { ___________ | {
el.hello{|,
__________________________
if { ____________ | {
e2.count = e2.count + l,
}
if { ____________ | {
e2.count = e2.count + el.count,
}
x = x + l,
}
System.out.println{e2.count|,
}
}
class ____________ {
int _________ = 0,
void ___________ {
System.out.println{"helloooo... "|,
}
}
Note: ach snippet
from the pooI can be
used more than oncel
File Edit Window Help mplode
%java EchoTestDrive
helloooo...
helloooo...
helloooo...
helloooo...
10
Dutput
el el + l,
el count + l,
el.count count + l,
el.count el.count + l,
e2 el,
Lcho e2,
Lcho e2 el,
Lcho e2 new Lcho( ),
x
y
e2
count
Lcho
Tester
echo( )
count( )
hello( )
onus uestion l
|f the last line of output was
24 instead of 10 how would
you complete the puzzle I
puzzIe: PooI PuzzIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
45

I am compiIed from a .java fiIe.


My instance variabIe vaIues can
be different from my buddy's
vaIues.
I behave Iike a tempIate.
I Iike to do stuff.
I can have many methods.
I represent 'state'.
I have behaviors.
I am Iocated in objects.
I Iive on the heap.
I am used to create object instances.
My state can change.
I decIare methods.
I can change at runtime.

A bunch of 1ava components, in full costume, are playing a party


game, "who am |I They give you a clue, and you try to guess who
they are, based on what they say. Assume they always tell the truth
about themselves. |f they happen to say something that could be true
for more than one of them, choose all for whom that sentence can
apply. Pill in the blanks next to the sentence with the names of one or
more attendees. The first one's on us.
7onight's attendees:
CIass Method Dbject Instance variabIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
46 chapter 2
A

Code Mognefs:
File Edit Window Help Dance
% java DrumKitTestDrive
bang bang ba-bang
ding ding da-ding
class DrumKit {
boolean topHat = true,
boolean snare = true,
void playTopHat{| {
System.out.println{"ding ding da~ding"|,
}
void playSnare{| {
System.out.println{"bang bang ba~bang"|,
}
}
class DrumKitTestDrive {
public static void main{String args| {

DrumKit d = new DrumKit{|,
d.playSnare{|,
d.snare = false,
d.playTopHat{|,
if {d.snare == true| {
d.playSnare{|,
}
}
}
class TapeDeck {
boolean canRecord = false,
void playTape{| {
System.out.println{"tape playing"|,
}
void recordTape{| {
System.out.println{"tape recording"|,
}
}
class TapeDeckTestDrive {
public static void main{String args| {

TupeDeck t = new TupeDeck{ };
t.canRecord = true,
t.playTape{|,
if {t.canRecord == true| {
t.recordTape{|,
}
} We've got the tempIute now we huve
} to muke un object |
class DVDPlayer {
boolean canRecord = false,
void recordDVD{| {
System.out.println{"DVD recording"|,
}
void pIuyDVD { } {
System,out,printIn{"DVD pIuying"};
}
}
class DVDPlayerTestDrive {
public static void main{String args| {
DVDPlayer d = new DVDPlayer{|,
d.canRecord = true,
d.playDVD{|,
if {d.canRecord == true| {
d.recordDVD{|,
}
} The Iine: d,pIuyDVD{ }; wouIdn't
} compiIe without u method |
]e;ejze o|ajoz

8e fhe CompiIer:
exercise soIutions
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
47
public class EchoTestDrive {
public static void main{String args| {
Echo el = new Echo{|,
Echo eZ ~ new Echo( ), // fhe correcf onswer
- or -
Echo eZ ~ eI, // is fhe bonus onswerl
int x = 0,
while { x 4 | {
el.hello{|,
eI.counf ~ eI.counf + I,
if { x ~~ 3 | {
e2.count = e2.count + l,
}
if { x 0 | {
e2.count = e2.count + el.count,
}
x = x + l,
}
System.out.println{e2.count|,
}
}
class Echo {
int counf = 0,
void heIIo( ) {
System.out.println{"helloooo... "|,
}
}
File Edit Window Help Assimilate
%java EchoTestDrive
helloooo...
helloooo...
helloooo...
helloooo...
10
I am compiIed from a .java fiIe.
My instance variabIe vaIues can be
different from my buddy's vaIues.
I behave Iike a tempIate.
I Iike to do stuff.
I can have many methods.
I represent 'state'.
I have behaviors.
I am Iocated in objects.
I Iive on the heap.
I am used to create object
instances.
My state can change.
I decIare methods.
I can change at runtime.
:|.::

--:l
:|.::
--:l, --l-
:|.::, --:l
-:l.-:- .-.|-
--:l, :|.::
--l-, -:l.-:- .-.|-
--:l
:|.::
--:l, -:l.-:- .-.|-
:|.::
--:l, -:l.-:- .-.|-

ygo m J/
Mofe: bofh cIosses ond objecfs ore soid fo hove sfofe ond behovior.
They're defned in fhe cIoss, buf fhe objecf is oIso soid fo 'hove'
fhem. Pighf now, we don'f core where fhey fechnicoIIy Iive.
]azz|e o|ajoz
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
3 primitives and references
this is a new chapter 49
VariabIes come in two fIavors: primitive and reference. So far you've
used variables in two placesas ob|ect state (instance variables), and as IocaI variables
(variables declared within a methoJ). Later, we'll 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).
ou've seen variables declared as simple primitive integer values (type ). ou've seen
variables declared as something more compIex like a String or an array. 8ut there's gotta be
more to Iife than integers, Strings, and arrays. what if you have a PetOwner ob|ect with a Dog
instance variableI Or a Car with an LngineI |n this chapter we'll unwrap the mysteries of 1ava
types and look at what you can Jeclote as a variable, what you can ut in a variable, and what you
can Jo with a variable. And we'll finally see what life is ttuly like on the garbage-collectible heap.
Know Your Variables
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
50 chapter 3
decIaring a variabIe
Pcr|zr|n] z vzr|z||c
]ava carcs about typc. Ii won`i lci you uo
somcihing lizaiic anu uangcious liIc siull a
Giiallc iclcicncc inio a Rallii vaiiallc-whai
hacns whcn somconc iiics io asI ihc so-callcu
Fnbb. io . Anu ii won`i lci you ui a
uoaiing oini numlci inio an inicgci vaiiallc,
unlcss you nIrowIeJe o Le o.Ie. ihai you
Inow you mighi losc iccision liIc, cvciyihing
alici ihc uccimal oini).
Thc comilci can soi mosi iollcms:
Rabbit hopper = new Giraffe();
Don`i cxcci ihai io comilc. TLnrIuII,.
Ioi all ihis iyc-salciy io woiI, you musi ucclaic
ihc iyc ol youi vaiiallc. Is ii an inicgci. a Dog.
A singlc chaiacici. Vaiiallcs comc in iwo uavois:
primitive anu object re[erence. Piimiiivcs holu
lunuamcnial valucs ihinI: simlc lii aiicins)
incluuing inicgcis, loolcans, anu uoaiing oini
numlcis. Ol|cci iclcicnccs holu, wcll, .ee.ere
io obe gcc, uiun`i Ln clcai ii u.)
Wc`ll looI ai iimiiivcs hisi anu ihcn movc
on io whai an ol|cci iclcicncc ically mcans.
Bui icgaiulcss ol ihc iyc, you musi lollow iwo
ucclaiaiion iulcs:
Bcsiucs a iyc, a vaiiallc nccus a namc, so ihai
you can usc ihai namc in couc.
variabIes must have a type
int count;
l]- -.--
).. :.--: .--l l]-
/
-- :.-'l -l . 6
-.-
- .
.l .-.|-
variabIes must have a name
Noic: Whcn you scc a siaicmcni liIc: an ol|cci
ol typc X", ihinI ol ,e anu In as synonyms.
Wc`ll ichnc ihai a liiilc moic in laici chaicis.)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
51
|4 ||kc z 4ee||c merhz, ne, mzkc | ! zn |n!.
Whcn you ihinI ol ]ava vaiiallcs, ihinI ol cus. Collcc cus, ica cus, giani
cus ihai holu lois anu lois ol lcci, ihosc lig cus ihc ocoin comcs in ai
ihc movics, cus wiih cuivy, scxy hanulcs, anu cus wiih mciallic iiim ihai
you lcaincu can ncvci, cvci go in ihc miciowavc.
A variablc is just a cup. A containcr. It hoIds somcthing.
Ii has a sizc, anu a iyc. In ihis chaici, wc`ic going io looI hisi ai ihc
vaiiallcs cus) ihai holu primitivcs, ihcn a liiilc laici wc`ll looI ai cus
ihai holu .ee.ere o obe. Siay wiih us hcic on ihc wholc cu analogy-as
simlc as ii is iighi now, ii`ll givc us a common way io looI ai ihings whcn
ihc uiscussion gcis moic comlcx. Anu ihai`ll hacn soon.
Piimiiivcs aic liIc ihc cus ihcy havc ai ihc collcchousc. Il you`vc lccn io a
SiailucIs, you Inow whai wc`ic ialIing aloui hcic. Thcy comc in uillcicni
sizcs, anu cach has a namc liIc shoii`, iall`, anu, I`u liIc a
gianuc` mocha hall-call wiih cxiia whicu cicam".
You mighi scc ihc cus uislaycu on ihc counici,
so you can oiuci aioiiaicly:
Anu in ]ava, iimiiivcs comc in uillcicni sizcs, anu ihosc sizcs
havc namcs. Whcn you ucclaic a vaiiallc in ]ava,
you musi ucclaic ii wiih a sccihc iyc. Thc
loui coniaincis hcic aic loi ihc loui
inicgci iimiiivcs in ]ava.
Each cu holus a valuc, so loi ]ava iimiiivcs, iaihci ihan saying, I`u liIc a
iall licnch ioasi", you say io ihc comilci, I`u liIc an ini vaiiallc wiih ihc
numlci 90 lcasc." Excci loi onc iiny uillcicncc... in ]ava you also havc io
givc youi cu a rne. So ii`s aciually, I`u liIc an ini lcasc, wiih ihc valuc
ol 24S6, anu namc ihc vaiiallc height." Each iimiiivc vaiiallc has a hxcu
numlci ol liis cu sizc). Thc sizcs loi ihc six numciic iimiiivcs in ]ava
aic shown lclow:
smoII shorf foII gronde
Iong inf shorf byfe
byfe shorf inf Iong oof doubIe

Type 8|l 0epl| va|ue Rare
boolean and char
boolean (1vM-specific) or
char l6 bits 0 to 65535
numeric {all are signed}
integer
byte 8 bits -l28 to l27
short l6 bits -32768 to
32767
int 32 bits -2l47483648
to 2l47483647
long 64 bits -huge to huge
hoating point
float 32 bits varies
double 64 bits varies
Primitive declarations
with assignments:
int x,
x 234,
byte b 89,
boolean isPun true,
double d 3456.98,
char c 'f',
int z x,
boolean isPunkPock,
isPunkPock false,
boolean powerOn,
powerOn isPun,
long big 3456789,
float f 32.5f,

N-l- l- '' 6-ll. .- l.l
-l . |-.l, -:.-:- ).. l-:
.-]l- -l . |-.l- --l :
. --|-, --|-:: ]-- -:- ''
Primitive Types
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
52 chapter 3
primitive assignment
Yee rcz||y 4en! wzn! !e sp||| !hz!...
Bc surc thc valuc can ht into thc variablc.
You can`i ui a laigc valuc inio a
small cu.
Wcll, OK, you can, lui you`ll
losc somc. You`ll gci, as wc say,
.IIne. Thc comilci iiics io
hcl icvcni ihis il ii can icll
liom youi couc ihai somcihing`s
noi going io hi in ihc coniainci
vaiiallc/cu) you`ic using.
Ioi cxamlc, you can`i oui an
ini-lull ol siull inio a lyic-sizcu
coniainci, as lollows:
int x = 24;
byte b = x;
//won't work!!
Why uocsn`i ihis woiI, you asI. Alici all, ihc valuc ol : is 24, anu 24 is uchniicly
small cnough io hi inio a lyic. You Inow ihai, anu we Inow ihai, lui all ihc
comilci caics aloui is ihai you`ic iiying io ui a lig ihing inio a small ihing,
anu ihcic`s ihc o.b.I., ol silling. Don`i cxcci ihc comilci io Inow whai ihc
valuc ol : is, cvcn il you hacn io lc allc io scc ii liicially in youi couc.
You can assign a valuc to a variablc in onc oI scvcral ways including:
iyc a I.e.nI valuc alici ihc cquals sign x, isGoou , cic.)
assign ihc valuc ol onc vaiiallc io anoihci x y)
usc an cxicssion comlining ihc iwo x y + )
In ihc cxamlcs lclow, ihc liicial valucs aic in lolu iialics:
int size = 32; dec|are ar |rl rared s|ze, ass|r |l l|e va|ue J2
char initial = `j'; dec|are a c|ar rared |n|r|a|, ass|r |l l|e va|ue 'j
double d = 456.709; dec|are a douo|e rared o, ass|r |l l|e va|ue 456.709
boolean isCrazy; dec|are a ooo|ear rared |s0razy (ro ass|rrerl)
isCrazy = true; ass|r l|e va|ue rrue lo l|e prev|ous|y-dec|ared |s0razy
int y = x + 456; dec|are ar |rl rared y, ass|r |l l|e va|ue l|al |s l|e sur
ol W|alever x |s roW p|us 456
+,-+ :+ ,-+:.|
The compiler won't let you put
a value from a large cup into
a small one. 8ut what about
the other waypouring a
small cup into a big oneI Ne
reblem.
8ased on what you know
about the size and type of the
primitive variables, see if you
can figure out which of these
are legal and which aren't.
we haven't covered all the
rules yet, so on some of these
you'll have to use your best
|udgment. 7i: The compiler
always errs on the side of
safety.
Prom the following list, Circle
the statements that would be
legal if these lines were in a
single method:
1. int x = 34.5;
2. boolean boo = x;
3. int g = 17;
4. int y = g;
5. y = y + 10;
6. short s;
7. s = y;
8. byte b = 3;
9. byte v = b;
10. short n = 12;
11. v = n;
12. byte k = 128;
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
primitives and references
53
M
.

-
l

l
:

7he e|ht t|m


|t|ve tyes ote:
boolean char byte short int Iong float double
AnJ hetes o m
nem
on|c lot tem
em
oet|n them
:

e C
areful!
ears Shouldn't Ingest Large
Furry D
ogs
ll you m
ole u yout own, |tll st|cl even oettet.
8_ C_ 8_ 5_ l_ l_ l_ 0_
Bzrk zwzy frem !hz! kcywer4|
You Inow you nccu a namc anu a iyc loi youi vaiiallcs.
You alicauy Inow ihc iimiiivc iycs.
But whot con you use os nomes Thc iulcs aic simlc. You
can namc a class, mcihou, oi vaiiallc accoiuing io ihc
lollowing iulcs ihc ical iulcs aic slighily moic ucxillc,
lui ihcsc will Icc you salc):
t must start with a letter, underscore {_}, or
dollar sign {S}. You can't start a name with a
number.
After the hrst character, you can use numbers as
well. Just don't start it with a number.
t can be anything you like, sub]ect to those two
rules, ]ust so long as it isn't one of Java's reserved
words.
aic Icywoius anu oihci ihings) ihai ihc comilci iccognizcs.
Anu il you ically wani io lay conlusc-a-comilci, ihcn |usi .,
using a icscivcu woiu as a namc.
You`vc alicauy sccn somc icscivcu woius whcn wc looIcu ai
wiiiing oui hisi main class:
public static void
Anu ihc iimiiivc iycs aic icscivcu as wcll:
boolean char byte short int long oat double
Bui ihcic aic a loi moic wc havcn`i uiscusscu yci. Evcn il you uon`i
nccu io Inow whai ihcy mcan, you siill nccu io Inow you can`i usc
cm youiscll. Do not-urJe. nr, ..unre-try to memorize these
now. To maIc ioom loi ihcsc in youi hcau, you`u iolally havc io
losc somcihing clsc. IiIc whcic youi cai is aiIcu. Don`i woiiy, ly
ihc cnu ol ihc looI you`ll havc mosi ol ihcm uown colu.

-
-
'l
-
:-
.
-
]
-

-
:-

-
-
]
-
-
-
-
-
-
-
.
-
-
:
|eeleer ||e tler iet|le Kee| ir| lerj :ler| jt|lit jrire|e
jre|et|ei e|:|ret| lrel re|ire :|e|it :|rit|lj :rtlreritei |rer:ier| rele|ile il
el:e ie wlile :wi|tl te:e ieletl| ler |reel ter|irte e::er|
tle:: et|eri: imjlemer|: imjer| ir:|erteel ir|erlete rew jetleje :tjer |li:
te|tl lrell |r |lrew |lrew: re|trr reii ter:| je|e ertm
Ih|s !z||c rcscrvc4.
Java's keywords and other reserved words (in no useful order). f you use these for names, the compiler will be very, upset.
Mo moffer whof
you heor, do nof, I repeof,
do Ief me ingesf
onofher Iorge furry dog.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
54 chapter 3
object references
0en!re|||n] yeer Pe] e|jcr!
You Inow how io ucclaic a iimiiivc vaiiallc anu assign ii a
valuc. Bui now whai aloui non-iimiiivc vaiiallcs. In oihci
woius, wLn nbou obe:
There is actuaIIy no such thing as an object variabIe.
There's onIy an object reference variabIe.
An object reference variabIe hoIds bits that represent a
way to access an object.
It doesn't hoId the object itseIf, but it hoIds something
Iike a pointer. Or an address. Except, in Java we don't
reaIIy know what is inside a reference variabIe. We do
know that whatever it is, it represents one and onIy one
object. And the JVM knows how to use the reference to
get to the object.
You can`i siull an ol|cci inio a vaiiallc. Wc olicn ihinI ol
ii ihai way... wc say ihings liIc, I asscu ihc Siiing io ihc
Sysicm.oui.iiniln) mcihou." Oi, Thc mcihou iciuins a Dog",
oi, I ui a ncw Ioo ol|cci inio ihc vaiiallc namcu myIoo."
Bui ihai`s noi whai hacns. Thcic aicn`i giani
cxanuallc cus ihai can giow io ihc sizc ol any
ol|cci. Ol|ccis livc in onc lacc anu onc lacc
only-ihc gailagc collcciillc hca! You`ll
lcain moic aloui ihai laici in ihis chaici.)
Alihough a iimiiivc vaiiallc is lull ol
liis icicscniing ihc aciual voIue ol ihc
vaiiallc, an ol|cci iclcicncc vaiiallc is lull
ol liis icicscniing o woy to get to the
object.
You usc ihc uoi ociaioi .)
on a iclcicncc vaiiallc io say,
usc ihc ihing beo.e ihc uoi io
gci mc ihc ihing ne. ihc uoi." Ioi
cxamlc:
myDog.bark();
mcans, usc ihc ol|cci iclcicnccu ly ihc vaiiallc myDog io
invoIc ihc laiI) mcihou." Whcn you usc ihc uoi ociaioi on
an ol|cci iclcicncc vaiiallc, ihinI ol ii liIc icssing a luiion
on ihc icmoic coniiol loi ihai ol|cci.
Dog d = new Dog{};
d.bark{};
l- - l:
|- l:
1- - . l-
------:- .-.|- .:
. l- ----l- :--l--|
/-- -:- l l- -l l-
--:l l- - :---l-
|--- --l-:`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
55
reference byfe shorf inf Iong
& I JZ 1 [|i| iej|l re| relerer|]
n e|jcr! rcfcrcnrc |s jes!
zne!hcr vzr|z||c vz|ec.
Something that goes in a cup.
DnIy this time, the vaIue is a remote controI.
Wi|h primi|ive voriobles, |he volue ol |he vori
oble is... |he volue (5, 2.Z, 'o).
Wi|h relerence voriobles, |he volue ol |he
vorioble is... bils represenling o woy lo gel lo
o specihc obecl.
You don| know (or core) how ony por|iculor
1VN implemen|s ob[ec| relerences. 5ure, |hey
migh| be o poin|er |o o poin|er |o... bu| even
il you know, you s|ill con| use |he bi|s lor
ony|hing o|her |hon occessing on ob[ec|.
Dog myDog = new Dog();
Tells the 1vM to allocate space for a
reference variable, and names that
variable . The reference variable
is, forever, of type Dog. |n other words,
a remote control that has buttons to
control a Dog, but not a Cat or a 8utton
or a Socket.

DecIore o reference
voriobIe
Dog
m9ej
Dog myDog = new Dog();
Tells the 1vM to allocate space for a
new Dog ob|ect on the heap (we'll
learn a lot more about that process,
especially in chapter 9.)
Creofe on objecf
Dog myDog = new Dog();
The 3 steps of ob]ect
declaration, creation and
assignment
1
2
3
Dog objecf
Dog myDog = new Dog();
Assigns the new Dog to the reference
variable myDog. |n other words,
regrnms rhe remere cenrrel.

Link fhe objecf


ond fhe reference
Dog objecf
Dog
m9ej
We don't care how many 1's and 0's there are in a reference variable.t's up to each
JVM and the phase of the moon.
byte x = 7;
The bits representing 7 go
into the variable. (00000lll).
0
0
0
0
0
I
I
I
Dog myDog = new Dog();
The bits representing a way to get to
the Dog ob|ect go into the variable.
7he eg ebjecr irselI Jees ner ge inre
rhe vnrinblel
--l-
.|--
------:-
.|--
Kcfcrcnrc Vzr|z||c
|r|m| !| vc Vzr|z||c
D
og
o
b
j
e
c
f
Dog
byfe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
56 chapter 3
(-,- a,- |
oa|| qa--(:|-

How big is a reference


variabIe!
ou don't know. Unless
you're cozy with someone on the
1vM's development team, you
don't know how a reference is
represented. There are pointers
in there somewhere, but you
can't access them. ou won't
need to. (OK, if you insist, you
might as well |ust imagine it
to be a 64-bit value.) 8ut when
you're talking about memory
allocation issues, your 8ig
Concern should be about how
many oojects (as opposed to
ob|ect teletences) you're creating,
and how big they (the oojects)
really are.

So, does that mean that


aII object references are the
same size, regardIess of the size
of the actuaI objects to which
they refer!
ep. All references for a
given 1vM will be the same
size regardless of the ob|ects
they reference, but each 1vM
might have a different way of
representing references, so
references on one 1vM may be
smaller or larger than references
on another 1vM.

Can I do arithmetic on a
reference variabIe, increment it,
you know - C stuff!
Nope. Say it with me again,
"1ava is not C.
object references
HeadFirst: So, tell us, what`s lile like lor an object relerence?
Reference: Fretty simple, really. I`m a remote control ano I can be programmeo to
control oillerent objects.
HeadFirst: Do you mean oillerent objects even while you`re running? Like, can you
reler to a Dog ano then nve minutes later reler to a Car?
Reference: Ol course not. Once I`m oeclareo, that`s it. Il I`m a Dog remote control
then I`ll never be able to point ,oops my bao, we`re not supposeo to say iot, I mean r.f.r
to anything but a Dog.
HeadFirst: Does that mean you can reler to only one Dog?
Reference: No. I can be relerring to one Dog, ano then nve minutes later I can reler to
some t/.r Dog. As long as it`s a Dog, I can be reoirecteo ,like reprogramming your remote
to a oillerent TV, to it. Unless... no never mino.
HeadFirst: No, tell me. What were you gonna say?
Reference: I oon`t think you want to get into this now, but I`ll just give you the short
version il I`m markeo as , then once I am assigneo a Dog, I can never be repro-
grammeo to anything else but t/ot one ano only Dog. In other woros, no other object can
be assigneo to me.
HeadFirst: You`re right, we oon`t want to talk about that now. OK, so unless you`re
, then you can reler to one Dog ano then reler to a oillerent Dog later. Can you ever
reler to ot/io ot oll? Is it possible to not be programmeo to anything?
Reference: Yes, but it oisturbs me to talk about it.
HeadFirst: Why is that?
Reference: Because it means I`m , ano that`s upsetting to me.
HeadFirst: You mean, because then you have no value?
Reference: Oh, i a value. I`m still a remote control, but it`s like you brought
home a new universal remote control ano you oon`t have a TV. I`m not programmeo to
control anything. They can press my buttons all oay long, but nothing gooo happens. I
just leel so... useless. A waste ol bits. Granteo, not that many bits, but still. Ano that`s not
the worst part. Il I am the only relerence to a particular object, ano then I`m set to
,oeprogrammeo,, it means that now ooo, can get to that object I hao been relerring to.
HeadFirst: Ano that`s bao because...
Reference: You have to o/? Here I`ve oevelopeo a relationship with this object, an
intimate connection, ano then the tie is suooenly, cruelly, severeo. Ano I will never see
that object again, because now it`s eligible lor |prooucer, cue tragic music| oroo. cll.ctio.
Snill. But oo you think programmers ever consioer t/ot? Snil. Why, o/, can`t I be a primi-
tive? I /ot. o.io o r.f.r.oc.. The responsibility, all the broken attachments...
This week's interview:
Object Reference
1a-a spese3
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
57
8ook

Book b = new Book();


Book c = new Book();
Book d = c;
Declare two 8ook reference
variables. Create two new 8ook
ob|ects. Assign the 8ook ob|ects to
the reference variables.
The two 8ook ob|ects are now living
on the heap.
Peferences: 2
Ob|ects: 2
Declare a new 8ook reference variable.
Pather than creating a new, third 8ook
ob|ect, assign the value of variable to
variable . 8ut what does this meanI
|t's like saying, "Take the bits in , make a
copy of them, and stick that copy into .
Both c and d refer to the same
ob]ect.
The c and d variables hold
two different copies of the
same value. Two remotes
programmed to one TV.
Peferences: 3
Ob|ects: 2
8ook

8
o
o
k
ob
j
e
c
f

8
o
o
k
ob
j
e
c
f

8ook

8
o
o
k
ob
j
e
c
f

8
o
o
k ob
j
e
c
f

8ook

8ook
c = b;
Assign the value of variable to
variable . 8y now you know what
this means. The bits inside variable
are copied, and that new copy is
stuffed into variable .
Both b and c refer to the
same ob]ect.
Peferences: 3
Ob|ects: 2
8ook

8
o
ok o
b
j
e
c
f

8
o
o
k ob
j
e
c
f

I|fc en !hc ]zr|z]c-re||cr!|||c hczp


g
a
r
b
a
g
e

c
o
l
l
e
c
t
i
b
l
e

h
e
a
p
g
a
r
b
a
g
e

c
o
l
l
e
c
t
i
b
l
e

h
e
a
p
g
a
r
b
a
g
e

c
o
l
l
e
c
t
i
b
l
e

h
e
a
p
I
I
Z
Z
I
Z
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
58 chapter 3
8ook

Book b = new Book();


Book c = new Book();
b = c;
Declare two 8ook reference variables.
Create two new 8ook ob|ects. Assign
the 8ook ob|ects to the reference
variables.
The two book ob|ects are now living
on the heap.
Active Peferences: 2
Peachable Ob|ects: 2
Assign the value of variable to variable .
The bits inside variable are copied, and
that new copy is stuffed into variable .
8oth variables hold identical values.
Both b and c refer to the same
ob]ect. Ob]ect 1 is abandoned
and eligible for Garbage Collec-
tion {GC}.
Active Peferences: 2
Peachable Ob|ects: l
Abandoned Ob|ects: l
The first ob|ect that referenced, Ob|ect l,
has no more references. |t's unteochoole.
8ook

8
o
o
k
ob
j
e
c
f

8
o
o
k
ob
j
e
c
f

8ook

8
o
o
k ob
j
e
c
f

8ook
c = null;
Assign the value to variable .
This makes a null teletence, meaning
it doesn't refer to anything. 8ut it's still
a reference variable, and another 8ook
ob|ect can still be assigned to it.
Ob]ect 2 still has an active
reference {b}, and as long
as it does, the ob]ect is not
eligible for GC.
Active Peferences: l
null Peferences: l
Peachable Ob|ects: l
Abandoned Ob|ects: l
I|fc zn4 4cz!h en !hc hczp
g
a
r
b
a
g
e

c
o
l
l
e
c
t
i
b
l
e

h
e
a
p
g
a
r
b
a
g
e

c
o
l
l
e
c
t
i
b
l
e

h
e
a
p
g
a
r
b
a
g
e

c
o
l
l
e
c
t
i
b
l
e

h
e
a
p
objects on the heap
1: -] : l-.:l
.-.-~:-||-:l-- .l

8
o
o
k ob
j
e
c
f

8ook
l|| l-.:l
8ook

--|| ------:-
|--l ---.--- l- .-]l-`
8
o
o
k
ob
j
e
c
f

8
o
o
k
ob
j
e
c
f

I
I
Z
Z
Z
I
N-l ]-l l-.:l
|:.- .: |-- .:
----: l- l`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
59
rrzys zrc e|jcr!s !ee
Thc ]ava sianuaiu liliaiy incluucs
lois ol sohisiicaicu uaia siiuciuics
incluuing mas, iiccs, anu scis
scc Acnuix B), lui aiiays aic
gicai whcn you |usi wani a quicI,
oiucicu, clhcicni lisi ol ihings.
Aiiays givc you lasi ianuom
acccss ly lciiing you usc an inucx
osiiion io gci io any clcmcni in
ihc aiiay.
Evciy clcmcni in an aiiay is |usi
a vaiiallc. In oihci woius, onc ol
ihc cighi iimiiivc vaiiallc iycs
ihinI: Iaigc Iuiiy Dog) oi a
iclcicncc vaiiallc. Anyihing you
woulu ui in a .n..nbIe ol ihai iyc
can lc assigncu io an n..n, eIeer
ol ihai iyc. So in an aiiay ol iyc
ini ini]|), cach clcmcni can holu
an ini. In a Dog aiiay Dog]|) cach
clcmcni can holu... a Dog. No,
icmcmlci ihai a iclcicncc vaiiallc
|usi holus a iclcicncc a icmoic
coniiol), noi ihc ol|cci iiscll. So
in a Dog aiiay, cach clcmcni can
holu a .eoe or.oI io a Dog. Ol
couisc, wc siill havc io maIc ihc
Dog ol|ccis... anu you`ll scc all ihai
on ihc ncxi agc.
Bc suic io noiicc onc Icy ihing
in ihc iciuic alovc - Le n..n, .
nr obe, e.er LouL .` nr n..n, o
.....e.
Arrays arc always objccts, whcthcr
thcy'rc dcclarcd to hold primitivcs
or objcct rcIcrcnccs. Bui you can
havc an aiiay ol|cci ihai`s ucclaicu
io LoIJ iimiiivc valucs. In oihci
woius, ihc aiiay ol|cci can havc
eIeer which aic iimiiivcs, lui
ihc aiiay iiscll is re.e. a iimiiivc.
Rcgaiulcss ol whai ihc aiiay holus,
ihc aiiay iiscll is always an ol|cci!
inf orroy objecf (inf[])
inf[]

nums[0] = 6;
nums[1] = 19;
nums[2] = 44;
nums[3] = 42;
nums[4] = 10;
nums[5] = 20;
nums[6] = 1;

DecIore on inf orroy voriobIe. An orroy voriobIe is


o remofe confroI fo on orroy objecf.
int[] nums;
nums = new int[7];

Creofe o new inf orroy wifh o Iengfh


of 7, ond ossign if fo fhe previousIy-
decIored voriobIe

0ive eoch eIemenf in fhe orroy


on inf voIue.
Pemember, eIemenfs in on inf
orroy ore jusf inf voriobIes.
n zrrzy |s ||kc z !rzy ef reps
inf inf inf inf inf inf inf
N-l:- l.l l- .--.] l:-| : .- --:l,
--- l-- l- 7 -|----l: .-- --l-:
7 -l .-.|-:
7

-
l

.
-

|
-
:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
60 chapter 3
Dog orroy objecf (Dog[])
Dog[]

pets[0] = new Dog();


pets[1] = new Dog();

DecIore o Dog orroy voriobIe


Dog[] pets;
pets = new Dog[7];

Creofe o new Dog orroy wifh


o Iengfh of 7, ond ossign if fo
fhe previousIy-decIored Dog[]
voriobIe pets

Creofe new Dog objecfs, ond


ossign fhem fo fhe orroy
eIemenfs.
Pemember, eIemenfs in o Dog
orroy ore jusf Dog reference
voriobIes. We sfiII need Dogsl
Mzkc zn zrrzy ef Pe]s
Dog Dog Dog Dog Dog Dog Dog
an array of objects
Whz!s m|ss|n]!
Dogsl We have an array
of Dog reIerences, but no
actuaI Dog ebjecrsl
Dog orroy objecf (Dog[])
Dog[]

Dog Dog Dog Dog Dog Dog Dog


D
o
g
O
bj
e
c
f
D
o
g
O
bj
e
c
f
+,-+ :+ ,-+:.|
what is the current value of
pets|2|I ___________
what code would make
pets|3| refer to one of the
two existing Dog ob|ectsI
_______________________
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
61
Dog

rare
oar|()
eal()
c|aseCal()
0en!re| yeer Pe]
|w| !h z rcfcrcnrc vzr|z||cI
Dog do = new Dog();
do.name = Fido;
D
og ob
j
e
c
f

Sfring Wc cicaicu a Dog ol|cci anu


uscu ihc uoi ociaioi on ihc
iclcicncc vaiiallc io acccss
ihc namc vaiiallc.*
Wc can usc ihc iclcicncc
io gci ihc uog io laiI) oi
cai) oi chascCai).
do.bark();
do.chaseCat();

Whz! hzppcns |f !hc Pe] |s |n


z Pe] zrrzy!
Wc Inow wc can acccss ihc Dog`s
insiancc vaiiallcs anu mcihous using
ihc uoi ociaioi, lui
Whcn ihc Dog is in an aiiay, wc uon`i
havc an aciual vaiiallc namc liIc
). Insicau wc usc aiiay noiaiion anu
ush ihc icmoic coniiol luiion uoi
ociaioi) on an ol|cci ai a aiiiculai
inucx osiiion) in ihc aiiay:
Dog[] myDogs = new Dog[3];
myDogs[0] = new Dog();
myDogs[0].name = Fido;
myDogs[0].bark();
Yes We |roW We're rol derorslral|r ercapsu|al|or |ere, oul We're
lry|r lo |eep |l s|rp|e. For roW. we'|| do ercapsu|al|or |r c|apler 1.
Java cares about type.
Once you've declared an array, you
can't put anything in it except things
that are of the declared array type.
For exompIe, you con'f puf o Cof info o Dog
orroy (if wouId be preffy owfuI if someone
fhinks fhof onIy Dogs ore in fhe orroy, so
fhey osk eoch one fo bork, ond fhen fo fheir
horror discover fhere's o cof Iurking.) And
you con'f sfick o double info on int orroy
(spiIIoge, remember7). You con, however,
puf o byte info on int orroy, becouse o
byte wiII oIwoys f f info on int-si;ed cup.
This is known os on impIicit widening, We'II
get into the detuiIs Iuter for now just
remember thut the compiIer won't Iet you
put the wrong thing in un urruy bused on
the urruy's decIured type,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
62 chapter 3
using references
class Dog {
String name;
public static void main (String[] args) {
// make a Dog object and access it
Dog dog1 = new Dog();
dog1.bark();
dog1.name = Bart;
// now make a Dog array
Dog[] myDogs = new Dog[3];
// and put some dogs in it
myDogs[0] = new Dog();
myDogs[1] = new Dog();
myDogs[2] = dog1;
// now access the Dogs using the array
// references
myDogs[0].name = Fred;
myDogs[1].name = Marge;

// Hmmmm... what is myDogs[2] name?
System.out.print(last dog's name is );
System.out.println(myDogs[2].name);
// now loop through the array
// and tell all dogs to bark
int x = 0;
while(x < myDogs.length) {
myDogs[x].bark();
x = x + 1;
}
}
public void bark() {
System.out.println(name + says Ruff!);
}
public void eat() { }
public void chaseCat() { }
}

rare
oar|()
eal()
c|aseCal()
Pe] crzmp|c
File Edit Window Help Howl
%java Dog
null says Ruff!
last dog's name is Bart
Fred says Ruff!
Marge says Ruff!
Bart says Ruff!

8ll P0lk5
var|ao|es core |r lWo l|avors: pr|r|l|ve ard
relererce.
var|ao|es rusl a|Ways oe dec|ared W|l| a rare
ard a lype.
A pr|r|l|ve var|ao|e va|ue |s l|e o|ls represerl|r
l|e va|ue (5, 'a', lrue, 3.111, elc.).
A relererce var|ao|e va|ue |s l|e o|ls
represerl|r a Way lo el lo ar oojecl or l|e
|eap.
A relererce var|ao|e |s |||e a rerole corlro|.
us|r l|e dol operalor (.) or a relererce
var|ao|e |s |||e press|r a oullor or l|e rerole
corlro| lo access a rel|od or |rslarce var|ao|e.
A relererce var|ao|e |as a va|ue ol null W|er
|l |s rol relererc|r ary oojecl.
Ar array |s a|Ways ar oojecl, ever |l l|e array
|s dec|ared lo |o|d pr|r|l|ves. T|ere |s ro suc|
l||r as a pr|r|l|ve array, or|y ar array l|al
pr|r|l|ves.
.--.]: .- . .-.|- '|--l'
l.l -: ]-- l- ----- -
-|----l: - l- .--.]
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
primitives and references
63
[ze[ | ([ ]zvz |j], n ([j, zg
,n(, z e]( ,ae |j].
(a j j, ( ]zy ej] zn]
](jn w[([ ze[ | ([, |j],
wj]] ej]. ]| ([y wn'(
ej], [w wa]] ya
|jy ([/

class Books {
String title,
String author,
}
class BooksTestDrive {
public static void main{String args| {
Books myBooks = new Books3,
int x = 0,
myBooks0.title = "The Grapes of Java",
myBooksl.title = "The Java Gatsby",
myBooks2.title = "The Java Cookbook",
myBooks0.author = "bob",
myBooksl.author = "sue",
myBooks2.author = "ian",
while {x < 3| {
System.out.print{myBooksx.title|,
System.out.print{" by "|,
System.out.println{myBooksx.author|,
x = x + l,
}
}
}

class Hobbits {
String name,
public static void main{String args| {
Hobbits h = new Hobbits3,
int z = 0,
while {z < 4| {
z = z + l,
hz = new Hobbits{|,
hz.name = "bilbo",
if {z == l| {
hz.name = "frodo",
}
if {z == 2| {
hz.name = "sam",
}
System.out.print{hz.name + " is a "|,
System.out.println{"good Hobbit name"|,
}
}
}

] ge eomgj|e;
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
64 chapter 3
A working 1ava program is all scrambled up
on the fridge. Can you reconstruct the code
snippets to make a working 1ava program
that produces the output listed belowI
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!
islands0 = "Bermuda", islandsl = "Fii",
islands2 = "Azores", islands3 = "Cozumel",
class TestArrays {

public static void main{String args| {
int ref,
while {y < 4| {
String islands = new String4,
System.out.print{"island = "|,
int index = new int4,
System.out.println{islandsref|,
File Edit Window Help Bikini
% java TestArrays
island = Fiji
island = Cozumel
island = Bermuda
island = Azores
index0 = l,
indexl = 3,
index2 = 0,
index3 = 2,
y = y + l,
int y = 0,
ref = indexy,

CaJe Kagaets
exercise: Code Magnets
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
65
x x + l,
x x + 2,
x x - l,
x < 4
x < 5

our is to take code snippets from
the pool and place them into the
blank lines in the code. ou may
use the same snippet more than
once, and you won't need to use
all the snippets. our is to
make a class that will compile and
run and produce the output listed.
class Triangle {
double area,
int height,
int length,
public static void main{String args| {
____________
_______________________
while { __________ | {
__________________________
________.height = {x + l| * 2,
________.length = x + 4,
__________________________
System.out.print{"triangle "+x+", area"|,
System.out.println{" = " + _______.area|,
________________
}
______________
x = 27,
Triangle t5 = ta2,
ta2.area = 343,
System.out.print{"y = " + y|,
System.out.println{", t5 area = "+ t5.area|,
}
void setArea{| {
____________ = {height * length| / 2,
}
}
Note: ach snippet
from the pooI can be
used more than oncel
File Edit Window Help Bermuda
%java Triangle
triangle 0, area = 4.0
triangle 1, area = 10.0
triangle 2, area = 18.0
triangle 3, area = ____
y = ______________________
Dutput
Triangle | | ta new Triangle(4),
Triangle ta new | | Triangle|4|,
Triangle | | ta new Triangle|4|,
ta new Triangle(),
ta|x| new Triangle(),
ta.x new Triangle(),
ta|x| setArea(),
ta.x setArea(),
ta|x|.setArea(),
int x,
int y,
int x 0,
int x l,
int y x,
area
ta.area
ta.x.area
ta|x|.area
ta.x
ta(x)
ta|x|
x
y
onus uestionl
Por extra bonus points, use snippets
from the pool to fill in the missing
output (above).
28.0
30.0
4, t5 area l8.0
4, t5 area 343.0
27, t5 area l8.0
27, t5 area 343.0
|---l--: -- --'l -:- . :-.-.l-
l-:l :|.::, -:.-:- --'-- l-]- l-
:.- :.:- -- l- .-`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
66 chapter 3
A short 1ava program is listed to the
right. when '// do stuff' is reached, some
ob|ects and some reference variables
will have been created. our task is
to determine which of the reference
variables refer to which ob|ects. Not all
the reference variables will be used, and
some ob|ects might be referred to more
than once. Draw lines connecting the
reference variables with their matching
ob|ects.
Unless you're way smarter than us,
you probably need to draw diagrams
like the ones on page 55 and 56 of this
chapter. Use a pencil so you can draw
and then erase reference links (the
arrows going from a reference remote
control to an ob|ect).
4 Heap o' 1roub|e
-.l: -.: ------:-
.-.|- -l -.l:-
--:l|:`
/-- -l --l .- l-
-:- ---] ------:-
Reference VariabIes: Heapuiz Dbjects:



class HeapQuiz {
int id = 0;
public static void main(String [] args) {
int x = 0;
HeapQuiz [ ] hq = new HeapQuiz[5];
while ( x < 3 ) {
hq[x] = new HeapQuiz();
hq[x].id = x;
x = x + 1;
}
hq[3] = hq[1];
hq[4] = hq[1];
hq[3] = null;
hq[4] = hq[0];
hq[0] = hq[3];
hq[3] = hq[2];
hq[2] = hq[0];
// do stuff
}
}
hq[0]
hq[I]
hq[Z]
hq[3]
hq[4]
puzzIe: Heap o' TroubIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
67
The case of the pilfered references
It was a dark and stormy night. Tawny strolled into the programmers` bullpen like she
owned the place. She knew that all the programmers would still be hard at work, and she
wanted help. She needed a new method added to the pivotal class that was to be loaded into the
client`s new top-secret Java-enabled cell phone. Heap space in the cell phone`s memory was
as tight as Tawny`s top, and everyone knew it. The normally raucous buzz in the bullpen Iell to
silence as Tawny eased her way to the white board. She sketched a quick overview oI the new
method`s Iunctionality and slowly scanned the room. 'Well boys, it`s crunch time, she purred.
'Whoever creates the most memory eIfcient version oI this method is coming with me to the
client`s launch party on Maui tomorrow... to help me install the new soItware.
The next morning Tawny glided into the bullpen wearing her short Aloha dress.
'Gentlemen, she smiled, 'the plane leaves in a Iew hours, show me what you`ve
got!. Bob went frst; as he began to sketch his design on the white board Tawny
said, 'Let`s get to the point Bob, show me how you handled updating the list oI con-
tact objects. Bob quickly drew a code Iragment on the board:
Contact [] ca = new Contact[10];
while ( x < 10 ) { // make 10 contact objects
ca[x] = new Contact();
x = x + 1;
}
// do complicated Contact list updating stuff with ca
'Tawny I know we`re tight on memory, but your spec said that we had to be able to access
individual contact inIormation Ior all ten allowable contacts, this was the best scheme I could
cook up, said Bob. Kent was next, already imagining coconut cocktails with Tawny, 'Bob,
he said, 'your solution`s a bit kludgy don`t you think? Kent smirked, 'Take a look at this
baby:
Contact refc;
while ( x < 10 ) { // make 10 contact objects
refc = new Contact();
x = x + 1;
}
// do complicated Contact list updating stuff with refc
'I saved a bunch oI reIerence variables worth oI memory, Bob-o-rino, so put away your
sunscreen, mocked Kent. 'Not so Iast Kent!, said Tawny, 'you`ve saved a little memory, but
Bob`s coming with me..
Why did 1awny choose Bob's method over Kent's, when Kent's used less memory?
]Jc_Jna[c
_s[ci
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
68 chapter 3
A

Code Mognefs:
class Books {
String title,
String author,
}
class BooksTestDrive {
public static void main{String args| {
Books myBooks = new Books3,
int x = 0,
myooks[0j = new ooks{}; Pemember: We huve to
myooks[1j = new ooks{}; uctuuIIy muke the ooks
myooks[Zj = new ooks{}; objects |
myBooks0.title = "The Grapes of Java",
myBooksl.title = "The Java Gatsby",
myBooks2.title = "The Java Cookbook",
myBooks0.author = "bob",
myBooksl.author = "sue",
myBooks2.author = "ian",
while {x < 3| {
System.out.print{myBooksx.title|,
System.out.print{" by "|,
System.out.println{myBooksx.author|,
x = x + l,
}
}
}
class Hobbits {
String name,
public static void main{String args| {
Hobbits h = new Hobbits3,
int z = -1; Pemember: urruys sturt with
whiIe {z - Z} { eIement 0 |
z = z + l,
hz = new Hobbits{|,
hz.name = "bilbo",
if {z == l| {
hz.name = "frodo",
}
if {z == 2| {
hz.name = "sam",
}
System.out.print{hz.name + " is a "|,
System.out.println{"good Hobbit name"|,
}
}
}
class TestArrays {
public static void main{String args| {
int index = new int4,
index0 = l,
indexl = 3,
index2 = 0,
index3 = 2,
String islands = new String4,
islands0 = "Bermuda",
islandsl = "Fii",
islands2 = "Azores",
islands3 = "Cozumel",
int y = 0,
int ref,
while {y < 4| {
ref = indexy,
System.out.print{"island = "|,
System.out.println{islandsref|,
y = y + l,
}
}
}
File Edit Window Help Bikini
% java TestArrays
island = Fiji
island = Cozumel
island = Bermuda
island = Azores
exercise soIutions
[yej, ]a(jn,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
69
class Triangle {
double area,
int height,
int length,
public static void main{String args| {
int = 0;
TriungIe [ j tu = new TriungIe[4j;
while { - 4 | {
tu[j = new TriungIe{};
tu[j.height = {x + l| * 2,
tu[j.length = x + 4,
tu[j,setAreu{};
System.out.print{"triangle "+x+", area"|,
System.out.println{" = " + tu[j.area|,
= + 1;
}
int y = ;
x = 27,
Triangle t5 = ta2,
ta2.area = 343,
System.out.print{"y = " + y|,
System.out.println{", t5 area = "+ t5.area|,
}
void setArea{| {
ureu = {height * length| / 2,
}
}
class Triangle {
double area,
int height,
int length,
public static void main{String args| {
int = 0;
TriungIe [ j tu = new TriungIe[4j;
while { - 4 | { 4
tu[j = new TriungIe{};
tu[j.height = {x + l| * 2,
tu[j.length = x + 4,
tu[j,setAreu{};
System.out.print{"triangle "+x+", area"|,
System.out.println{" = " + tu[j.area|,
= + 1;
}
int y = ;
x = 27,
Triangle t5 = ta2,
ta2.area = 343,
System.out.print{"y = " + y|,
System.out.println{", t5 area = "+ t5.area|,
}
void setArea{| {
ureu = {height * length| / 2,
}
} File Edit Window Help Bermuda
%java Triangle
triangle 0, area = 4.0
triangle 1, area = 10.0
triangle 2, area = 18.0
triangle 3, area = Z,0
y = 4 t ureu = 343
Reference VariabIes: Heapuiz Dbjects:



Thc casc of thc piIfcrcd rcfcrcnccs
Tawny coulu scc ihai Kcni`s mcihou hau a sciious
uaw. Ii`s iiuc ihai hc uiun`i usc as many iclcicncc
vaiiallcs as Bol, lui ihcic was no way io acccss any
lui ihc lasi ol ihc Coniaci ol|ccis ihai his mcihou cic-
aicu. Wiih cach iii ihiough ihc loo, hc was assign-
ing a ncw ol|cci io ihc onc iclcicncc vaiiallc, so ihc
icviously iclcicnccu ol|cci was alanuoncu on ihc
hca - ur.enLnbIe. Wiihoui acccss io ninc ol ihc icn
ol|ccis cicaicu, Kcni`s mcihou was usclcss.
(T|e sollWare Was a |ue success ard l|e c||erl ave TaWry ard 8oo ar exlra Wee|
|r laWa||. we'd |||e lo le|| you l|al oy l|r|s||r l||s ooo| you loo W||| el slull |||e l|al.)
hq[0]
hq[I]
hq[Z]
hq[3]
hq[4]
]azz] ]a(jn,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
4 methods use instance variabIes
this is a new chapter 71
State affects behavior, behavior affects state. we know that ob|ects
have state and behavior, represented by instance variabIes and methods. 8ut until now, we
haven't looked at how state and behavior are teloteJ. we already know that each instance of a
class (each ob|ect of a particular type) can have its own unique values for its instance variables.
Dog A can have a nome "Pido and a we|ht of 70 pounds. Dog 8 is "Killer and weighs 9 pounds.
And if the Dog class has a method makeNoise(), well, don't you think a 70-pound dog barks a
bit deeper than the little 9-pounderI (Assuming that annoying yippy sound can be considered
a ootl.) Portunately, that's the whole point of an ob|ectit has oehov|ot that acts on its stote. |n
other words, merheJs use insrnnce vnrinble vnlues. Like, "if dog is less than l4 pounds, make
yippy sound, else... or "increase weight by 5. Lers ge chnnge seme srnre.
How Ob]ects Behave
This oughfo
chonge her sfofel
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
72 chapter 4
objects have state and behavior
A class is thc blucprint Ior an objcct. Whcn you
wiiic a class, you`ic ucsciiling how ihc ]VM
shoulu maIc an ol|cci ol ihai iyc. You alicauy
Inow ihai cvciy ol|cci ol ihai iyc can havc
uillcicni .rnre .n..nbIe valucs. Bui whai aloui
ihc mcihous.
0zn cvcry e|jcr! ef !hz! !ypc hzvc 4|ffcrcn!
mc!he4 |chzv|er!
Wcll... *
Evciy insiancc ol a aiiiculai class has ihc samc
mcihous, lui ihc mcihous can beLn.e uillcicnily
lascu on ihc valuc ol ihc insiancc vaiiallcs.
Thc Song class has iwo insiancc vaiiallcs, .Ie
anu n... Thc lay) mcihou lays a song, lui
ihc insiancc you call lay) on will lay ihc song
icicscnicu ly ihc valuc ol ihc .Ie insiancc
vaiiallc loi ihai insiancc. So, il you call ihc lay)
mcihou on onc insiancc you`ll hcai ihc song
PoliiiI", whilc anoihci insiancc lays DaiIsiai".
Thc mcihou couc, howcvci, is ihc samc.
void play() {
soundPlayer.playSound(title);
}

t|t|e
art|st
setT|t|e(}
setArt|st(}
p|ay(}
| ns!znrc
vzr| z||cs
(state}
mc!he4s
(behav|or}
knews
4ecs
*Yes, another stunningly clear answer!
Kcmcm|cr: z r|zss 4csrr||cs whz! zn
e|jcr! knews zn4 whz! zn e|jcr! 4ecs
PoIitik
CoIdpIoy
Sing
Trovis
Durkstur
0rofefuI
Deod
My Wuy
Sinofro
My Wuy
Sex PisfoIs
Song

t2.play();
Song

s3.play();
c
.
||-
|.
]
|` -
- l

: -:l
.
-:-
-
|| :.
-:-
-' l
-

|.
]

c.||- |.]|` -- l: -:l.-:-
-|| :.-:- M] w.]' l- |.]
|-l --l l- -.l-. ---`
Song t2 = new Song();
t2.setArtist(Travis);
t2.setTitle(Sing);
Song s3 = new Song();
s3.setArtist(Sex Pistols);
s3.setTitle(My Way);

-

-
:
l
.
-
:
-
:

-


:
|.
:
:

-
-

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
methods use instance variabIes
73
Ihc s|zc zffcr!s !hc |zrk
A small Dog`s laiI is uillcicni liom a lig Dog`s laiI.
Thc Dog class has an insiancc vaiiallc ..e, ihai ihc
bn.I() mcihou uscs io ucciuc whai Iinu ol laiI sounu
io maIc.

s|ze
rare
oar|()
class Dog {
int size;
String name;
void bark() {
if (size > 60) {
System.out.println(Wooof! Wooof!);
} else if (size > 14) {
System.out.println(Ruff! Ruff!);
} else {
System.out.println(Yip! Yip!);
}
}
}
class DogTestDrive {
public static void main (String[] args) {
Dog one = new Dog();
one.size = 70;
Dog two = new Dog();
two.size = 8;
Dog three = new Dog();
three.size = 35;
one.bark();
two.bark();
three.bark();
}
}
File Edit Window Help Playdead
%java DogTestDrive
Wooof! Wooof!
Yip! Yip!
Ruff! Ruff!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
74 chapter 4
0
0
0
0
0
0
I
I
inf
method parameters
Yee rzn scn4 !h|n]s !e z mc!he4
]usi as you cxcci liom any iogiamming languagc, you can ass valucs inio
youi mcihous. You mighi, loi cxamlc, wani io icll a Dog ol|cci how many
iimcs io laiI ly calling:
d.bark(3);
Dccnuing on youi iogiamming lacIgiounu anu cisonal iclcicnccs,
,ou mighi usc ihc icim n.uer oi cihas n.nee. loi ihc valucs asscu
inio a mcihou. Alihough ihcic n.e loimal comuici scicncc uisiinciions ihai
colc who wcai lal coais anu who will almosi cciiainly noi icau ihis looI,
maIc, wc havc liggci hsh io liy in ihis looI. So ,ou can call ihcm whaicvci
you liIc aigumcnis, uonuis, haiilalls, cic.) lui wc`ic uoing ii liIc ihis:
A method uses parameters. A caIIer passes arguments.
Aigumcnis aic ihc ihings you ass inio ihc mcihous. An orgument a valuc
liIc 2, Ioo", oi a iclcicncc io a Dog) lanus lacc-uown inio a... waii loi ii...
porometer. Anu a aiamcici is noihing moic ihan a local vaiiallc. A vaiiallc
wiih a iyc anu a namc, ihai can lc uscu insiuc ihc louy ol ihc mcihou.
Bui hcic`s ihc imoiiani aii: II a mcthod takcs a paramctcr, you must pass
it somcthing. Anu ihai somcihing musi lc a valuc ol ihc aioiiaic iyc.
void bark(int numOfBarks) {
while (numOfBarks > 0) {
System.out.println(ruff);
numOfBarks = numOfBarks - 1;
}
}
Dog d = new Dog();
d.bark(3);

CoII fhe bork mefhod on fhe Dog refer-


ence, ond poss in fhe voIue 3 (os fhe
orgumenf fo fhe mefhod).

The bifs represenfing fhe inf


voIue 3 ore deIivered info fhe
bork mefhod.

The bifs Iond in fhe numOf8orks


poromefer (on inf-si;ed voriobIe).

Use fhe numOf8orks


poromefer os o voriobIe in
fhe mefhod code.
.-----l
.-.-
-l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
methods use instance variabIes
75
0
0
I
0
I
0
I
0
inf
int theSecret = life.giveSecret();
int giveSecret() {
return 42;
}
Yee rzn ]c! !h|n]s |zrk frem z mc!he4.
Mcihous can iciuin valucs. Evciy mcihou is ucclaicu wiih a iciuin
iyc, lui uniil now wc`vc mauc all ol oui mcihous wiih a void
iciuin iyc, which mcans ihcy uon`i givc anyihing lacI.
void go() {
}
Bui wc can ucclaic a mcihou io givc a sccihc iyc ol valuc
lacI io ihc callci, such as:
int giveSecret() {
return 42;
}
Il you ucclaic a mcihou io iciuin a valuc, you u
iciuin a valuc ol ihc ucclaicu iyc! Oi a valuc
ihai is on.bIe wiih ihc ucclaicu iyc. Wc`ll gci
inio ihai moic whcn wc ialI aloui olymoihism
in chaici 7 anu chaici S.)
Whatever you say
you'll give back, you
better give backl
1- :--|-- ---'l |-l ]-- --l--- l- ---- l]- - l-
Cufe...
buf nof exocfIy whof I
wos expecfing.
1
- l: ----:--l- +
i .-- --l---- ---
l- --:--l|` --l-, .- |.- - l-
.-.|- -.-- l--:--l
l: --:l l
- .- -l'
1

-
:-

l
]

-
:
-
-
:l

-
.
l
:

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
76 chapter 4
muItipIe arguments
1- .-----l: ]-- .:: |.- - l- :.--
---- ]-- .::- l-- |-:l .-----l |.-:
- l- -:l .-.--l--, :-:-- .-----l -
l- :-:-- .-.--l--, .- :- --
Yee rzn scn4 merc !hzn enc !h|n]
!e z mc!he4
Mcihous can havc muliilc aiamcicis. Scaiaic ihcm
wiih commas whcn you ucclaic ihcm, anu scaiaic ihc
aigumcnis wiih commas whcn you ass ihcm. Mosi
imoiianily, il a mcihou has aiamcicis, you ass
aigumcnis ol ihc iighi iyc anu oiuci.
void takeTwo(int x, int y) {
int z = x + y;
System.out.println(Total is + z);
}
void go() {
TestStuff t = new TestStuff();
t.takeTwo(12, 34);
}
0z| || n] z ! we-pzrzmc!cr mc!he4, zn4 scn4| n]
| ! ! we zr]emcn!s.
void takeTwo(int x, int y) {
int z = x + y;
System.out.println(Total is + z);
}
void go() {
int foo = 7;
int bar = 3;
t.takeTwo(foo, bar);
}
Yee rzn pzss vzr| z||cs | n!e z mc!he4, zs |en] zs
!hc vzr| z||c ! ypc mz!rhcs !hc pzrzmc!cr ! ypc.
1

- .
|--: -


-
-
.
-


.
- |.
-

-
l

.
-

]

.
-.
-
-l
--:
-
-
-
-
l

-
l
: -

.
--
--
l
:.
| l
-
l

-
l
: -

-
-
|l

l

.
l
l
---

-
- l

- -
l
--- '7
'` .
-

l
: -
]
.
--
--
l
:.
| l
-
l

-
l
: -

.
-
w.l': l- .|-- - - |l': l- :.--
--:-|l ]--' -l ]-- .- -- +
.- .l l- l-- ]-- .::- l-- -l-
l- l.-1-- --l-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
methods use instance variabIes
77
1zvz |s pzss-|y-vz|ec.
Ihz! mczns pzss-|y-repy.
int x = 7;
0
0
0
0
0
I
I
I
inf
X

DecIore on inf voriobIe ond ossign if
fhe voIue '7'. The bif poffern for 7
goes info fhe voriobIe nomed x.
void go(int z){ }

DecIore o mefhod wifh on inf
poromefer nomed ;.
inf
Z
0
0
0
0
0
I
I
I
inf
X

CoII fhe go() mefhod, possing


fhe voriobIe x os fhe orgumenf.
The bifs in x ore copied, ond
fhe copy Ionds in ;.
0
0
0
0
0
I
I
I
inf
Z
:-] -

foo.go(x);
void go(int z){ }
0
0
0
0
0
I
I
I
inf
X

Chonge fhe voIue of ; inside


fhe mefhod. The voIue of x
doesn'f chongel The orgumenf
possed fo fhe ; poromefer wos
onIy o copy of x.
The mefhod con'f chonge fhe
bifs fhof were in fhe coIIing
voriobIe x.
inf
Z
void go(int z){
z = 0;
}
--:-'l :.--, --- - --:
0
0
0
0
0
0
0
0
.- - .---'l
:----:l-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
78 chapter 4
(-,- a,- |
oa|| qa--(:|-

What happens if the argument you want to


pass is an object instead of a primitive!

ou'll learn more about this in later chapters,


but you already lnow the answer. 1ava passes
evetyth|n by value. veryrhing. 8ut... volue means
o|ts |ns|Je the vot|oole. And remember, you don't
stuff ob|ects into variables, the variable is a remote
controlo teletence to on ooject. So if you pass a
reference to an ob|ect into a method, you're passing
a coy ol the temote conttol. Stay tuned, though, we'll
have lots more to say about this.

Can a method decIare muItipIe return vaIues!


Dr is there some way to return more than one
vaIue!

Sort of. A method can declare only one return


value. 8UT... if you want to return, say, three int values,
then the declared return type can be an int ottoy.
Stuff those ints into the array, and pass it on back. |t's
a little more involved to return multiple values with
different types, we'll be talking about that in a later
chapter when we talk about ArrayList.

Do I have to return the exact type I decIared!

ou can return anything that can be |ml|c|tly


promoted to that type. So, you can pass a byte where
an int is expected. The caller won't care, because the
byte fits |ust fine into the int the caller will use for
assigning the result. ou must use an exl|c|t cast
when the declared type is smollet than what you're
trying to return.

Do I have to do something with the return


vaIue of a method! Can I just ignore it!
1ava doesn't require you to acknowledge a
return value. ou might want to call a method with
a non-void return type, even though you don't care
about the return value. |n this case, you're calling
the method for the work it does |ns|Je the method,
rather than for what the method gives tetutns. |n
1ava, you don't have to assign or use the return value.
arguments and return vaIues
8ll P0lk5
C|asses del|re W|al ar oojecl |roWs ard W|al ar
oojecl does.
T||rs ar oojecl |roWs are |ls |nstance var|ab|es
(slale).
T||rs ar oojecl does are |ls methods (oe|av|or).
Vel|ods car use |rslarce var|ao|es so l|al oojecls
ol l|e sare lype car oe|ave d|llererl|y.
A rel|od car |ave pararelers, W||c| rears you
car pass ore or rore va|ues |r lo l|e rel|od.
T|e ruroer ard lype ol va|ues you pass |r rusl
ralc| l|e order ard lype ol l|e pararelers
dec|ared oy l|e rel|od.
va|ues passed |r ard oul ol rel|ods car oe
|rp||c|l|y proroled lo a |arer lype or exp||c|l|y casl
lo a sra||er lype.
T|e va|ue you pass as ar arurerl lo a rel|od
car oe a ||lera| va|ue (2, 'c', elc.) or a var|ao|e ol
l|e dec|ared parareler lype (lor exarp|e, W|ere
|s ar |rl var|ao|e). (T|ere are ol|er l||rs you
car pass as arurerls, oul We're rol l|ere yel.)
A rel|od dec|are a relurr lype. A vo|d relurr
lype rears l|e rel|od doesr'l relurr aryl||r.
ll a rel|od dec|ares a ror-vo|d relurr lype, |l
relurr a va|ue corpal|o|e W|l| l|e dec|ared relurr
lype.
Reminder: Java
cares about type!
You can't return a Giraffe when
the return type is decIared
as a Rabbit. Same thing with
parameters. You can't pass a
Giraffe into a method that
takes a Rabbit.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
methods use instance variabIes
79
0ee| !h|n]s yee rzn 4e w|!h pzrzmc!crs
zn4 rc!ern !ypcs
Now ihai wc`vc sccn how aiamcicis anu iciuin iycs woiI, ii`s
iimc io ui ihcm io goou usc: anu . Il you`ic inio
lcing all loimal aloui ii, you mighi iclci io call ihcm Aeo.
anu Auno.. Bui ihai`s a wasic ol cilccily goou syllallcs.
Bcsiucs, Gciicis anu Sciicis his ihc ]ava naming convcniion, so
ihai`s whai wc`ll call ihcm.
Gciicis anu Sciicis lci you, wcll, e nrJ e L.r. Insiancc vaii-
allc valucs, usually. A Gciici`s solc uiosc in lilc is io scnu lacI,
as a iciuin valuc, ihc valuc ol whaicvci ii is ihai aiiiculai Gciici
is suoscu io lc Gciiing. Anu ly now, ii`s iolally no suiiisc
ihai a Sciici livcs anu licaihcs loi ihc chancc io iaIc an aigu-
mcni valuc anu usc ii io e ihc valuc ol an insiancc vaiiallc.
E|ectr|cCu|tar
orard
rur0lP|c|ups
roc|3larusesll
el8rard()
sel8rard()
elNur0lP|c|ups()
selNur0lP|c|ups()
elRoc|3larusesll()
selRoc|3larusesll()
class ElectricGuitar {
String brand;
int numOfPickups;
boolean rockStarUsesIt;
String getBrand() {
return brand;
}
void setBrand(String aBrand) {
brand = aBrand;
}
int getNumOfPickups() {
return numOfPickups;
}
void setNumOfPickups(int num) {
numOfPickups = num;
}
boolean getRockStarUsesIt() {
return rockStarUsesIt;
}
void setRockStarUsesIt(boolean yesOrNo) {
rockStarUsesIt = yesOrNo;
}
}
N-l- c:- l-:-
-.-- :----l--:
--.-: ]--'|| -
-||--- .-
---l.-l )..
:l.-.-'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
80 chapter 4
Jen soys you're
weII-encopsuIofed...
Inrzpse|z!|en
Pe | ! er r|sk hem|||z!|en zn4
r|4|re|c.
Uniil ihis mosi imoiiani momcni, wc`vc
lccn commiiiing onc ol ihc woisi OO
laux as anu wc`ic noi ialIing minoi
violaiion liIc showing u wiihoui ihc B`
in BYOB). No, wc`ic ialIing Iaux Pas wiih
a caiial I`. Anu P`.
Oui shamclul iiansgicssion.
Exosing oui uaia!
Hcic wc aic, |usi humming along wiihoui
a caic in ihc woilu lcaving oui uaia oui
ihcic loi io scc anu cvcn iouch.
You may havc alicauy cxciicnccu ihai
vagucly unsciiling lccling ihai comcs wiih
lcaving youi insiancc vaiiallcs cxoscu.
Exoscu mcans icachallc wiih ihc uoi
ociaioi, as in:
theCat.height = 27;
ThinI aloui ihis iuca ol using oui icmoic
coniiol io maIc a uiicci changc io ihc Cai
ol|cci`s sizc insiancc vaiiallc. In ihc hanus
ol ihc wiong cison, a iclcicncc vaiiallc
icmoic coniiol) is quiic a uangcious
wcaon. Bccausc whai`s io icvcni:
theCat.height = 0;
This woulu lc a Bau Thing. Wc nccu io
luilu sciici mcihous loi all ihc insiancc
vaiiallcs, anu hnu a way io loicc oihci
couc io call ihc sciicis iaihci ihan acccss
ihc uaia uiiccily.
]-:' w
- :.-'l
|-l l: .--'
reaI deveIopers encapsuIate
public void setHeight(int ht) {
if (ht > 9) {
height = ht;
}
}
B] --:- ---]-] l- :.|| . :-ll--
--l-, -- :.- --l-:l l- :.l ---
--.::-l.|- :-- :.--:
w
- -l - :-::
l- -.-.-l-- .
----- :.l -l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
methods use instance variabIes
81
"SudIy iII forgot to
encupsuIute his Cut cIuss und
ended up with u fIut cut,"
(overheard at the water cooler).

Ycs ii . ihai simlc io go liom
an imlcmcniaiion ihai`s |usi
lcgging loi lau uaia io onc
ihai ioiccis youi uaia nrJ
ioiccis youi iighi io mouily
youi imlcmcniaiion laici.
OK, so how cxacily uo you
L.Je ihc uaia. Wiih ihc
public anu private
acccss mouihcis. You`ic
lamiliai wiih public-wc usc
ii wiih cvciy main mcihou.
Hcic`s an cncasulaiion
n.e. iulc ol ihuml all sian-
uaiu uisclaimcis aloui iulcs
ol ihuml aic in cllcci): maiI
youi insiancc vaiiallcs privote
anu ioviuc pubIic gciicis
anu sciicis loi acccss coniiol.
Whcn you havc moic ucsign
anu couing savvy in ]ava, you
will iolally uo ihings a liiilc
uillcicnily, lui loi now, ihis
aioach will Icc you salc.
Mark instance
variabIes private.
Mark getters and
setters public.
HeadFirst: What`s the big oeal about encapsulation?
Object: OK, you know that oream where you`re giving a talk to 500 people when you
suooenly realize you`re oo/.o?
HeadFirst: Yeah, we`ve hao that one. It`s right up there with the one about the Filates
machine ano... no, we won`t go there. OK, so you leel nakeo. But other than being a little
exposeo, is there any oanger?
Object: Is there any oanger? Is there any ooo.r? |starts laughing| Hey, oio all you other
instances hear that, I t/.r. oo, ooo.r.` he asks? |lalls on the noor laughing|
HeadFirst: What`s lunny about that? Seems like a reasonable question.
Object: OK, I`ll explain it. It`s |bursts out laughing again, uncontrollably|
HeadFirst: Can I get you anything? Water?
Object: Whew Oh boy. No I`m nne, really. I`ll be serious. Deep breath. OK, go on.
HeadFirst: So what ooes encapsulation protect you lrom?
Object: Encapsulation puts a lorce-nelo arouno my instance variables, so nobooy can set
them to, let`s say, something ioorriot..
HeadFirst: Can you give me an example?
Object: Doesn`t take a FhD here. Most instance variable values are cooeo with certain
assumptions about the bounoaries ol the values. Like, think ol all the things that woulo
break il negative numbers were alloweo. Number ol bathrooms in an olnce. Velocity ol
an airplane. Birthoays. Barbell weight. Cell phone numbers. Microwave oven power.
HeadFirst: I see what you mean. So how ooes encapsulation let you set bounoaries?
Object: By lorcing other cooe to go through setter methoos. That way, the setter methoo
can valioate the parameter ano oecioe il it`s oo-able. Maybe the methoo will reject it ano
oo nothing, or maybe it`ll throw an Exception ,like il it`s a null social security number
lor a creoit caro application,, or maybe the methoo will rouno the parameter sent in to
the nearest acceptable value. The point is, you can oo whatever you want in the setter
methoo, whereas you can`t oo oo,t/io il your instance variables are public.
HeadFirst: But sometimes I see setter methoos that simply set the value without check-
ing anything. Il you have an instance variable that ooesn`t have a bounoary, ooesn`t that
setter methoo create unnecessary overheao? A perlormance hit?
Object: The point to setters ,ano getters, too, is that you can change your nInd later,
uIthout breakIng anybody else`s code! Imagine il hall the people in your com-
pany useo your class with public instance variables, ano one oay you suooenly realizeo,
Oops there`s something I oion`t plan lor with that value, I`m going to have to switch to a
setter methoo. You break everyone`s cooe. The cool thing about encapsulation is that ,o
.t t c/oo. ,or oioo. Ano nobooy gets hurt. The perlormance gain lrom using variables
oirectly is so miniscule ano woulo rarelyif ...r be worth it.
This week's interview:
An Object gets candid about encapsuIation.
1a-a spese3
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
how objects behave
82 chapter 4
class GoodDog {

private int size;
public int getSize() {
return size;
}

public void setSize(int s) {
size = s;
}
void bark() {
if (size > 60) {
System.out.println(Wooof! Wooof!);
} else if (size > 14) {
System.out.println(Ruff! Ruff!);
} else {
System.out.println(Yip! Yip!);
}
}
}
class GoodDogTestDrive {
public static void main (String[] args) {
GoodDog one = new GoodDog();
one.setSize(70);
GoodDog two = new GoodDog();
two.setSize(8);
System.out.println(Dog one: + one.getSize());
System.out.println(Dog two: + two.getSize());
one.bark();
two.bark();
}
}
Inrzpse|z!|n] !hc
0ee4Pe] r|zss
M
.

-
l

-
-
:l
.
-
:
-

.
-
.

|-

-
.
l
-

M
.- l- -ll-- .-
:-ll-- -
-l-: -|:
!-- l-- l- --l-: --'l --.||]
. --- --:l--.|l], l- :--| l-
: l.l ]-- :.- :.-- ]--- --
|.l-- ]-- :.- :--- .: .- -.- .
--l- :.--, .:l--, -ll--

s|ze
el3|ze( )
sel3|ze( )
oar|( )
Any place where a
particular value can
be used, a method
call that returns that
type can be used.
insteud of:
inf x ~ 3 + Z4,
you cun suy:
inf x ~ 3 + one.gefSi;e(),
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
methods use instance variabIes
83
Hew 4e e|jcr!s |n zn zrrzy
|chzvc!
Dog orroy objecf (Dog[])
Dog[]

pets[0] = new Dog();


pets[1] = new Dog();
Dog[] pets;
pets = new Dog[7];
Creofe fwo new Dog objecfs,
ond ossign fhem fo fhe frsf
fwo orroy eIemenfs.
Dog Dog Dog Dog Dog Dog Dog
Dog orroy objecf (Dog[])
Dog[]

Dog Dog Dog Dog Dog Dog Dog


D
o
g
O
bj
e
c
f
D
o
g
O
bj
e
c
f
DecIore ond creofe o Dog orroy,
fo hoId 7 Dog references.

]usi liIc any oihci ol|cci. Thc only uillcicncc is


how you io ihcm. In oihci woius, how you gci
ihc icmoic coniiol. Ici`s iiy calling mcihous on
Dog ol|ccis in an aiiay.

pets[0].setSize(30);
int x = pets[0].getSize();
pets[1].setSize(8);
CoII mefhods on fhe fwo Dog
objecfs.

30
si;e
8
si;e
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
84 chapter 4
You alicauy Inow ihai a vaiiallc ucclaiaiion nccus ai lcasi a namc
anu a iyc:
int size;
String name;
Anu you Inow ihai you can iniiializc assign a valuc) io ihc
vaiiallc ai ihc samc iimc:
int size = 420;
String name = Donny;
Bui whcn you uon`i iniiializc an insiancc vaiiallc, whai hacns
whcn you call a gciici mcihou. In oihci woius, whai is ihc .nIue ol
an insiancc vaiiallc beo.e you iniiializc ii.
Pcr|zr|n] zn4 |n| !|z||z|n]
|ns!znrc vzr|z||cs
class PoorDog {
private int size;
private String name;

public int getSize() {
return size;
}
public String getName() {
return name;
}
}
public class PoorDogTestDrive {
public static void main (String[] args) {
PoorDog one = new PoorDog();
System.out.println(Dog size is + one.getSize());
System.out.println(Dog name is + one.getName());
}
}
nstance variables
always get a
default value. f
you don't explicitly
assign a value
to an instance
variable, or you
don't call a setter
method, the
instance variable
still has a valuel
|ntegers 0
f|oat|ng po|nts 0.0
boo|eans fa|se
references nu||
-:|.-- l-- -:l.-:- .-.|-:,
-l --'l .::- . .|--
w.l -|| l-:- --l---
w
.l

- ]-- l
- w
||
l
: --- :--
|-
File Edit Window Help CallVet
% java PoorDogTestDrive
Dog size is 0
Dog name is null
/-- --'l .- l- -l.|-- -:l.-:- .-.|-:,
-:.-:- l-] .|-.]: .- . -.-|l .|-- N----
--l-: |-:|-- :.-` -l o, --|-.-: -l .|:-,
.- --:l ------:- .-.|-: -l --||
|------, --|| -:l --.-: . ----l- :--l--| l.l
:-'l :--l--||- / ---.--- l- .-]l- A
------:-, -l -- .:l-.| --:l
initiaIizing instance variabIes
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
methods use instance variabIes
85
Ihc 4|ffcrcnrc |c! wccn |ns!znrc
zn4 |erz| vzr|z||cs
Instunce voriobIes ore decIored
inside o cIoss buf nof wifhin o mefhod.

class Horse {
private double height = 15.2;
private String breed;
// more code...
}
LocuI voriobIes ore decIored wifhin o mefhod.

class AddThing {
int a;
int b = 12;
public int add() {
int total = a + b;
return total;
}
}

Local variables do
NOT get a default
valuel The compiler
complains if you
try to use a local
variable before
the variable is
initialized.
LocuI voriobIes MUST be inifioIi;ed before usel

class Foo {
public void go() {
int x;
int z = x + 3;
}
}

w--'l :--|-'' /-- :.-
-:|.-- -l--l . .|--,
-l .: :--- .: ]-- l-]
l- c! l, l- :--|--
--.: --l
File Edit Window Help Yikes
% javac Foo.java
Foo.java:4: variable x might
not have been initialized
int z = x + 3;
1 error ^
(-,- a,- |
oa|| qa--(:|-

What about method parameters!


How do the ruIes about IocaI variabIes
appIy to them!

Method parameters are virtually the
same as local variablesthey're declared
|ns|Je the method (well, technically they're
declared in the otument l|st of the method
rather than within the ooJy of the method,
but they're still local variables as opposed to
instance variables). 8ut method parameters
will never be uninitialized, so you'll never get
a compiler error telling you that a parameter
variable might not have been initialized.
8ut that's because the compiler will give
you an error if you try to invoke a method
without sending arguments that the method
needs. So parameters are ALwAS initialized,
because the compiler guarantees that
methods are always called with arguments
that match the parameters declared for the
method, and the arguments are assigned
(automatically) to the parameters.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
86 chapter 4
object equaIity
Somciimcs you wani io Inow il iwo .....e aic ihc samc. Thai`s casy
cnough, |usi usc ihc ociaioi. Somciimcs you wani io Inow il iwo
iclcicncc vaiiallcs iclci io a singlc ol|cci on ihc hca. Easy as wcll, |usi usc
ihc ociaioi. Bui somciimcs you wani io Inow il iwo obe aic cqual.
Anu loi ihai, you nccu ihc .cquals) mcihou. Thc iuca ol cqualiiy loi
ol|ccis uccnus on ihc iyc ol ol|cci. Ioi cxamlc, il iwo uillcicni Siiing
ol|ccis havc ihc samc chaiacicis say, cxcuiiious"), ihcy aic mcaninglully
cquivalcni, icgaiulcss ol whcihci ihcy aic iwo uisiinci ol|ccis on ihc hca.
Bui whai aloui a Dog. Do you wani io iicai iwo Dogs as lcing cqual il ihcy
hacn io havc ihc samc sizc anu wcighi. Piolally noi. So whcihci iwo
uillcicni ol|ccis shoulu lc iicaicu as cqual uccnus on whai maIcs scnsc loi
ihai aiiiculai ol|cci iyc. Wc`ll cxloic ihc noiion ol ol|cci cqualiiy again
in laici chaicis anu acnuix B), lui loi now, wc nccu io unucisianu ihai
ihc ociaioi is uscu orI, io comaic ihc liis in iwo vaiiallcs. VLn ihosc
liis icicscni uocsn`i maiici. Thc liis aic ciihci ihc samc, oi ihcy`ic noi.
To compare two primitives, use the == operator
Thc ociaioi can lc uscu io comaic iwo vaiiallcs ol any Iinu, anu ii
simly comaics ihc liis.
il a l) [...} looIs ai ihc liis in a anu l anu iciuins iiuc il ihc lii aiicin
is ihc samc alihough ii uocsn`i caic aloui ihc sizc ol ihc vaiiallc, so all ihc
cxiia zciocs on ihc lcli cnu uon`i maiici).
int a = 3;
byte b = 3;
if (a == b) { // true }
To see if two references are the same {which means they
refer to the same ob]ect on the heap} use the == operator
Rcmcmlci, ihc ociaioi caics only aloui ihc aiicin ol liis in ihc
vaiiallc. Thc iulcs aic ihc samc whcihci ihc vaiiallc is a iclcicncc oi
iimiiivc. So ihc ociaioi iciuins iiuc il iwo iclcicncc vaiiallcs iclci io
ihc samc ol|cci! In ihai casc, wc uon`i Inow whai ihc lii aiicin is lccausc
ii`s uccnucni on ihc ]VM, anu hiuucn liom us) lui wc Jo Inow ihai whaicvci
ii looIs liIc, . w.II be Le ne o. wo .ee.ere o n .rIe obe.
Foo a = new Foo();
Foo b = new Foo();
Foo c = a;
if (a == b) { // false }
if (a == c) { // true }
if (b == c) { // false }
0empzr|n] vzr|z||cs |pr|m| !| vcs er rcfcrcnrcsI
0
0
0
0
0
0
I
I
inf
a
0
0
0
0
0
0
I
I
byfe
b
==
|l--- .-- -
--- -----: --
l- |-l :- - l- -l,
-l -- --'l :.-- .--l
l.l ---`
l- l .ll---: .-- l-
:.-
-, :- l-:- l-- .--
--.| -:- =
=
Foo

Foo

Foo

. == : : l---
. == : .|:-
l- l .ll---: .-- l-
:.-
- -- . .- :, :- l-]
.-- --.| -:- =
=
Use == to compare
two primitives,
or to see if two
references refer to
the same ob]ect.
Use the equals{}
method to see
if two different
ob]ects are equal.
{8uch as two different
8tring ob]ects that both
represent the characters
in Fred}
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
methods use instance variabIes
87
+,-+ :+ ,-+:.|
What's IegaI?
0iven fhe mefhod beIow, which
of fhe mefhod coIIs Iisfed on fhe
righf ore IegoI7
Puf o checkmork nexf fo fhe
ones fhof ore IegoI. (Some
sfofemenfs ore fhere fo ossign
voIues used in fhe mefhod coIIs).
int calcArea(int height, int width) {
return height * width;
}
int a = calcArea(7, 12);
short c = 7;
calcArea(c,15);
int d = calcArea(57);
calcArea(2,3);
long t = 42;
int f = calcArea(t,17);
int g = calcArea();
calcArea();
byte h = calcArea(4,20);
int j = calcArea(2,3,5);

I oIwoys
keep my voriobIes
privofe. If you wonf fo
see fhem, you hove fo
foIk fo my mefhods.

koses ote teJ,


th|s oem
|s choy,
oss|n oy volue
|s oss|n oy coy.
Oh, like you can do betterI Try it. Peplace our
dumb second line with your own. 8etter yet,
replace the whole thing with your own words
and you'll nevet forget it.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
88 chapter 4

class XCopy {
public static void main{String args| {
int orig = 42,
XCopy x = new XCopy{|,
int y = x.go{orig|,
System.out.println{orig + " " + y|,
}
int go{int arg| {
arg = arg * 2,

return arg,
}
}

class Clock {
String time,
void setTime{String t| {
time = t,
}
void getTime{| {
return time,
}
}
class ClockTestDrive {
public static void main{String args| {
Clock c = new Clock{|,
c.setTime{"l245"|,
String tod = c.getTime{|,
System.out.println{"time: " + tod|,
}
}

[ze[ | ([ ]zvz |j], n ([j, zg


,n(, z e]( ,ae |j].
(a j j, ( ]zy ej] zn]
](jn w[([ ze[ | ([, |j],
wj]] ej]. ]| ([y wn'(
ej], [w wa]] ya
|jy ([, zn] j| ([y ]
ej], w[z( wa]]
([j a(a(/
] ge eomgj|e;
exercise: Be the CompiIer
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
methods use instance variabIes
89

A cIass can have any number of these.


A method can have onIy one of these.
This can be impIicitIy promoted.
I prefer my instance variabIes private.
It reaIIy means 'make a copy'.
OnIy setters shouId update these.
A method can have many of these.
I return something by definition.
I shouIdn't be used with instance variabIes.
I can have many arguments.
By definition, I take one argument.
These heIp create encapsuIation.
I aIways fIy soIo.
A bunch of 1ava components, in full costume, are playing a party
game, "who am |I They give you a clue, and you try to guess who
they are, based on what they say. Assume they always tell the truth
about themselves. |f they happen to say something that could be true
for more than one guy, then write down all for whom that sentence
applies. Pill in the blanks next to the sentence with the names of one
or more attendees.
7onight's attendees:
instance variabIe, argument, return, getter, setter,
encapsuIation, pubIic, private, pass by vaIue, method

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
90 chapter 4
A short 1ava program is listed to your right.
Two blocks of the program are missing.
our challenge is to match the candidate
bIocks of code (below), with the output
that you'd see if the blocks 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.

x < 9
index < 5
x < 20
index < 5
x < 7
index < 7
x < l9
index < l
l4 7
9 5
l9 l
l4 l
25 l
7 7
20 l
20 5
Candidates: PossibIe output:
public class Mix4 {
int counter = 0;
public static void main(String [] args) {
int count = 0;
Mix4 [] m4a =new Mix4[20];
int x = 0;
while ( ) {
m4a[x] = new Mix4();
m4a[x].counter = m4a[x].counter + 1;
count = count + 1;
count = count + m4a[x].maybeNew(x);
x = x + 1;
}
System.out.println(count +
+ m4a[1].counter);
}

public int maybeNew(int index) {
if ( ) {
Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
return 1;
}
return 0;
}
}
puzzIe: Mixed Messages
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
methods use instance variabIes
91
ivar
factor
public
private

our is to take code snippets from the
pool and place them into the blank lines
in the code. ou may not use the same
snippet more than once, and you won't
need to use all the snippets. our
is to make a class that will compile and
run and produce the output listed.
public class Puzzle4 {
public static void main{String args| {
___________________________________
int y = l,
int x = 0,
int result = 0,
while {x < 6| {
___________________________
___________________________
y = y * l0,
_________________
}
x = 6,
while {x > 0| {
_________________
result = result + ___________________
}
System.out.println{"result " + result|,
}
}
class ___________ {
int ivar,
________ ______ doStuff{int _________| {
if {ivar > l00| {
return _________________________
} else {
return _________________________
}
}
}
Note: ach snippet
from the pooI can be
used onIy oncel
File Edit Window Help BellyFlop
%java Puzzle4
result 543345
Dutput
Puzzle4 | | obs new Puzzle4|6|,
Puzzle4b | | obs new Puzzle4b|6|,
Puzzle4b | | obs new Puzzle4|6|,
obs |x| new Puzzle4b(x),
obs | | new Puzzle4b( ),
obs |x| new Puzzle4b( ),
obs new Puzzle4b( ),
doStuff(x),
obs.doStuff(x),
obs|x|.doStuff(factor),
obs|x|.doStuff(x),
ivar x,
obs.ivar x,
obs|x|.ivar x,
obs|x|.ivar y,
ivar + factor,
ivar ` (2 + factor),
ivar ` (5 - factor),
ivar ` factor,
x x + l,
x x - l,
Puzzle4
Puzzle4b
Puzzle4b( )
int
short
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
92 chapter 4
Fast Times in Stim-City
When Buchanan jammed his twitch-gun into Jai`s side, Jai Iroze. Jai knew that Buchanan
was as stupid as he was ugly and he didn`t want to spook the big guy. Buchanan ordered Jai
into his boss`s oIfce, but Jai`d done nothing wrong, (lately), so he fgured a little chat with
Buchanan`s boss Leveler couldn`t be too bad. He`d been moving lots oI neural-stimmers in
the west side lately and he fgured Leveler would be pleased. Black market stimmers weren`t
the best money pump around, but they were pretty harmless. Most oI the stim-junkies he`d
seen tapped out aIter a while and got back to liIe, maybe just a little less Iocused than beIore.
Leveler`s oIfce` was a skungy looking skimmer, but once Buchanan shoved him in, Jai
could see that it`d been modifed to provide all the extra speed and armor that a local boss like
Leveler could hope Ior. 'Jai my boy, hissed Leveler, 'pleasure to see you again. 'Likewise
I`m sure..., said Jai, sensing the malice behind Leveler`s greeting, 'We should be square
Leveler, have I missed something? 'Ha! You`re making it look pretty good Jai, your volume
is up, but I`ve been experiencing, shall we say, a little breach` lately... said Leveler.
Jai winced involuntarily, he`d been a top drawer jack-hacker in his day. Anytime someone
fgured out how to break a street-jack`s security, unwanted attention turned toward Jai. 'No
way it`s me man, said Jai, 'not worth the downside. I`m retired Irom hacking, I just move
my stuII and mind my own business. 'Yeah, yeah, laughed Leveler, 'I`m sure you`re
clean on this one, but I`ll be losing big margins until this new jack-hacker is shut
out! 'Well, best oI luck Leveler, maybe you could just drop me here and I`ll go
move a Iew more units` Ior you beIore I wrap up today, said Jai.
'I`m aIraid it`s not that easy Jai, Buchanan here tells me that word is you`re
current on J37NE, insinuated Leveler. 'Neural Edition? sure I play around a bit, so
what?, Jai responded Ieeling a little queasy. 'Neural edition`s how I let the stim-junkies
know where the next drop will be, explained Leveler. 'Trouble is, some stim-junkie`s stayed
straight long enough to fgure out how to hack into my WareHousing database. 'I need a
quick thinker like yourselI Jai, to take a look at my StimDrop J37NE class; methods, instance
variables, the whole enchilada, and fgure out how they`re getting in. It should.., 'HEY!,
exclaimed Buchanan, 'I don`t want no scum hacker like Jai nosin` around my code! 'Easy
big guy, Jai saw his chance, 'I`m sure you did a top rate job with your access modi.. 'Don`t
tell me - bit twiddler!, shouted Buchanan, 'I leIt all oI those junkie level methods public,
so they could access the drop site data, but I 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 oII at the corner
and take a cruise around the block, suggested Jai. Buchanan reached Ior his twitch-gun but
Leveler`s stunner was already on Buchanan`s 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 1ai suspect?
Will he get out of Leveler`s skimmer with all his bones intact?
]Jc_Jna[c
_s[ci
puzzIe: Five Minute Mystery
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
methods use instance variabIes
93
A class can have any number of these.
A method can have only one of these.
This can be implicitly promoted.
prefer my instance variables private.
t really means 'make a copy'.
Only setters should update these.
A method can have many of these.
return something by defnition.
shouldn't be used with instance variables
can have many arguments.
By defnition, take one argument.
These help create encapsulation.
always fy solo.
instunce vuriubIes getter settermethod
return
return urgument
encupsuIution
puss by vuIue
instunce vuriubIes
urgument
getter
pubIic
method
setter
getter setter pubIic privute
return
A Class 'XCopy' compiles and runs as it stands ! The
output is: '42 84'. Remember Java is pass by value, (which
means pass by copy), the variable 'orig' is not changed by the
go( ) method.

class Clock {
String time,
void setTime{String t| {
time = t,
}
String getTime{| {
return time,
}
}
class ClockTestDrive {
public static void main{String args| {
Clock c = new Clock{|,
c.setTime{"l245"|,
String tod = c.getTime{|,
System.out.println{"time: " + tod|,
}
} Mofe: '0effer' mefhods hove o refurn
fype by defnifion.
[yej, ]a(jn,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
94 chapter 4
public class Puzzle4 {
public static void main{String args| {
Pu;;Ie4b [ ] obs ~ new Pu;;Ie4b[o],
int y = l,
int x = 0,
int result = 0,
while {x < 6| {
obs[x] ~ new Pu;;Ie4b( ),
obs[x] . ivor ~ y,
y = y * l0,
x ~ x + I,
}
x = 6,
while {x > 0| {
x ~ x - I,
result = result + obs[x].doSfuff(x),
}
System.out.println{"result " + result|,
}
}
class Pu;;Ie4b {
int ivar,
pubIic inf doStuff{int focfor| {
if {ivar > l00| {
return ivor * focfor,
} else {
return ivor * (b - focfor),
}
}
}
File Edit Window Help BellyFlop
%java Puzzle4
result 543345
Dutput
x < 9
index < 5
x < 20
index < 5
x < 7
index < 7
x < l9
index < l
l4 7
9 5
l9 l
l4 l
25 l
7 7
20 l
20 5
Candidates: PossibIe output:
Answer to the 5-minute mystery...
Jai knew that Buchanan wasn`t the sharpest
pencil in the box. When Jai heard Buchanan
talk about his code, Buchanan never mentioned
his instance variables. Jai suspected that
while Buchanan did in Iact handle his methods
correctly, he Iailed to mark his instance variables
private. That slip up could have easily cost
Leveler thousands.
puzzIe answers
]azz] ]a(jn,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
5 writing a program
this is a new chapter 95
Let's put some muscIe in our methods. we dabbled with variables, played
with a few ob|ects, and wrote a little code. 8ut we were weak. we need more tools. Like
operators. we need more operators so we can do something a little more interesting than, say,
ootl. And Ioops. we need loops, but what's with the wimpy wh|le loopsI we need loops
if we're really serious. Might be useful to generate random numbers. And turn a String
into an int, yeah, that would be cool. 8etter learn that too. And why don't we learn it all by
ou|lJ|n something real, to see what it's like to write (and test) a program from scratch. Maybe
a game, like 8attleships. That's a heavy-lifting task, so it'll take two chapters to finish. we'll build
a simple version in this chapter, and then build a more powerful deluxe version in chapter 6.
Extra-8trength Methods
I con Iiff
heovy objecfs.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
96 chapter 5
Ic!s |e||4 z Bz!!|csh|p-s!y|c
]zmc: 8|nk z Pe! 0em
Ii`s you againsi ihc comuici, lui unliIc ihc ical
Baiilcshi gamc, in ihis onc you uon`i lacc any shis
ol youi own. Insicau, youi |ol is io sinI ihc comuici`s
shis in ihc lcwcsi numlci ol gucsscs.
Oh, anu wc aicn`i sinIing shis. Wc`ic Iilling Doi
Coms. Thus csiallishing lusincss iclcvancy so you can
cxcnsc ihc cosi ol ihis looI).
Goal: SinI all ol ihc comuici`s Doi Coms in ihc lcwcsi
numlci ol gucsscs. You`ic givcn a iaiing oi lcvcl, lascu
on how wcll you ciloim.
Sctup: Whcn ihc gamc iogiam is launchcu, ihc
comuici laccs ihicc Doi Coms on a virtual 7 x 7
grid. Whcn ihai`s comlcic, ihc gamc asIs loi youi hisi
gucss.
How you play: Wc havcn`i lcaincu io luilu a GUI yci, so
ihis vcision woiIs ai ihc commanu-linc. Thc comuici
will iomi you io cnici a gucss a ccll), ihai you`ll iyc
ai ihc commanu-linc as AS", C", cic.). In icsonsc
io youi gucss, you`ll scc a icsuli ai ihc commanu-
linc, ciihci Hii", Miss", oi You sunI Pcis.com" oi
whaicvci ihc lucIy Doi Com ol ihc uay is). Whcn
you`vc scni all ihicc Doi Coms io ihai lig 404 in ihc
sIy, ihc gamc cnus ly iiniing oui youi iaiing.
7 x 7 -
File Edit Window Help Sell
%java DotComBust
Enter a guess A3
miss
Enter a guess B2
miss
Enter a guess C4
miss
Enter a guess D2
hit
Enter a guess D3
hit
Enter a guess D4
Ouch! You sunk Pets.com : (
kill
Enter a guess B4
miss
Enter a guess G3
hit
Enter a guess G4
hit
Enter a guess G5
Ouch! You sunk AskMe.com : (
kill
Enter a guess A7
miss
Enter a guess B7
A

C
D

F
C
0 1 2 3 4 5 6
AskMe.com
Pets.com
C
o
2
.
c
o
m
:l.-l: .l ----, |- ).. .--.]:
pzr! ef z ]zmc |n!crzr!|en
You're going to build the
Sink a Dot Com game, with
a 7 x 7 grid and three
Dot Coms. Each Dot Com
takes up three cells.
-.: -
: . :-||'
buiIding a reaI game
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
97
I|rs!, z h|]h-|cvc| 4cs|]n
Wc Inow wc`ll nccu classcs anu mcihous, lui whai
shoulu ihcy lc. To answci ihai, wc nccu moic
inloimaiion aloui whai ihc gamc shoulu uo.
Iiisi, wc nccu io hguic oui ihc gcncial uow ol ihc
gamc. Hcic`s ihc lasic iuca:

User sforfs fhe gome


0ome creofes fhree Dof Coms

0ome pIoy begins


Pepeof fhe foIIowing unfiI fhere ore
no more Dof Coms:

0ome pIoces fhe fhree Dof


Coms onfo o virfuoI grid

Prompf user for o guess


("AZ", "C0", efc.)

Check fhe user guess ogoinsf


oII Dof Coms fo Iook for o hif,
miss, or kiII. Toke oppropri-
ofe ocfion: if o hif, deIefe ceII
(AZ, D4, efc.). If o kiII, deIefe
Dof Com.

0ome fnishes
0ive fhe user o rofing bosed on
fhe number of guesses.
Sforf
0ome sef-up
0ef user
guess
Check
guess
hif miss
remove Ioco-
fion ceII
kiII
remove
Dof Com
yes
no
sfiII some
Dof Coms
oIive7
dispIoy user
score/rofing
gome
over
Whoa. A real fow chart.
Now wc havc an iuca ol ihc Iinus ol ihings ihc
iogiam nccus io uo. Thc ncxi sic is hguiing
oui whai Iinu ol wc`ll nccu io uo ihc
woiI. Rcmcmlci, ihinI liIc Biau iaihci ihan
Iaiiy, locus hisi on ihc things in ihc iogiam
iaihci ihan ihc procedures.

A
:-:|- --.-:
:l.-l -- -:
A
--:l.-|- :
-:- l- ----:--l
.- .:l--
A .---
----:--l: .
-::-- --l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
98 chapter 5
8|mp|e0ot6omCame

vo|d ra|r
8|mp|e0ot6om
|rl [| |ocal|orCe||s
|rl rur0ll|ls
3lr|r c|ec|Yourse|l(3lr|r uess)
vo|d selLocal|orCe||s(|rl[| |oc)
remp|c!c ]zmc |n!crzr!|en
Ihc 8|mp|c Pe! 0em 0zmc
z ]cn!|cr |n!re4er!|en
Ii looIs liIc wc`ic gonna nccu ai lcasi iwo classcs, a
Gamc class anu a DoiCom class. Bui lcloic wc luilu
ihc lull moniy Sinh o Dot Com gamc, wc`ll siaii wiih
a siiicu-uown, simlih cu vcision, SimpIe Dot Com
Come. Wc`ll luilu ihc simlc vcision in L. chaici,
lollowcu ly ihc ucluxc vcision ihai wc luilu in ihc
re: chaici.
Evciyihing is simlci in ihis gamc. Insicau ol a 2-D
giiu, wc hiuc ihc Doi Com in |usi a singlc .ow. Anu
insicau ol L.ee Doi Coms, wc usc ore.
Thc goal is ihc samc, ihough, so ihc gamc siill nccus
io maIc a DoiCom insiancc, assign ii a locaiion
somcwhcic in ihc iow, gci usci inui, anu whcn all
ol ihc DoiCom`s cclls havc lccn hii, ihc gamc is ovci.
This simlih cu vcision ol ihc
gamc givcs us a lig hcau siaii
on luiluing ihc lull gamc.
Il wc can gci ihis small onc
woiIing, wc can scalc ii u io
ihc moic comlcx onc laici.
In ihis simlc vcision, ihc
gamc class has no insiancc
vaiiallcs, anu all ihc gamc
couc is in ihc main) mcihou.
In oihci woius, whcn ihc
iogiam is launchcu anu
main) lcgins io iun, ii will
maIc ihc onc anu only DoiCom
insiancc, icI a locaiion loi ii ihicc
consccuiivc cclls on ihc singlc viiiual
scvcn-ccll iow), asI ihc usci loi a gucss, chccI ihc
gucss, anu iccai uniil all ihicc cclls havc lccn hii.
Kcc in minu ihai ihc viiiual iow is... ...unI. In oihci
woius, ii uocsn`i cxisi anywhcic in ihc iogiam. As
long as loih ihc gamc anu ihc usci Inow ihai ihc
DoiCom is hiuucn in ihicc consccuiivc cclls oui ol a
ossillc scvcn siaiiing ai zcio), ihc iow iiscll uocsn`i
havc io lc icicscnicu in couc. You mighi lc icmicu
io luilu an aiiay ol scvcn inis anu ihcn assign ihc
DoiCom io ihicc ol ihc scvcn clcmcnis in ihc aiiay,
lui you uon`i nccu io. All wc nccu is an aiiay ihai
holus |usi ihc ihicc cclls ihc DoiCom occuics.

Sume sturts, ond creofes OME DofCom


ond gives if o Iocofion on fhree ceIIs in
fhe singIe row of seven ceIIs.
Insfeod of "AZ", "C4", ond so on, fhe
Iocofions ore jusf infegers (for exompIe:
I,Z,3 ore fhe ceII Iocofions in fhis
picfure:

Sume pIuy begins. Prompf user for


o guess, fhen check fo see if if hif
ony of fhe DofCom's fhree ceIIs.
If o hif, incremenf fhe numOfHifs
voriobIe.

Sume h nishes when oII fhree ceIIs hove


been hif (fhe numOfHifs voriobIe voI-
ue is 3), ond feIIs fhe user how mony
guesses if fook fo sink fhe DofCom.
File Edit Window Help Destroy
%java SimpleDotComGame
enter a number 2
hit
enter a number 3
hit
enter a number 4
miss
enter a number 1
kill
You took 4 guesses
a simpIer version of the game
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
99
Pcvc|ep|n] z 0|zss
As a iogiammci, you iolally havc a mcihouology/
ioccss/aioach io wiiiing couc. Wcll, so uo wc. Oui
scqucncc is ucsigncu io hcl you scc anu lcain) whai
wc`ic ihinIing as wc woiI ihiough couing a class. Ii
isn`i ncccssaiily ihc way wc oi wiiic couc in ihc
Rcal Woilu. In ihc Rcal Woilu, ol couisc, you`ll lollow
ihc aioach youi cisonal iclcicnccs, io|cci, oi
cmloyci uiciaic. Wc, howcvci, can uo iciiy much
whaicvci wc wani. Anu whcn wc cicaic a ]ava class as a
lcaining cxciicncc", wc usually uo ii liIc ihis:
Pigure out what the class is supposed to Jo.
List the instance variabIes and methods.
write prepcode for the methods. (ou'll see
this in |ust a moment.)
write test code for the methods.
ImpIement the class.
7est the methods.
Debug and reimpIement as needed.
Lxpress gratitude that we don't have to test
our so-called leotn|n exet|ence app on
actual live users.
Ihc !hrcc !h|n]s wc| | wr| !c fer
czrh r|zss:
prep code
A form of pseudocode, to help you focus on
the logic without stressing about syntax.
test code
A class or methods that will test the real code
and validate that it's doing the right thing.
reaI code
The actual implementation of the class. This is
where we write real Java code.

8impleDotCom class
write prep code
write test code
write f nal Java code
8impleDotComGame
class
write prep code

write test code [no]
write f nal Java code
prep code test code reaI code
This bar is displayed on the next set of pages to tell
you which part you're working on. Por example, if you
see this picture at the top of a page, it means you're
working on prepcode for the SimpleDotCom class.
prep code test code reaI code
3|rp|e0olCor c|ass
prep code
FIex those dendrites.
How wouId you decide which cIass or cIasses
to buiId , when you're writing a program!
Assuming that aII but the tiniest programs
need more than one cIass (if you're foIIowing
good DD principIes and not having cIass
do many different jobs), where do you start!
WWkm
Qw&W
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
100 chapter 5
8|mp|e0ot6om
|rl [| |ocal|orCe||s
|rl rur0ll|ls
3lr|r c|ec|Yourse|l(3lr|r uess)
vo|d selLocal|orCe||s(|rl[| |oc)
You`ll gci ihc iuca ol how iccouc oui vcision ol scuuocouc) woiIs as you
icau ihiough ihis cxamlc. Ii`s soii ol hall-way lciwccn ical ]ava couc anu a lain
English ucsciiiion ol ihc class. Mosi iccouc incluucs ihicc aiis: insiancc
vaiiallc ucclaiaiions, mcihou ucclaiaiions, mcihou logic. Thc mosi imoiiani
aii ol iccouc is ihc mcihou logic, lccausc ii uch ncs has io hacn,
which wc laici iianslaic inio , whcn wc aciually wiiic ihc mcihou couc.
prep code test code reaI code prep code
DECLARE ao |nt orro, to |o|o t|o |ocat|oo co||s. Ca|| |t |ocot|onCe||s.
DECLARE ao |nt to |o|o t|o oobo o ||ts. Ca|| |t num0fH|ts aoo 5EY |t to 0.
DECLARE a checkourse|f(j ot|oo t|at ta'os a Str|ng o t|o oso's gooss ('+', '3', otc.),
c|oc's |t, aoo otoos a oso|t oposoot|og a '||t', '|ss', o ''|||'.
DECLARE a setLocot|onCe||s(j sotto ot|oo t|at ta'os ao |nt orro, (.||c| |as t|o t|oo co||
|ocat|oos as |nts (2,3,+, otc.).
MEYHOD. Str|ng checkourse|f(Str|ng userCuessj
GEY t|o oso gooss as a St|og paaoto
CONVERY t|o oso gooss to ao |nt
REPEAY .|t| oac| o t|o |ocat|oo co||s |o t|o |nt aa
// COmPAR t|o oso gooss to t|o |ocat|oo co||
IF t|o oso gooss atc|os
INCREMENY t|o oobo o ||ts
// lIND OUT | |t .as t|o |ast |ocat|oo co||.
IF oobo o ||ts |s 3, REYURN ''|||' as t|o oso|t
EL5E |t .as oot a '|||, so REYURN'||t'
||| ||
EL5E t|o oso gooss o|o oot atc|, so REYURN '|ss'
||| ||
||| ||||/T
||| ||TC|
MEYHOD. vo|d setLocot|onCe||s(|nt[] ce||Locot|onsj
GEY t|o co|| |ocat|oos as ao |nt orro, paaoto
A55IGN t|o co|| |ocat|oos paaoto to t|o co|| |ocat|oos |ostaoco va|ab|o
||| ||TC|

SimpIeDotCom cIass
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
101
Wr| !| n] !hc mc!he4
|mp|cmcn!z!|ens
|c!s wr| !c !hc rcz|
mc!he4 re4c new, zn4 ]c!
!h|s peppy werk|n].
Bcloic wc siaii couing ihc
mcihous, ihough, lci`s lacI
u anu wiiic somc couc io
e ihc mcihous. Thai`s iighi,
wc`ic wiiiing ihc icsi couc
beo.e ihcic`s anyihing io icsi!
Thc concci ol wiiiing
ihc icsi couc hisi is onc ol
ihc iaciiccs ol Exiicmc
Piogiamming XP), anu
ii can maIc ii casici anu
lasici) loi you io wiiic youi
couc. Wc`ic noi ncccssaiily
saying you shoulu usc XP,
lui wc uo liIc ihc aii aloui
wiiiing icsis hisi. Anu XP |usi
ourJ cool.
Oh myl For o minufe
fhere I fhoughf you
weren'f gonno wrife your
fesf code frsf. Whool
Don'f score me Iike fhof.
Lxtreme Programming(XP) is a newcomer to the software
development methodology world. Considered by many
to be "the way programmers really want to work, XP
emerged in the late 90's and has been adopted by
companies ranging from the two-person garage shop
to the Pord Motor Company. The thrust of XP is that the
customer gets what he wants, when he wants it, even
when the spec changes late in the game.
XP is based on a set of proven practices that are all
designed to work together, although many folks do pick
and choose, and adopt only a portion of XP's rules. These
practices include things like:
Make small, but frequent, releases.
Develop in iteration cycles.
Don't put in anything that's not in the spec (no matter
how tempted you are to put in functionality "for the
future).
write the test code .
No killer schedules, work regular hours.
Pefactor (improve the code) whenever and wherever you
notice the opportunity.
Don't release anything until it passes all the tests.
Set realistic schedules, based around small releases.
Keep it simple.
Program in pairs, and move people around so that
everybody knows pretty much everything about the code.
Extreme Programming (XP)
prep code test code reaI code test code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
102 chapter 5
Wr| !|n] !cs! re4c fer !hc 8|mp|cPe!0em r|zss

MEYHOD Str|ng checkourse|f(Str|ng userCuessj
GEY t|o oso gooss as a St|og paaoto
CONVERY t|o oso gooss to ao |nt
REPEAY .|t| oac| o t|o |ocat|oo co||s |o t|o |nt aa
// COmPAR t|o oso gooss to t|o |ocat|oo co||
IF t|o oso gooss atc|os
INCREMENY t|o oobo o ||ts
// lIND OUT | |t .as t|o |ast |ocat|oo co||.
IF oobo o ||ts |s 3, REYURN '||||' as t|o oso|t
EL5E |t .as oot a '|||, so REYURN'|t'
||| ||
EL5E t|o oso gooss o|o oot atc|, so REYURN '||ss'
||| ||
||| ||||/T
||| ||TC|
Wc nccu io wiiic icsi couc ihai can maIc a SimlcDoiCom ol|cci
anu iun iis mcihous. Ioi ihc SimlcDoiCom class, wc ically
caic aloui only ihc LeIYou.eI() mcihou, alihough wc w.II havc
io imlcmcni ihc e1on.orCeII() mcihou in oiuci io gci ihc
LeIYou.eI() mcihou io iun coiiccily.
TaIc a goou looI ai ihc iccouc lclow loi ihc LeIYou.eI()
mcihou ihc e1on.orCeII() mcihou is a no-liainci sciici mcihou,
so wc`ic noi woiiicu aloui ii, lui in a ical` alicaiion wc mighi
wani a moic iolusi sciici` mcihou, which wc wouIJ wani io icsi).
Thcn asI youiscll, Il ihc chccIYouiscll) mcihou wcic
imlcmcnicu, whai icsi couc coulu I wiiic ihai woulu iovc io mc
ihc mcihou is woiIing coiiccily."
1. nstantiate a SimpleDotCom object.
2. Assign it a location (an array of 3 ints, like
{2,3,4}).
3. Create a String to represent a user guess
(2, 0, etc.).
4. nvoke the checkYourself() method pass-
ing it the fake user guess.
5. Print out the result to see if it's correct
(passed or failed).
Bzsc4 en !h|s prcpre4c: Hcrcs whz! wc shee|4 !cs!:
prep code test code reaI code test code
SimpIeDotCom cIass
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
writing a program
103
public class SimpleDotComTestDrive {
public static void main (String[] args) {
SimpleDotCom dot = new SimpleDotCom();
int[] locations = {2,3,4};
dot.setLocationCells(locations);

String userGuess = 2;
String result = dot.checkYourself(userGuess);
String testResult = failed;
if (result.equals(hit) ) {
testResult = passed;
}
System.out.println(testResult);
}
}
Ics! re4c fer !hc 8|mp|cPe!0em r|zss
(-,- a,- |
oa|| qa--(:|-

Maybe I'm missing some-


thing here, but how exactIy do
you run a test on something
that doesn't yet existl!

ou don't. we never said


you start by tunn|n the test,
you start by wt|t|n the test. At
the time you write the test code,
you won't have anything to run
it against, so you probably won't
be able to compile it until you
write 'stub' code that can com-
pile, but that will always cause
the test to fail (like, return null.)

7hen I stiII don't see the


point. Why not wait untiI the
code is written, and then whip
out the test code!

The act of thinking through


(and writing) the test code helps
clarify your thoughts about what
the method itself needs to do.
As soon as your implementation
code is done, you already have
test code |ust waiting to validate
it. 8esides, you lnow if you don't
do it now, you'll nevet do it.
There's always something more
interesting to do.
|deally, write a little test code,
then write only the implementa-
tion code you need in order to
pass that test. Then write a little
mote test code and write only
the new implementation code
needed to pass thot new test. At
each test iteration, you run oll
the previously-written tests, so
that you always prove that your
latest code additions don't break
previously-tested code.
-:l.-l.l- .
-|-l
-lc--
--:l
-
.- .- -l .--.] --
l- |-:.l-- - l- -l
:--
|? :--:-:-l- -l:
--l - . -::|- 7
`
-.- . .-
-:-- --::
--- l- :-:/---:-||` --l- -- l- -l :--
--:l, .- .:: l l-
.- --::
+,-+ :+ ,-+:.|
|n the next couple of pages we implement the SimpleDotCom class,
and then later we return to the test class. Looking at our test code
above, what else should be addedI what are we not testing in this
code, that we shoulJ be testing forI write your ideas (or lines of
code) below:
prep code test code reaI code test code
--l --l l- l-:l --:-|l
|.::- -- .|-'`
l- .- --:: |i` -:
.: . l', l': ----
--- l- :-ll-- --l- -- l- -l :--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
104 chapter 5
Thcic isn`i a cilcci maing liom iccouc io |avacouc, you`ll scc a lcw
au|usimcnis. Thc iccouc gavc us a much lciici iuca ol ihc couc nccus io
uo, anu now wc havc io hnu ihc ]ava couc ihai can uo ihc .
In ihc lacI ol youi minu, lc ihinIing aloui aiis ol ihis couc you mighi wani
oi nccu) io imiovc. Thc numlcis aic loi ihings syniax anu languagc
lcaiuics) you havcn`i sccn yci. Thcy`ic cxlaincu on ihc oosiic agc.
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = miss;
for (int cell : locationCells) {
if (guess == cell) {
result = hit;
numOfHits++;
break;
} // end if
} // end for
if (numOfHits == locationCells.length) {
result = kill;
} // end if
System.out.println(result);
return result;
} // end method
Ihc rhcrkYeersc|f|I mc!he4
:----l l- l--
l- .- -l
-.- . .-.|- l- -| l- --:-|l --'||
--l--- -l -::' - .: l- -.-|l
|- -- .::--- . -::'`
---.l -l -.: :-|| - l- |-:.l--c-||:
.--.] |-.: :-|| |-:.l-- - l- --:l`
:--.-- l- -:-- --:: l- l:
-|----l |:-||` - l- .--.]
-- -l . l'
-l --l - l- |--, -- ---
l- l-:l l- -l-- :-||:
--'-- --l - l- |--, -l |-l': :-- --'--
--- '-.' |l ? l--:` .- :.-- l-
--:-|l l-- l- r||'
:|.] l- --:-|l -- l- -:--
|M::', --|-:: l -.: :.-- l- +l' -- r||'`
--l--- l- --:-|l .: l-
l- :.||- --l-
GEY t|o oso
gooss
CONVERY
t|o oso gooss to
ao
REPEAY .|t|
oac| co|| |o t|o
aa
IF t|o oso gooss
atc|os
INCREMENY
t|o oobo o
||ts
// lIND OUT |
|t .as t|o |ast co||
IF oobo o ||ts
|s 3,
REYURN ''|||'
as t|o oso|t
EL5E |t .as
oot a '|||, so
REYURN'||t'
EL5E
REYURN
'|ss'
1
prep code test code reaI code reaI code
2
3
4
1
SimpIeDotCom cIass
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
105
1es! !hc ncw s!eff
Thc ihings wc havcn`i sccn lcloic
aic on ihis agc. Sio woiiying! Thc
icsi ol ihc uciails aic ai ihc cnu ol
ihc chaici. This is |usi cnough io lci
you Icc going.
1
Converfing o
String to un int
B The for Ioop
The post-increment
operutor
4
breuk sfofemenf
1nteger.parse1nt{"")
A
:|.:: l.l
:: -
l )..
A --l- - l-
|-l--- :|.:: l.l
---: -- l- .-:-'
. l-- -l- l- -l
l ----:--l:
1
.

-
:
.

l
-
-

tcr {Int ceII : IccatIcn0eIIs) ( ]


l-:|.-- . .-.|- l.l -|| -| --- -|----l
--- l- .--.] !.: l-- l--- l- |--,
l: .-.|- |- l: :.:- .- -l .-.|- -.--
:-||'`, -|| -| . ----l -|----l --- l-
.--.], --l| l--- .-- -- ---- -|----l: |-- l-
:-- --: . --.' :-- ++ -|--`
num0tHIts
1- ++ --.-: . | l-
-.l---': l--- |- -l--
---:, -:-----l ] |`
---6+l:++ : l- :.-- |-
l: :.:-` .: :.]- ---6+l: =
---6+l: + |, -:-l :|l|]
---- -:--l
break
6-l: ]-- --l - . |-- |---.l-|] l ---
N- l--.l--, -- --|-.- l-:l, -:l -l --l ---'
prep code test code reaI code reaI code
1
2
3
4
1
- .--.] l- l--.l- --- - l- |--
!
.: l-
- l--- l- |--, l- --l
-|--
--l - l- .--.] -
|| - .::-- l-
l- .-.|- :-||' |M
--- -- l: .l l-
-- - l: :.l--`
-. l: -- |-- -:|.-.l-- .: ---.l
-- -.: -|----l - l- '|-:.l--c-||:'
.--.] l.- l- --l -|----l - l- .--.]
.- .::- l l- l- -l .-.|- ':-||''
1- :-|-- |` --.-: -', :- l-
--|- l- --.-: -- -.: -l
.|-- |N |-:.l--c-||:'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
106 chapter 5
(-,- a,- |
oa|| qa--(:|-

What happens in
Integer.parseInt() if the thing you
pass isn't a number! And does it
recognize speIIed-out numbers,
Iike "three"!

|nteger.parse|nt() works only


on Strings that represent the ascii
values for digits (0,l,2,3,4,5,6,7,8,9).
|f you try to parse something like
"two or "blurp, the code will blow
up at runtime. (8y olow u, we
actually mean thtow on excet|on,
but we don't talk about exceptions
until the Lxceptions chapter. So for
now, olow u is close enough.)

In the beginning of the


book, there was an exampIe of a
Ioop that was reaIIy different
from this one-are there two
different styIes of Ioops!
es! Prom the first version of
1ava there has been a single kind
of lot loop (explained later in this
chapter) that looks like this:
for (int i 0, i < l0, i++) }
// do something l0 times
}
ou can use this format for any
kind of loop you need. 8ut...
beginning with 1ava 5.0 ( Tiger),
you can also use the enhonceJ for
loop (that's the official description)
when your loop needs to iterate
over the elements in an array (or
onothet kind of collection, as you'll
see in the next chapter). ou can
always use the plain old for loop
to iterate over an array, but the
enhonceJ for loop makes it easier.
I|nz| re4c fer 8|mp|cPe!0em zn4 8|mp|cPe!0emIcs!cr
public class SimpleDotComTestDrive {
public static void main (String[] args) {
SimpleDotCom dot = new SimpleDotCom();
int[] locations = {2,3,4};
dot.setLocationCells(locations);
String userGuess = 2;
String result = dot.checkYourself(userGuess);
}
}
public class SimpleDotCom {
int[] locationCells;
int numOfHits = 0;

public void setLocationCells(int[] locs) {
locationCells = locs;
}
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = miss;
for (int cell : locationCells) {
if (guess == cell) {
result = hit;
numOfHits++;
break;
}
} // out of the loop
if (numOfHits ==
locationCells.length) {
result = kill;
}
System.out.println(result);
return result;
} // close method
} // close class
What shouId we see
when we run this code!
The test code makes a
SimpleDotCom ob|ect
and gives it a location at
2,3,4. Then it sends a fake
user guess of "2 into the
checkouself() method.
|f the code is working
correctly, we should see the
result print out:
java SimpleDotComTestDrive
hit
prep code test code reaI code reaI code
There's a little bug lurking here. t compiles and
runs, but sometimes... don't worry about it for now,
but we have to face it a little later.
SimpIeDotCom cIass
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
107
+,-+ :+ ,-+:.|
we built the test class, and the SimpleDotCom class. 8ut we still haven't
made the actual ome. Given the code on the opposite page, and the spec for
the actual game, write in your ideas for prepcode for the game class. we've given
you a few lines here and there to get you started. The actual game code is on the
next page, so Jenr rurn rhe nge unril yeu Je rhis exercisel
ou should have somewhere between l2 and l8 lines (including the ones we wrote,
but not including lines that have only a curly brace).
MEYHOD pu5||c stot|c vo|d mo|n (Str|ng [] orgsj
DECLARE ao |ot va|ab|o to |o|o t|o oobo o oso goossos, oaoo

COMPUYE a aooo oobo bot.ooo 0 aoo + t|at .||| bo t|o stat|og |ocat|oo co|| pos|t|oo
WHILE t|o oot co |s st||| a||vo .
GEY oso |opot o t|o coaoo ||oo

7he SimpIeDotComCame
needs to do this:
l. Make the single
SimpleDotCom Ob|ect.
2. Make a location for it (three
consecutive cells on a single
row of seven virtual cells).
3. Ask the user for a guess.
4. Check the guess.
5. Pepeat until the dot com is
dead .
6. Tell the user how many
guesses it took.
File Edit Window Help Runaway
%java SimpleDotComGame
enter a number 2
hit
enter a number 3
hit
enter a number 4
miss
enter a number 1
kill
You took 4 guesses
remp|c!c ]zmc |n!crzr!|en
prep code test code reaI code prep code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
108 chapter 5
pu5||c stot|c vo|d mo|n (Str|ng [] orgsj
DECLARE ao |ot va|ab|o to |o|o t|o oobo o oso goossos, oaoo .C,C.esses sot |t to 0.
MAKE a oo. S|p|o|otCo |ostaoco
COMPUYE a aooo oobo bot.ooo 0 aoo + t|at .||| bo t|o stat|og |ocat|oo co|| pos|t|oo
MAKE ao |ot aa .|t| 3 |ots os|og t|o aooo|-goooatoo oobo, t|at oobo |ocoootoo b +,
aoo t|at oobo |ocoootoo b 2 (oap|o. 3,+,5)
INVOKE t|o set!ccotcCe''s() ot|oo oo t|o S|p|o|otCo |ostaoco
DECLARE a boo|oao va|ab|o oposoot|og t|o stato o t|o gao, oaoo s^'.e 5EY |t to too
WHILE t|o oot co |s st||| a||vo (|s/||vo == too) .
GEY oso |opot o t|o coaoo ||oo
t|o oso gooss
INVOKE t|o cec'`c.se',() ot|oo oo t|o S|p|o|otCo |ostaoco
INCREMENY .C,C.esses va|ab|o
o oot co ooat|
IF oso|t |s ''|||'
5EY s^'.e to a|so (.||c| oaos .o .oo't ooto t|o |oop aga|o)
PRINY t|o oobo o oso goossos
||| ||
||| \|||
||| ||TC|
prep code test code reaI code prep code
|rcpre4c fer !hc 8|mp|cPe!0em0zmc r|zss
Ivcry!h|n] hzppcns |n mz|n|I
Thcic aic somc ihings you`ll havc io iaIc on laiih. Ioi cxamlc, wc havc onc
linc ol iccouc ihai says, GET usci inui liom commanu-linc". Ici mc icll
you, ihai`s a liiilc moic ihan wc wani io imlcmcni liom sciaich iighi now. Bui
haily, wc`ic using OO. Anu ihai mcans you gci io asI somc oLe. class/ol|cci
io uo somcihing loi you, wiihoui woiiying aloui ii uocs ii. Whcn you wiiic
iccouc, you shoulu assumc ihai oeLow you`ll lc allc io uo whaicvci you
nccu io uo, so you can ui all youi liainowci inio woiIing oui ihc logic.
meeogjjve jg
0or'l Wor| ore parl ol l|e ora|r lor loo |or a slrelc| al ore l|re.
wor||r jusl l|e |ell s|de ol l|e ora|r lor rore l|ar 30 r|rules
|s |||e Wor||r jusl your |ell lor 30 r|rules. 0|ve eac| s|de
ol your ora|r a orea| oy sW|lc||r s|des al reu|ar |rlerva|s.
w|er you s||ll lo ore s|de, l|e ol|er s|de els lo resl ard
recover. Lell-ora|r acl|v|l|es |rc|ude l||rs |||e slep-oy-slep
sequerces, |o|ca| proo|er-so|v|r, ard ara|ys|s, W|||e l|e
r||l-ora|r ||c|s |r lor relap|ors, creal|ve proo|er-so|v|r,
pallerr-ralc||r, ard v|sua||z|r.
SimpIeDotCom cIass
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
109
How muny
hits did you get
Iust month? IncIuding
repeof visifors7
Yes,,,
3
8ll P0lk5
Your Java prorar s|ou|d slarl W|l| a |||-
|eve| des|r.
Typ|ca||y you'|| Wr|le l|ree l||rs W|er you
creale a reW c|ass:
recode
testcode
reel [Jeve} code
Prepcode s|ou|d descr|oe unar lo do, rol nou
lo do |l. lrp|ererlal|or cores |aler.
use l|e prepcode lo |e|p des|r l|e lesl
code.
wr|le lesl code oelore you |rp|ererl l|e
rel|ods.
-, ,-- /-:: 7--
C|oose lor |oops over un||e |oops W|er you
|roW |oW rary l|res you Warl lo repeal l|e
|oop code.
use l|e pre/posl |noremenr operalor lo add 1
lo a var|ao|e (x,)
use l|e pre/posl oeoremenr lo suolracl 1 lror
a var|ao|e (x--,)
use Integer.parseInt() lo el l|e |rl
va|ue ol a 3lr|r.
Integer.parseInt() Wor|s or|y |l l|e
3lr|r represerls a d||l ('0,1,2, elc.)
use oreak lo |eave a |oop ear|y (|.e. ever |l
l|e ooo|ear lesl cord|l|or |s sl||| lrue).
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
110 chapter 5
public static void main(String[] args) {
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);

int[] locations = {randomNum, randomNum+1, randomNum+2};
theDotCom.setLocationCells(locations);
boolean isAlive = true;
while(isAlive == true) {
String guess = helper.getUserInput(enter a number);
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if (result.equals(kill)) {
isAlive = false;
System.out.println(You took + numOfGuesses + guesses);
} // close if
} // close while
} // close main
]usi as you uiu wiih ihc SimlcDoiCom class, lc ihinIing aloui aiis ol ihis couc
you mighi wani oi nccu) io imiovc. Thc numlcicu ihings aic loi siull wc
wani io oini oui. Thcy`ic cxlaincu on ihc oosiic agc. Oh, il you`ic wonuci-
ing why wc sIicu ihc icsi couc hasc loi ihis class, wc uon`i nccu a icsi class loi
ihc gamc. Ii has only onc mcihou, so whai woulu you uo in youi icsi couc. MaIc
a en.ne class ihai woulu call n.r() on L. class. Wc uiun`i loihci.
Ihc ]zmcs mz|n|I mc!he4
-.- . .-.|- l- l-.: --
-.-] --::-: l- -:-- -.-:
l: : . :-:.| :|.:: -- ---l- l.l .:
l- --l- -- -ll- -:-- --l --
---, --l-- l': .-l - )..
DECLARE a va|-
ab|o to |o|o oso
gooss cooot, sot |t
to 0
MAKE a S|p|o|ot-
Co ob,oct
COMPUYE a
aooo oobo
bot.ooo 0 aoo +
MAKE ao |ot aa
.|t| t|o 3 co|| |oca-
t|oos, aoo
INVOKE sot|oca-
t|ooCo||s oo t|o oot
co ob,oct
DECLARE a boo|-
oao |s/||vo
WHILE t|o oot
co |s st||| a||vo
GEY oso |opot
|t
INVOKE c|oc'Yo-
oso|() oo oot co
INCREMENY
ooCCoossos
IF oso|t |s ''|||'
5EY gao/||vo to
a|so
PRINY t|o oobo
o oso goossos
1
prep code test code reaI code reaI code
2
1
-.- l- -l :-- --:l
-.- . -.--- ----- -- l- -:l
:-||, .- -:- l l- -.- l- :-||
|-:.l--: .--.]
- l- -l :-- l: |-:.l--: |l- .--.]`
-.- . --|-.- .-.|- l- l-.: --l-- l- .--
: :l|| .|-, l- -:- - l- -|- |-- l-:l ---.l
-|- .-- : :l|| .|-
-l -:-- --l l--
.: l- -l :-- l- :-: l- --::. :.- l- --l---- --:-|l - . l--
-:-----l --:: :---l
-.: l . ||' :-, :-l :A|- l- .|:- |:- -- ---'l
--~--l-- l- |--` .- --l -:-- --:: :---l
SimpIeDotComGame cIass
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
111
rzn4em|I zn4 ]c!0scr|npe!|I
Two ihings ihai nccu a lii moic
cxlaining, aic on ihis agc. This is
|usi a quicI looI io Icc you going,
moic uciails on ihc GamcHclci
class aic ai ihc cnu ol ihis chaici.
1
0effing user inpuf
using fhe 0omeHeIper
cIoss
B
Moke o rondom
number
Int randcmNum = {Int) {math.randcm{) * S)
prep code test code reaI code reaI code
2
1
1: : . ':.:l', .- l --:-: l- l-
---.l-|] .l-- l l- -:--- l-
l]- - l- :.:l |- l- l]- - l-
.---:` M.l-.--- --l---: . --|-,
:- -- .- l- :.:l l l- - .- -l |--
-.-l . -:- --|- ----- -l---- o
.- +` |- l: :.:-, l- :.:l |-: -
l- -.:l--.| .-l - l- --|-
w- -:|.-- .- -l .-.|- l- -|
l- -.--- ----- -- -l .:
A :|.:: l.l :---:
-l )..
A --l- - l-
M.l :|.::
1- M.l-.--- --l-
--l---: . ----- --- ---- l-
-:l |-:: l.- --- - l: ----|.
|-l l- :.:l`, --l---: . -----
--- o l- + |- o ~ +,
:.:l l- .- -l`
StrIng guess = heIper.getUser1nput{"enter a number")
w- -:|.-- . l-- .-.|- l-
-| l- -:-- --l l-- --
-l .: |?', -', -l:`
A- -:l.-:- -- -.- -.-|--,
- . :|.:: l.l -- -|l l-
-| -l l- .-- |l': :.||-
6.--+-|-- .- ]-- .--'l
:--- l ]-l |]-- -||`
A --l- - l- 6.--+-|-- :|.::
l.l .:: l- -:-- -- :---.-~
|-- --l, --.: l - .l-- l-
-:-- l: !1cN, .- -: .:
l- --:-|l .: . l--
1
: --l- l.-: . l--
.-----l l.l l -:-: l- ---l
l- -:-- .l l- :---.-~|--
w
.l--- ]-- .:: - --- -l:
:|.]- - l- l----.| -:l
---- l- --l- :l.-l:
|--- -- -:-- --l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
112 chapter 5
0nc |zs! r|zss: 0zmcHc|pcr
prep code test code reaI code reaI code
Wc madc thc dot com class.
Wc madc thc gome class.
All that's lcIt is thc heIper class- ihc onc wiih ihc
gciUsciInui) mcihou. Thc couc io gci commanu-
linc inui is moic ihan wc wani io cxlain iighi now.
Ii ocns u way ioo many ioics lcsi lcli loi laici.
Iaici, as in chaici 14.)
import java.io.*;
public class GameHelper {
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + );
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0 ) return null;
} catch (IOException e) {
System.out.println(IOException: + e);
}
return inputLine;
}
}
I pre-cooked
some code so you
don'f hove fo moke
if yourseIf.
0zsJj-hskz
0aJz
]usi coy* ihc couc lclow anu comilc ii inio
a class namcu GamcHclci. Dio all ihicc
classcs SimlcDoiCom, SimlcDoiComGamc,
GamcHclci) inio ihc samc uiiccioiy, anu maIc ii
youi woiIing uiiccioiy.
Whcncvci you scc ihc logo, you`ic scc-
ing couc ihai you havc io iyc as-is anu iaIc on laiih.
Tiusi ii. You`ll lcain how ihai couc woiIs .
0zsJj-hskz
0aJz
*We know how much you enjoy typing, but for those rare
moments when you'd rather do something else, we've made
the Ready-bake Code available on wickedlysmart.com.
Camehe|per c|ass (Ready-bake}
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
writing a program
113
File Edit Window Help Smile
%java SimpleDotComGame
enter a number 1
miss
enter a number 2
miss
enter a number 3
miss
enter a number 4
hit
enter a number 5
hit
enter a number 6
kill
You took 6 guesses
remp|c!c ]zmc |n!crzr!|en
(your mileage may vary)
Ic!s p|zy
Here's whof hoppens when we
run if ond enfer fhe numbers
I,Z,3,4,b,o. Lookin' good.
File Edit Window Help Faint
%java SimpleDotComGame
enter a number 1
hit
enter a number 1
hit
enter a number 1
kill
You took 3 guesses
4|ffcrcn! ]zmc |n!crzr!|en
(yikes)
Here's whof hoppens when we
enfer I,I,I.
Whz!s !h|s! !

+,-+ :+ ,-+:.|
It's a cIiff-hangerl
will we the bugI
will we the bugI
Stay tuned for the next chapter, where we answer
these questions and more...
And in the meantime, see if you can come up with
ideas for what went wrong and how to fix it.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
114 chapter 5
tcr{Int I = 0 I < 100 I)( ]
rcpcz! fer 100 rcps:
Kc]e|zr |nen-cnhznrc4I fer |eeps
-l.|-.l--
--|-.- l-:l
l--.l-- ---::--
What it means in pIain ngIish: "Pepeat l00 times.
How the compiIer sees it:

create a variable | and set it to 0.

repeat while | is less than l00.

at the end of each loop iteration, add l to |
Part Dne: inirinliznrien
Use this part to declare and initialize a variable to use within the loop body.
ou'll most often use this variable as a counter. ou can actually initialize more
than one variable here, but we'll get to that later in the book.
Part 7wo: beelenn resr
This is where the conditional test goes. whatever's in there, it must resolve to a
boolean value (you know, rrue or Inlse). ou can have a test, like (x > 4), or you
can even invoke a method that returns a boolean.
Part 7hree: irernrien exressien
|n this part, put one or more things you want to happen with each trip through
the loop. Keep in mind that this stuff happens at the enJ of each loop.
-:l~-:-----l ---.l--
for Ioops
Merc z|ee! fer |eeps
Wc`vc covcicu all ihc gamc couc loi chaici lui wc`ll icI ii u again
io hnish ihc ucluxc vcision ol ihc gamc in ihc ncxi chaici). Wc uiun`i
wani io iniciiui youi woiI wiih somc ol ihc uciails anu lacIgiounu inlo,
so wc ui ii lacI hcic. Wc`ll siaii wiih ihc uciails ol loi loos, anu il you`ic
a C++ iogiammci, you can |usi sIim ihcsc lasi lcw agcs...
l- :-- l-
---.l --: --- |l- -]`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
115


Pre and Post Increment/Decrement Dperator
The shortcut for adding or subtracting l from a variable.

is the same as:

They both mean the same thing in this context:
"add l to the current value of x or "incremenr x by l
And:

is the same as:

Of course that's never the whole story. The placement of the
operator (either before or after the variable) can affect the re-
sult. Putting the operator oelote the variable (for example, ++x),
means, "htst, increment x by l, and then use this new value of x.
This only matters when the ++x is part of some larger expres-
sion rather than |ust in a single statement.
int x = 0; int z = ++x;
produces: x is l, z is l
8ut putting the ++ oltet the x give you a different result:
int x = 0; int z = x++;
produces: x is l, but z is 0! z gets the value of x and then x is
incremented.
P|ffcrcnrc |c! wccn fer zn4 wh||c
Ir|ps !hree]h z |eep
for (int i = 0; i < 8; i++) {
System.out.println(i);
}
System.out.println(done);
ee!pe!:
File Edit Window Help Repeat
%java Test
0
1
2
3
4
5
6
7
done
decIore inf
sef fo 0
is 87
(fhe booIeon
fesf)
frue
enfer Ioop
body
foIse
prinf "done"
(jump beIow Ioop)
prinf fhe voIue
of
incremenf
(fhe iferofion
expression)
A wh|le loop has only the boolean test, it doesn't have
a built-in initialization or iteration expression. A wh|le
loop is good when you don't know how many times to
loop and |ust want to keep going while some condi-
tion is true. 8ut if you lnow how many times to loop
(e.g. the length of an array, 7 times, etc.), a lot loop is
cleaner. Here's the loop above rewritten using wh|le:
int i = 0;
while (i < 8) {
System.out.println(i);
i++;
}
System.out.println(done);
-- .- l- -:-----l
l- :---l--
-- .- l- -:|.-- .- -l.|-- l- :---l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
116 chapter 5
tcr {StrIng name : nameArray) ( ]
1- -|----l: - l-
.--.] Mc1 -
:--.l|- -l l-
-:|.-- .-.|- l]-
wl -.: l--.l--,
. ----l -|----l
- l- .--.] -||
- .::-- l- l-
.-.|- -.--'
What it means in pIain ngIish: "Por each element in nameArray, assign the
element to the 'name' variable, and run the body of the loop.
How the compiIer sees it:

Create a String variable called nome and set it to null.

Assign the first value in nomeAttoy to name.



Pun the body of the loop (the code block bounded by curly braces).

Assign the next value in nomeAttoy to name.



Pepeat while thete ote st|ll elements |n the ottoy.
Part Dne: irernrien vnrinble Jeclnrnrien
Use this part to declare and initialize a variable to use within the loop body. with each
iteration of the loop, this variable will hold a different element from the collection. The
type of this variable must be compatible with the elements in the array! Por example,
you can't declare an |nt iteration variable to use with a 5tt|njj array.
Part 7wo: rhe ncrunl cellecrien
This must be a reference to an array or other collection. Again, don't worry about the
othet non-array kinds of collections yetyou'll see them in the next chapter.
l-:|.-- .- l--.l-- .-.|-
l.l -|| -| . :-|- -|----l
- l- .--.]
Ihc cnhznrc4 fer |eep
Bcginning wiih ]ava .0 Tigci), ihc ]ava languagc has a scconu Iinu ol o. loo
callcu ihc erLnreJ o., ihai maIcs ii casici io iiciaic ovci all ihc clcmcnis in an
aiiay oi oihci Iinus ol collcciions you`ll lcain aloui oLe. collcciions in ihc ncxi
chaici). Thai`s ically all ihai ihc cnhanccu loi givcs you-a simlci way io walI
ihiough all ihc clcmcnis in ihc collcciion, lui sincc ii`s ihc mosi common usc ol a
o. loo, ii was woiih auuing ii io ihc languagc. Wc`ll icvisii ihc erLnreJ o. Ioo in
ihc ncxi chaici, whcn wc ialI aloui collcciions ihai n.er` aiiays.
1
- :-- l-
---.l --: --- |l- -]`
enhanced for
1- :-||-:l-- - -|----l: l.l ]-- -.-l l- l--.l- ---
|-.-- l.l :------- -.-|--, l- :-- :.
l--|1 -.--A--.] = |--', M.-]', B-'!.
wl l- -:l l--.l--, l- -.-- .-.|- .: l- .|-- -
|--', .- -l l- :-:-- l--.l--, . .|-- - M.-]', -l:
N-l- ---- -- l-
---.--- |.--.- l-]'-
-:- - l- .:l, :--- --|-
---- l- l- --.-:- -- .:
l- -- -.:' -- l- --
-' |--, -:.-:- l.l': -- l
--.: -- !Ac+ l- |N l-
:-||-:l--'
1
- :-|-- |`
--.-: |N'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
117
lr c|apler 3 We la||ed aooul l|e s|zes ol l|e var|ous pr|r|l|ves, ard |oW you
car'l s|ove a o| l||r d|recl|y |rlo a sra|| l||r:
long y = 42;
int x = y; // won't compile
A |ong |s o|er l|ar ar |nr ard l|e corp||er car'l oe sure W|ere l|al |ong |as
oeer. ll r||l |ave oeer oul dr|r||r W|l| l|e ol|er |ors, ard la||r or rea||y
o| va|ues. To lorce l|e corp||er lo jar l|e va|ue ol a o|er pr|r|l|ve var|ao|e
|rlo a sra||er ore, you car use l|e operalor. ll |oo|s |||e l||s:
long y = 42; // so far so good
int x = (int) y; // x = 42
Pull|r |r l|e casl le||s l|e corp||er lo la|e l|e va|ue ol y, c|op |l doWr lo |rl
s|ze, ard sel x equa| lo W|alever |s |ell. ll l|e va|ue ol y Was o|er l|ar l|e
rax|rur va|ue ol x, l|er W|al's |ell W||| oe a We|rd (oul ca|cu|ao|e) ruroer:
long y = 40002;
// 40002 exceeds the 16-bit limit of a short

short x = (short) y; // x now equals -25534!
3l|||, l|e po|rl |s l|al l|e corp||er |els you do |l. Ard |el's say you |ave a l|oal-
|r po|rl ruroer, ard you jusl Warl lo el al l|e W|o|e ruroer (|nr) parl ol |l:
oat f = 3.14f;
int x = (int) f; // x will equal 3
Ard dor'l ever rn|nk aooul casl|r aryl||r lo a ooo|ear or v|ce versajusl
Wa|| aWay.
*lr |nvo|ves s|gn o|rs, o|nary, 'ruos oom|emenr ano orner geekery, a|| ol un|on
are o|sousseo ar rne oeg|nn|ng ol aeno|x 3.
int guess = Integer.parseInt(stringGuess);
The user types his guess at the command-
line, when the game prompts him. That
guess comes in as a String ("2, "0, etc.) ,
and the game passes that String into the
checkourself() method.
8ut the cell locations are simply ints in an
array, and you can't compare an int to a
String.
Por example, rhis wenr werk:
String num "2,
int x 2,
if (x num) // horrible explosion!
Trying to compile that makes the compiler
laugh and mock you:
operator == cannot be applied to
int,java.lang.String
if (x == num) { }
^
So to get around the whole apples and
oranges thing, we have to make the 5tt|n
"2 into the |nt 2. 8uilt into the 1ava class
library is a class called |nteger (that's right,
an |nteger closs, not the int t|m|t|ve),
and one of its |obs is to take Strings that
tetesent numbers and convert them into
octuol numbers.
1nteger.parse1nt{"")
. :|.:: l.l ::
-
l )..
. --l- - l- |-l---
:|.:: l.l ---: -- l-
.-:-' . l-- -l- l-
-l l ----:--l:
l.-: . l--
Converting a String to an int 0zs!|n]
pr|m| !| vcs
Iong
shorf
con be cosf fo
0
I
0
I
I
I
0
I I
I
0
I
but you might
Iose something
l: -- l- |-l :- -
--- :-l -
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
118 chapter 5
[[ ]zvz |j] n ([j, zg
,n(, z e]( ,ae
|j]. (a j j, ( ]zy ]Vp
zn] ](jn w[z( wa]]
([ a(a( w[n ([
gz an,/
] ge ]\Q
class Output {
public static void main{String args| {
Output o = new Output{|,
o.go{|,
}
void go{| {
int y = 7,
for{int x = l, x < 8, x++| {
y++,
if {x > 4| {
System.out.print{++y + " "|,
}
if {y > l4| {
System.out.println{" x = " + x|,
break,
}
}
}
}
File Edit Window Help Sleep
% java TestArrays
island = Fiji
island = Cozumel
island = Bermuda
island = Azores
File Edit Window Help Believe
% java Output
13 15 x = 6
File Edit Window Help OM
% java Output
12 14
File Edit Window Help ncense
% java Output
12 14 x = 6

exercise: Be the JVM


Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
119
A working 1ava program is all scrambled up on the fridge. Can you
reconstruct the code snippets to make a working 1ava program that
produces the output listed belowI 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!
x++,
for{int x = 0, x < 4, x++| {
public static void main{String args| {
if {x == l| {
System.out.println{x + " " + y|,
File Edit Window Help Raid
% java MultiFor
0 4
0 3
1 4
1 3
3 4
3 3
class MultiFor {
for{int y = 4, y > 2, y~~| {

CaJe Kagaets
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
120 chapter 5


How does a crossword puzzle
help you learn 1avaI well, all
of the words are 1ava related.
|n addition, the clues provide
metaphors, puns, and the like.
These mental twists and turns
burn alternate routes to 1ava
knowledge, right into your
brain!
Down
2. |ncrement type
3. Class's workhorse
5. Pre is a type of _____
6. Por's iteration ______
7. Lstablish rst value
8. while or Por
9. Update an instance variable
l2. Towards blastoff
l4. A cycle
l6. Talkative package
l9. Method messenger
(abbrev.)
Across
l. Pancy computer word
for build
4. Multi-part loop
6. Test rst
7. 32 bits
l0. Method's answer
ll. Prepcode-esque
l3. Change
l5. The big toolkit
l7. An array unit
l8. |nstance or local
l 2
l2
27
5
25
2l 20
6
29
l7
4
l0
l3
l9
28
26
l8
ll
22
l6
9
7
l4
24 23
3
l5
8
20. Automatic toolkit
22. Looks like a primitive,
but..
25. Un-castable
26. Math method
28. Converter method
29. Leave early
2l. As if
23. Add after
24. Pi house
26. Compile it and ____
27. ++ quantity
puzzIe: JavaCross
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
121
class MixFor5 {
public static void main(String [] args) {
int x = 0;
int y = 30;
for (int outer = 0; outer < 3; outer++) {
for(int inner = 4; inner > 1; inner--) {
y = y - 2;
if (x == 6) {
break;
}
x = x + 3;
}
y = y - 2;
}
System.out.println(x + + y);
}
}

A short 1ava program is listed below. One block of the program
is missing. our challenge is to match the candidate bIock of
code (on the left), with the output that you'd 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.
:.-.l- :--
--: ---

-.l: -.:
:.-.l- -l
--- - l-
-::|- --l-l:
x = x + 3,
x = x + 6,
x = x + 2,
x++,
x~~,
x = x + 0,
45 6
36 6
54 6
60 l0
l8 6
6 l4
l2 l4
Candidates: PossibIe output:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
122 chapter 5
class MultiFor {
public static void main{String args| {
for{int x = 0, x < 4, x++| {

for{int y = 4, y > 2, y~~| {
System.out.println{x + " " + y|,
}
if {x == l| { Whut wouId huppen
x++, if this code bIock cume
} before the 'y' for Ioop?
}
}
}
class Output {
public static void main{String args| {
Output o = new Output{|,
o.go{|,
}
void go{| {
int y = 7,
for{int x = l, x < 8, x++| {
y++,
if {x > 4| {
System.out.print{++y + " "|,
}
if {y > l4| {
System.out.println{" x = " + x|,
break,
}
}
}
} Did you remember to fuctor in the
breuk stutement? How did thut
uffect the output?
File Edit Window Help Sleep
% java TestArrays
island = Fiji
island = Cozumel
island = Bermuda
island = Azores
File Edit Window Help MotorcycleMaintenance
% java Output
13 15 x = 6
8e fhe JVM: Code Mognefs:
File Edit Window Help Monopole
% java MultiFor
0 4
0 3
1 4
1 3
3 4
3 3
exercise soIutions
]e;ejze o|ajoz
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
writing a program
123
x = x + 3,
x = x + 6,
x = x + 2,
x++,
x~~,
x = x + 0,
45 6
36 6
54 6
60 l0
l8 6
6 l4
l2 l4
Candidates: PossibIe output:
l 2
l2
27
5
25
2l 20
6
29
l7
4
l0
l3
l9
28
26
l8
ll
22
l6
9
7
l4
24 23
3
l5
8
I M P L E M E M T M
P F O P E
E X T P E M E P I M T
X L S P E T U P M H
P S E U D O C O D E P I O
P E O T C A S T T D
E I C A P I J T I
S T P A O A
S E L E M E M T V A P I A 8 L E
I P M A P I
O A E J A V A . L A M 0 Z
M T M I I E
I M T E 0 E P O P M
O T 8 O O L E A M
P A M D O M U S T
U M P A P S E I M T H
M 8 P E A I L
]azz|e o|ajoz
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
6 get to know the Java API
this is a new chapter 125
Java ships with hundreds of pre-buiIt cIasses. ou don't have to
reinvent the wheel if you know how to find what you need in the 1ava library, known as
the 1ava API. ouve ot oettet th|ns to Jo. |f you're going to write code, you might as well
write only the parts that are truly custom for your application. ou know those programmers
who walk out the door each night at 5 PMI The ones who don't even show u until l0 AMI
7hey use the 1ava API. And about eight pages from now, so will you. The core 1ava library
is a giant pile of classes |ust waiting for you to use like building blocks, to assemble your own
program out of largely pre-built code. The Peady-bake 1ava we use in this book is code you
don't have to create from scratch, but you still have to type it. The 1ava AP| is full of code you
don't even have to tye. All you need to do is learn to use it.
Using the Java Library
I con Iiff
heovy objecfs.
So if's frue7
We don'f hove fo
buiId if ourseIves7
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
126 chapter 6
|n eer |zs! rhzp!cr, wc |cf! yee
w| !h !hc r||ff-hzn]cr. |e].
File Edit Window Help Smile
%java SimpleDotComGame
enter a number 1
miss
enter a number 2
miss
enter a number 3
miss
enter a number 4
hit
enter a number 5
hit
enter a number 6
kill
You took 6 guesses
remp|c!c ]zmc |n!crzr!|en
(your mileage may vary)
Hew | !s seppesc4 !e |eek
Here's whof hoppens when we
run if ond enfer fhe numbers
I,Z,3,4,b,o. Lookin' good.
File Edit Window Help Faint
%java SimpleDotComGame
enter a number 2
hit
enter a number 2
hit
enter a number 2
kill
You took 3 guesses
4|ffcrcn! ]zmc |n!crzr!|en
(yikes)
Here's whof hoppens when we
enfer Z,Z,Z.
Hew !hc |e] |eeks
|n !hc rerrcn! vcrs|en, enrc
yee ]c! z h| !, yee rzn s|mp|y
rcpcz! !hz! h| ! ! we merc
!|mcs fer !hc k||||
we stiII have a bug
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 127
8e whz! hzppcnc4!
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = miss;
for (int cell : locationCells) {
if (guess == cell) {
result = hit;
numOfHits++;
break;
} // end if
} // end for
if (numOfHits == locationCells.length) {
result = kill;
} // end if
System.out.println(result);
return result;
} // end method
c----l l- l--
l- .- -l
M.- . .-.|- l- -| l- --:-|l --'||
--l--- |-l -::' - .: l- -.-|l
|- -- .::--- . -::'`
--.l -l -.: l- - l- .--.] c--.-- l- -:--
--:: l- l: -|----l
|:-||`, - l- .--.]
-- -l . l'
6-l --l - l- |--, -- ---
l- l-:l l- -l-- :-||:
w-'-- --l - l- |--, -l
|-l': :-- --'-- --- '-.'
|l ? l--:` .- :.-- l-
--:-|l l-- l- ||'
l:|.] l- --:-|l -- l- -:--
|-::', --|-:: l -.: :.-- l- l' -- ||'`
-l--- l- --:-|l .: l-
l- :.||- --l-
here's where |t
goes wrong. we
counted a h|t every
t|me the user
guessed a ce||
|ocat|on, even if
thet locetion hed
elreedy been hit!
we need a way to
know that when
a user makes
a h|t, he hasn't
prev|ous|y h|t that
ce||. |f he has, then
we don't want to
count |t as a h|t.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
128 chapter 6
A 'l---' - . .-l:-|.- -- - l- .--.] --.-: l.l
l- :-|| |-:.l-- .l l.l :.-- -- - l- 61+!
.--.] ||-:.l--c-||:` .: --- l
Hew 4e wc f| r | ! !
0 1 2 3 4 5 6
We need o woy fo know whefher o ceII hos oIreody been hif. Lef's run
fhrough some possibiIifies, buf frsf, we'II Iook of whof we know so for...
We hove o virfuoI row of 7 ceIIs, ond o DofCom wiII occupy fhree
consecufive ceIIs somewhere in fhof row. This virfuoI row shows o
DofCom pIoced of ceII Iocofions 4,b ond o.
We couId moke o second orroy, ond eoch fime fhe user mokes o hif, we
sfore fhof hif in fhe second orroy, ond fhen check fhof orroy eoch fime
we gef o hif, fo see if fhof ceII hos been hif before.

1- -l-.| ---, -l l-
? :-|| |-:.l--: -- l-
l
-lc-- --:l
The DofCom hos on insfonce voriobIe-on inf orroy-fhof hoIds fhof
DofCom objecf's ceII Iocofions.
0 I Z
4
5
6
1- .--.] -:l.-:- .-.|- l.l
-|: l- l-lc--': :-|| |-:.l--:
1: l-lc-- -|: l- ? .|--: -
+, -, .- | 1-:- .-- l- -----:
l- -:-- ---: l- --::
0p!|en enc
IocutionCeIIs
(insfonce voriobIe of
fhe DofCom)
0 I Z
faIse
hitCeIIs urruy
(fhis wouId be o
new booIeon orroy
insfonce voriobIe of
fhe DofCom)
1: .--.] -|: l--- .|--: ----:--l-
l- ':l.l-' - -.: :-|| - l- l-lc--':
|-:.l-- :-||: .--.] |-- -.-|-, l-
:-|| .l -- i : l, l-- :-l -- i -
l- lc-||:' .--.] l- 'l---'
faIse
true
fixing the bug
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 129
We couId jusf keep fhe one originoI orroy, buf chonge fhe voIue of ony hif
ceIIs fo -I. Thof woy, we onIy hove OME orroy fo check ond monipuIofe
2
0p!|en ! we
0p!|en enc |s !ee r|enky
Opfion one seems Iike more work fhon you'd expecf. If meons fhof eoch
fime fhe user mokes o hif, you hove fo chonge fhe sfofe of fhe second
orroy (fhe 'hifCeIIs' orroy), oh -- buf frsf you hove fo CHECI fhe 'hifCeIIs'
orroy fo see if fhof ceII hos oIreody been hif onywoy. If wouId work, buf
fhere's gof fo be somefhing beffer...
0 I Z



IocutionCeIIs
(insfonce voriobIe of
fhe DofCom)
. ~| .l . .-l:-|.- :-|| |-:.l-- --.-: l.l l- :-||
.: .|--.] --- l, :- --'-- --|] |--- -- ---~
--.l- -----: - l- .--.]
Opfion fwo is o IiffIe Iess cIunky fhon opfion one, buf if's nof very effcienf. You'd
sfiII hove fo Ioop fhrough oII fhree sIofs (index posifions) in fhe orroy, even if
one or more ore oIreody invoIid becouse fhey've been 'hif' (ond hove o -I voIue).
There hos fo be somefhing beffer...
0p!|en ! we |s z || !!|c |c!!cr, |e!
s!|| | prc!!y r|enky
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
130 chapter 6
REPEAY .|t| oac| o t|o |ocat|oo co||s |o t|o aa
// CC/|^| t|o oso gooss to t|o |ocat|oo co||
IF t|o oso gooss atc|os
INCREMENY t|o oobo o ||ts
// |` CJ | |t .as t|o |ast |ocat|oo co||.
IF oobo o ||ts |s 3, REYURN ''|||'
EL5E |t .as oot a '|||, so REYURN'||t'
||| ||
EL5E oso gooss o|o oot atc|, so REYURN '|ss'
||| ||
||| ||||/T
REPEAY .|t| oac| o t|o |ocat|oo co||s
// CC/|^| t|o oso gooss to t|o |ocat|oo co||
IF t|o oso gooss atc|os
REMOVE t||s co|| o t|o aa
// |` CJ | |t .as t|o |ast |ocat|oo co||.
IF t|o aa |s oo. opt, REYURN ''|||'
EL5E |t .as oot a '|||, so REYURN'||t'
||| ||
EL5E oso gooss o|o oot atc|, so REYURN '|ss'
||| ||
||| ||||/T
Ihc er|]|nz| prcpre4c fer pzr! ef !hc
rhcrkYeersc|f|I mc!he4:
I|fc wee|4 |c ]ee4 |f en|y wc ree|4
rhzn]c | ! !e:
prep code test code reaI code prep code
We deIefe eoch ceII Iocofion os if gefs hif, ond fhen modify fhe orroy fo
be smoIIer. Excepf orroys con'f chonge fheir si;e, so we hove fo moke o
new orroy ond copy fhe remoining ceIIs from fhe oId orroy info fhe new
smoIIer orroy.
3
0p!|en !hrcc
0 I Z


IocutionCeIIs urruy
8EFOPE ony ceIIs
hove been hif
1- .--.] :l.-l: --l -l . :-- - ?, .- -- |-- l--- .|| ? :-||: |-:l--: - l- .--.]` l- |-- -- . -.l: -l---- l- -:-- --:: .- l- :-|| .|-- |+,-, |`
w-- :-|| '-' : l, -- -.- . ---, :-.||-- .--.] -l --|] l- ---.-~ - :-|| |-:.l--:, .- .::- l l- l- ---.| |-:.l--c-||: ------:-

IocutionCeIIs urruy
AFTEP ceII 'b', which
wos of index I in fhe
orroy, hos been hif
0 I


0p!|en !hrcc wee|4 |c merh |c!!cr |f !hc zrrzy ree|4 shr|nk, se !hz! wc wee|4n! hzvc
!e mzkc z ncw smz||cr zrrzy, repy !hc rcmz|n|n] vz|ecs |n, zn4 rczss|]n !hc rcfcrcnrc.
prep code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 131
If onIy I couId fnd on orroy
fhof couId shrink when you remove
somefhing. And one fhof you didn'f hove
fo Ioop fhrough fo check eoch eIemenf, buf
insfeod you couId jusf usk it if it contuins
whof you're Iooking for. And if wouId Ief you
get fhings ouf of if, wifhouf hoving fo know
exocfIy which sIof fhe fhings ore in.
Thof wouId be dreomy. 8uf I know if's
jusf o fonfosy...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
when arrays aren't enough
132 chapter 6
Wzkc ep zn4 smc| | !hc |||rzry
As if by magic, there really is such a thing.
But it's not an array, it's an ArrayList.
A class in the core Java library {the AP}.
Thc ]ava Sianuaiu Euiiion which is whai you havc unlcss you`ic woiI-
ing on ihc Micio Euiiion loi small ucviccs anu lclicvc mc, ,ou`J Irow)
shis wiih hunuicus ol ic-luili classcs. ]usi liIc oui Rcauy-BaIc couc
cxcci ihai ihcsc luili-in classcs aic alicauy comilcu.
Thot meons no typing.
]usi usc cm.
6-- - . .-||-- :|.::-: -
l- ).. |-.-]
/-- :.- -:- l - ]--- :--
.: ]-- ---l- l ]---:-|
ArrayList
add(D
bject eIem
)

rem
ove(int index)
rem
ove(D
bject eIem
)
contains(D
bject eIem
)
ism
pty()
indexD
f(D
bject eIem
)
size()
get(int index)
Adds the ob|ect parameter to the list.
Pemoves the ob|ect at the index parameter.
Peturns 'true' if there's a match for the ob|ect parameter
Peturns 'true' if the list has no elements
Peturns either the index of the ob|ect parameter, or -l
Peturns the number of elements currently in the list
Peturns the ob|ect currently at the index parameter
Pemoves this ob|ect (if it's in the ArrayList).
|N-l- l- .|6-:l -|--` --l-
.:l-.||] |--: . |ll|- :l-.--- l.- l-
--- --'- :--- --- --'|| -l l- l-
--.| --- |.l-- - l- -- |-- ---, -:l
l- - l .: .- .|` --l- l.l
l.-: l- --:l ]-- -.-l l- .`
1: : -:l . :.-|- - 6M! -
l- --l-: - A--.]|:l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
get to know the Java API
you are here 133
8emc !h|n]s yee rzn 4e w| !h rrzyI|s!
1 Moke one
ArrayList<Egg> myList = new ArrayList<Egg>();
2 Puf somefhing in if
Egg s = new Egg();
myList.add(s);
7
Pemove somefhing from if
myList.remove(s);
4 Find ouf how mony fhings ore in if
int theSize = myList.size();
5 Find ouf if if confoins somefhing
boolean isIn = myList.contains(s);
6
Find ouf if if's empfy
boolean empty = myList.isEmpty();
Find ouf where somefhing is (i.e. ifs index)
int idx = myList.indexOf(b);
8
3 Puf onofher fhing in if
Egg b = new Egg();
myList.add(b);
A --- A--.]|:l --:l :
:--.l- -- l- -. |l': |ll|-
-:.-:- l': --l]
N-- l- A--.]|:l ---: . -'
l- -| l- ! --:l
1- A--.]|:l ---: ..- l- -|
l- :-:-- ! --:l
1- A--.]|:l : -|- i --:l: :-
l- :--|` --l- --l---: i
1- A--.]|:l l6! :--l.- l- ! --:l
------:- ] ':', :- :--l.-:|` --l---: l---
A--.]|:l : ----~.:- |--.-: -:l -- : o`
.- :-:- l- --:l ------:- ] '' -.: l-
:-:-- l- - l- |:l, --6|` --l---: |
l': --l-|] N61 --l], :- :!-l]|`
--l---: .|:-
+-] |-- - l :-.-'
l--'l ----] .--l l: --- ! .-|-~-.:-l :]-l.
-l ---. l -:l --.-: -.- l: . |:l - ! --:l:'
:
:

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
when arrays aren't enough
134 chapter 6
+,-+ :+ ,-+:.|

ArrayList<String> myList = new
ArrayList<String>();
l-- |1 -]|:l = --- l--|i1.
String a = new String(whoohoo);
l-- . = --- l--|-----'`.
myList.add(a);
String b = new String(Frog);
l-- = --- l--||--'`.
myList.add(b);
int theSize = myList.size();
Object o = myList.get(1);
myList.remove(1);
boolean isIn = myList.contains(b);
rrzyI|s! rc]e|zr zrrzy
Pill in the rest of the table below by looking at the ArrayList code
on the left and putting in what you think the code might be if it
were using a regular array instead. we don't expect you to get all
of them exactly right, so |ust make your best guess.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 135
(-,- a,- |
oa|| qa--(:|-

So ArrayList is cooI, but


how wouId I know it exists!
The question is really,
"How do | what's in the
AP|I and that's the key to your
success as a 1ava programmer.
Not to mention your key to
being as lazy as possible while
still managing to build software.
ou might be amazed at how
much time you can save when
somebody else has already done
most of the heavy lifting, and
all you have to do is step in and
create the fun part.
8ut we digress... the short
answer is that you spend some
time learning what's in the core
AP|. The long answer is at the
end of this chapter, where you'll
learn to do that.

ut that's a pretty big


issue. Not onIy do I need to
know that the 1ava Iibrary
comes with ArrayList, but more
importantIy I have to know
that ArrayList is the thing that
can do what I wantl So how
do I go from a need-to-do-
something to a-way-to-do-it
using the API!

Now you're really at the


heart of it. 8y the time you've
finished this book, you'll have
a good grasp of the language,
and the rest of your learning
curve really is about knowing
how to get from a problem to
a solution, with you writing the
least amount of code. |f you can
be patient for a few more pages,
we start talking about it at the
end of this chapter.
HeadFirst: So, ArrayLists are like arrays, right?
ArrayList: In their oreams am an o.ct thank you very much.
HeadFirst: Il I`m not mistaken, arrays are objects too. They live on the heap right
there with all the other objects.
ArrayList: Sure arrays go on the heap, , but an array is still a wanna-be
ArrayList. A poser. Objects have state ooo behavior, right? We`re clear on that. But
have you actually trieo calling a methoo on an array?
HeadFirst: Now that you mention it, can`t say I have. But what methoo woulo I
call, anyway? I only care about calling methoos on the stull I put io the array, not
the array itsell. Ano I can use array syntax when I want to put things in ano take
things out ol the array.
ArrayList: Is that so? You mean to tell me you actually r.o..o something lrom an
array? ,Sheesh, where oo they troio you guys? McJava`s?,
HeadFirst: Ol cor. I take something out ol the array. I say Dog o ~ oogArray|1|
ano I get the Dog object at inoex 1 out ol the array.
ArrayList: Allright, I`ll try to speak slowly so you can lollow along. You were ot,
I repeat ot, removing that Dog lrom the array. All you oio was make a copy ol the
r.f.r.oc. t t/. D ano assign it to another Dog variable.
HeadFirst: Oh, I see what you`re saying. No I oion`t actually remove the Dog
object lrom the array. It`s still there. But I can just set its relerence to null, I guess.
ArrayList: But I`m a nrst-class object, so I have methoos ano I can actually, you
know, o things like remove the Dog`s relerence lrom mysell, not just set it to null.
Ano I can change my size, o,oooicoll, ,look it up,. Just try to get an orro, to oo that
HeadFirst: Gee, hate to bring this up, but the rumor is that you`re nothing more
than a glorineo but less-elncient array. That in lact you`re just a wrapper lor an
array, aooing extra methoos lor things like resizing that I woulo have hao to write
mysell. Ano while we`re at it, ,o coo`t ...o /lo rioiti.. Isn`t that a big limitation?
ArrayList: I can`t o.li... you buy into that urban legeno. No, I am ot just a less-
elncient array. I will aomit that there are a lew .xtr.o.l, rare situations where an
array might be just a tao, I repeat, too bit laster lor certain things. But is it worth the
oioicol. perlormance gain to give up all this o.r. Still, look at all this .xioilit,. Ano
as lor the primitives, ol cor. you can put a primtive in an ArrayList, as long as it`s
wrappeo in a primitive wrapper class ,you`ll see a lot more on that in chapter 10,.
Ano as ol Java 5.0, that wrapping ,ano unwrapping when you take the primitive out
again, happens automatically. Ano allright, I`ll oc/ool.o. that yes, il you`re using an
ArrayList ol rioiti.., it probably is laster with an array, because ol all the wrapping
ano unwrapping, but still... who really uses primitives t/.. oays?
Oh, look at the time I`o lot. fr Pilot.. We`ll have to oo this again sometime.
This week's interview:
ArrayList, on arrays
1a-a spese3
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
136 chapter 6
0empzr|n] rrzyI|s! !e z rc]e|zr zrrzy

ArrayList<String> myList = new
ArrayList<String>();
String [] myList = new String[2];
String a = new String(whoohoo); String a = new String(whoohoo);
myList.add(a); myList[0] = a;
String b = new String(Frog); String b = new String(Frog);
myList.add(b); myList[1] = b;
int theSize = myList.size(); int theSize = myList.length;
Object o = myList.get(1); String o = myList[1];
myList.remove(1); myList[1] = null;
boolean isIn = myList.contains(b); boolean isIn = false;
for (String item : myList) {
if (b.equals(item)) {
isIn = true;
break;
}
}
+---': ---- l
:l.-l: l- |--
--.||] ----l
rrzyI|s! rc]e|zr zrrzy
Noiicc how wiih AiiayIisi, you`ic woiIing
wiih an ol|cci ol iyc AiiayIisi, so you`ic |usi
invoIing icgulai olu mcihous on a icgulai olu
ol|cci, using ihc icgulai olu uoi ociaioi.
Wiih an n..n,, you usc e.nI n..n, ,rn: liIc
myIisi]0| loo) ihai you won`i usc anywhcic
clsc cxcci wiih aiiays. Evcn ihough an
aiiay . an ol|cci, ii livcs in iis own sccial
woilu anu you can`i invoIc any mcihous on
ii, alihough you can acccss iis onc anu only
insiancc vaiiallc, IerL.
difference between ArrayList and array
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 137
1
A plain old array has to know its
size at the time it's created.
Bui loi AiiayIisi, you |usi maIc an ol|cci ol
iyc AiiayIisi. Evciy iimc. Ii ncvci nccus io
Inow how lig ii shoulu lc, lccausc ii giows
anu shiinIs as ol|ccis aic auucu oi icmovcu.
2
To put an ob]ect in a regular array,
you must assign it to a specihc
location.
(An index from 0 to one less than the length of
the array.)
myList[1] = b;
Il ihai inucx is ouisiuc ihc lounuaiics ol ihc
aiiay liIc, ihc aiiay was ucclaicu wiih a sizc ol
2, anu now you`ic iiying io assign somcihing
io inucx S), ii llows u ai iuniimc.
Wiih AiiayIisi, you can sccily an inucx us-
ing ihc nJJ(nrIr, nrObe) mcihou, oi you
can |usi Icc saying nJJ(nrObe) anu ihc
AiiayIisi will Icc giowing io maIc ioom loi
ihc ncw ihing.
myList.add(b);
3
Arrays use array syntax that's not
used anywhere else in Java.
Bui AiiayIisis aic lain olu ]ava ol|ccis, so
ihcy havc no sccial syniax.
myList[1]
4
new String[2]
new ArrayList<String>()
N--: . :--
N- :-- ----- |.|l-- ]-- :.-
- l . :-- ]-- -.-l l-`
0empzr|n] rrzyI|s! !e z rc]e|zr zrrzy
N--: .- --
N- --
ArrayLists in Java 5.0 are
parameterized.
Wc |usi saiu ihai unliIc aiiays, AiiayIisis
havc no sccial syniax. Bui ihcy Jo usc
somcihing sccial ihai was auucu io ]ava .0
Tigci-porometerized types.
ArrayList<String>
Piioi io ]ava .0, ihcic was no way io ucclaic
ihc ,e ol ihings ihai woulu go in ihc
AiiayIisi, so io ihc comilci, all AiiayIisis
wcic simly hciciogcnous collcciions ol
ol|ccis. Bui now, using ihc iycGocsHcic>
syniax, wc can ucclaic anu cicaic an
AiiayIisi ihai Inows anu icsiiicis) ihc
iycs ol ol|ccis ii can holu. Wc`ll looI ai ihc
uciails ol aiamciciizcu iycs in AiiayIisis
in ihc Collcciions chaici, so loi now, uon`i
ihinI ioo much aloui ihc anglc liacIci >
syniax you scc whcn wc usc AiiayIisis. ]usi
Inow ihai ii`s a way io loicc ihc comilci io
allow only a sccihc iyc ol ol|cci (Le ,e .r
nrIe b.nIe) in ihc AiiayIisi.
1- .--.] -.:-l: | 1 .-- :-:.|
:]-l. -:- --|] -- .--.]:
1- l-- - .-|- -.:-l: : . l]-
.-.--l--' A--.]|:ll-- --.-: :-|] .
|:l - l--:', .: --:- l- A--.]|:ll-
-: --.-:, . |:l - l-:'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
138 chapter 6
Ic!s f| r !hc Pe!0em re4c.
prep code test code reaI code reaI code
public class DotCom {
int[] locationCells;
int numOfHits = 0;

public void setLocationCells(int[] locs) {
locationCells = locs;
}
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = miss;
for (int cell : locationCells) {
if (guess == cell) {
result = hit;
numOfHits++;

break;
}
} // out of the loop
if (numOfHits == locationCells.length) {
result = kill;
}
System.out.println(result);
return result;
} // close method
} // close class
Pemember, fhis is how fhe buggy version Iooks:
w--- l .|| ---l ---- w-
:---l- -.: --:: .: . l,
-l--l :-:- --l-- l.l :-||
. .|--.] --- l
the buggy DotCom code
w-'- ---.-- l- :|.:: l-lc-- --- |-:l-. -
-|-l-lc--`, -- l- --- ..-:- --:--, -l l:
: l- :.-- :-- ]-- :.- - l- |.:l :.l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 139
import java.util.ArrayList;
public class DotCom {
private ArrayList<String> locationCells;
// private int numOfHits;
// don't need that now
public void setLocationCells(ArrayList<String> loc) {
locationCells = loc;
}


public String checkYourself(String userInput) {

String result = miss;
int index = locationCells.indexOf(userInput);

if (index >= 0) {

locationCells.remove(index);


if (locationCells.isEmpty()) {
result = kill;
} else {
result = hit;
} // close if

} // close outer if

return result;
} // close method
} // close class
hcw zn4 |mprevc4 Pe!0em r|zss
prep code test code reaI code reaI code
c.-- l- l-- .--.] l- .- A--.]|:l l.l -|: l--:
|---- l: |-- -- ---. -- l.| .--l l .l l- -- - l- :.l--
|- --l l- -:-- --:: : - l-
A--.]|:l, ] .:- -- l: --
| l': --l - l- |:l, l-- --6|`
--l---: . ~|
| -- : --.l-- l.- -- --.| l-
----, l- -:-- --:: : --l-|] - l-
|:l, :- ----- l
| l- |:l : --l], l:
-.: l- ||- |--'
N
--
.- -
--- .---
--l -.-
-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
140 chapter 6
making the DotComBust
Ic!s |e||4 !hc KII ]zmc:
8|nk z Pe! 0em
Wc`vc lccn woiIing on ihc simlc` vcision, lui now
lci`s luilu ihc ical onc. Insicau ol a singlc iow, wc`ll
usc a giiu. Anu insicau ol onc DoiCom, wc`ll usc
ihicc.
Goal: SinI all ol ihc comuici`s Doi Coms in ihc
lcwcsi numlci ol gucsscs. You`ic givcn a iaiing lcvcl
lascu on how wcll you ciloim.
Sctup: Whcn ihc gamc iogiam is launchcu, ihc
comuici laccs ihicc Doi Coms, ianuomly, on ihc
virtual 7 x 7 grid. Whcn ihai`s comlcic, ihc gamc
asIs loi youi hisi gucss.
How you play: Wc havcn`i lcaincu io luilu a GUI
yci, so ihis vcision woiIs ai ihc commanu-linc. Thc
comuici will iomi you io cnici a gucss a ccll),
which you`ll iyc ai ihc commanu-linc as AS", C",
cic.). In icsonsc io youi gucss, you`ll scc a icsuli ai
ihc commanu-linc, ciihci hii", miss", oi You sunI
Pcis.com" oi whaicvci ihc lucIy Doi Com ol ihc uay
is). Whcn you`vc scni all ihicc Doi Coms io ihai lig
404 in ihc sIy, ihc gamc cnus ly iiniing oui youi
iaiing.
7 x 7 -
File Edit Window Help Sell
%java DotComBust
Enter a guess A3
miss
Enter a guess B2
miss
Enter a guess C4
miss
Enter a guess D2
hit
Enter a guess D3
hit
Enter a guess D4
Ouch! You sunk Pets.com : (
kill
Enter a guess B4
miss
Enter a guess G3
hit
Enter a guess G4
hit
Enter a guess G5
Ouch! You sunk AskMe.com : (
kill
Enter a guess A7
miss
Enter a guess B7
A

C
D

F
C
0 1 2 3 4 5 6
AskMe.com
Pets.com
C
o
2
.
c
o
m
:l.-l: .l ----, |- ).. .--.]:
pzr! ef z ]zmc |n!crzr!|en
You're going to build the
Sink a Dot Com game, with
a 7 x 7 grid and three
Dot Coms. Each Dot Com
takes up three cells.
-.: -
: . :-||'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 141
Whz! ncc4s !e rhzn]c!
Wc havc ihicc classcs ihai nccu io changc: ihc
DoiCom class which is now callcu DoiCom insicau ol
SimlcDoiCom), ihc gamc class DoiComBusi) anu ihc
gamc hclci class which wc won`i woiiy aloui now).
DotCom class
Add a nome variablc
io holu ihc namc ol ihc DoiCom
Pcis.com", Go2.com", cic.) so cach Doi-
Com can iini iis namc whcn ii`s Iillcu scc
ihc ouiui sciccn on ihc oosiic agc).
DotComBust class continued...
Put thc DotComs on a grid rathcr than
just a singlc row, and do it Ior all thrcc
DotComs.
This sic is now way moic comlcx ihan
lcloic, il wc`ic going io lacc ihc DoiComs
ianuomly. Sincc wc`ic noi hcic io mcss
wiih ihc maih, wc ui ihc algoiiihm loi
giving ihc DoiComs a locaiion inio ihc
GamcHclci Rcauy-laIc) class.
Chcck cach uscr gucss with oII three
DotComs, instcad oI just onc.
Kccp playing thc gamc i.c accciing
usci gucsscs anu chccIing ihcm wiih ihc
icmaining DoiComs) untiI there ore no more
Iive DotComs.
Gct out oI main. Wc Ici ihc simlc onc in
main |usi io... Icc ii simlc. Bui ihai`s noi
whai wc wani loi ihc gamc.
0ot6omust
The game c|ass.
Va|es 0olCors,
els user |rpul,
p|ays url|| a|| 0ol-
Cors are dead
0ot6om
The actua|
0ot6om objects.
0olCors |roW l|e|r
rare, |ocal|or, ard
|oW lo c|ec| a user
uess lor a ralc|.
3 Classes:
Camehe|per
The he|per c|ass
(Ready-8a|e).
ll |roWs |oW lo
accepl user cor-
rard-||re |rpul,
ard ra|e 0olCor
|ocal|ors.
5 Ob]ects:
DofCom8usf
DofCom
DofCom
DofCom
0omeHeIper
u
s
e
s

f
o
r

p
Io
y
e
r
in
p
u
f ond fo moke D
o
f
C
o
m
Io
c
o
f
i
o
n
s

c
r
e
o
fes ond pIoys wif
h
DotComBust class {the game}
Crcatc three DotComs instcad oI onc.
Givc cach oI thc thrcc DotComs a nome.
Call a sciici mcihou on cach DoiCom
insiancc, so ihai ihc DoiCom can assign ihc
namc io iis namc insiancc vaiiallc.
PIus 4
ArroyLisfs: I for
fhe DofCom8usf
ond I for eoch
of fhe 3 DofCom
objecfs.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
142 chapter 6
Whe 4ecs whz! |n !hc Pe!0emBes! ]zmc
|zn4 whcnI

detaiIed structure of the game


0ot6omust
The game
c|ass.
DofCom8usf
objecf
insfonfiofes
The moin() mefhod
in fhe DofCom8usf
cIoss insfonfiofes fhe
DofCom8usf objecf fhof
does oII fhe gome sfuff.

insfonfiofes
The DofCom8usf (gome)
objecf insfonfiofes on
insfonce of 0omeHeIper,
fhe objecf fhof wiII heIp
fhe gome do ifs work.
leljer
DofCom8usf
objecf
0omeHeIper
objecf

ArroyLisf objecf (fo


hoId DofCom objecfs)
The DofCom8usf objecf
insfonfiofes on ArroyLisf
fhof wiII hoId fhe 3 DofCom
objecfs.
leljer
ie|Cem:|i:|
DofCom8usf
objecf
0omeHeIper
objecf
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
get to know the Java API
you are here 143

ArroyLisf objecf fo
hoId DofCom objecfs
The DofCom8usf objecf
creofes fhree DofCom
objecfs (ond pufs fhem in
fhe ArroyLisf)
leljer
ie|Cem:|i:|
DofCom8usf
objecf
0omeHeIper
objecf
ie|Cem
J
ie|Cem
I
ie|Cem
Z
tell:
tell:
tell:
DofCom
objecfs

ArroyLisf objecf fo
hoId DofCom objecfs
The DofCom8usf objecf osks fhe
heIper objecf for o Iocofion for o
DofCom (does fhis 3 fimes, one for
eoch DofCom)
leljer
ie|Cem:|i:|
DofCom8usf
objecf
0omeHeIper
objecf
m
o
k
e
Io
cofion
ie|Cem
J
ie|Cem
I
ie|Cem
Z
tell:
tell:
tell:
DofCom
objecfs
h
e
re
if is
The DofCom8usf objecf gives eoch of fhe Dof-
Com objecfs o Iocofion (which fhe DofCom8usf
gof from fhe heIper objecf) Iike "AZ", "8Z",
efc. Eoch DofCom objecf pufs his own fhree
Iocofion ceIIs in on ArroyLisf
ArroyLisf objecf
(fo hoId DofCom
ceII Iocofions)
tell
J
tell
I
tell
Z
ArroyLisf
objecf
ArroyLisf
objecf
tell
J
tell
I
tell
Z
tell
J
tell
I
tell
Z

ArroyLisf objecf fo
hoId DofCom objecfs
The DofCom8usf objecf osks fhe heIper
objecf for o user guess (fhe heIper
prompfs fhe user ond gefs inpuf from
fhe commond-Iine)
leljer
ie|Cem:|i:|
DofCom8usf
objecf
0omeHeIper
objecf
g
e
f
u
s
er guess
ie|Cem
J
ie|Cem
I
ie|Cem
Z
tell:
tell:
tell:
DofCom
objecfs
c
h
e
c
k

f
h
is
g
u
ess
h
e
re
if is
ArroyLisf objecf
(fo hoId DofCom
ceII Iocofions)
tell
J
tell
I
tell
Z
ArroyLisf
objecf
ArroyLisf
objecf
tell
J
tell
I
tell
Z
tell
J
tell
I
tell
Z
"h
if"
The DofCom8usf objecf Ioops fhrough fhe Iisf
of DofComs, ond osks eoch one fo check fhe user
guess for o mofch. The DofCom checks ifs Iocofions
ArroyLisf ond refurns o resuIf ("hif", "miss", efc.)
And so fhe gome confinues... gef-
fing user inpuf, osking eoch DofCom
fo check for o mofch, ond confinuing
unfiI oII DofComs ore deod
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
144 chapter 6
0arele|per |e|per
ArrayL|sl dolCorsL|sl
|rl rur0l0uesses
selup0are()
slarlP|ay|r()
c|ec|user0uess()
l|r|s|0are()
prep code test code reaI code prep code
DECLARE aoo |ostaot|ato t|o ComeHe|per |ostaoco va|ab|o, oaoo he|per.
DECLARE aoo |ostaot|ato ao Arro,L|st to |o|o t|o ||st o |otCos (|o|t|a|| t|oo) Ca|| |t
dotComsL|st.
DECLARE ao |ot va|ab|o to |o|o t|o oobo o oso goossos (so t|at .o cao g|vo t|o oso a
scoo at t|o ooo o t|o gao). |ao |t num0fCuesses aoo sot |t to 0.
DECLARE a setUpCome(j ot|oo to coato aoo |o|t|a||zo t|o |otCo ob,octs .|t| oaos
aoo |ocat|oos. ||sp|a b|o |ostoct|oos to t|o oso.
DECLARE a stortP|o,|ng(j ot|oo t|at as's t|o p|ao o goossos aoo ca||s t|o
c|oc'|soCooss() ot|oo oot|| a|| t|o |otCo ob,octs ao oovoo o p|a.
DECLARE a checkUserCuess(j ot|oo t|at |oops t|oog| a|| oa|o|og |otCo ob,octs aoo
ca||s oac| |otCo ob,oct's c|oc'Yooso|() ot|oo.
DECLARE a f n|shCome(j ot|oo t|at p|ots a ossago aboot t|o oso's pooaoco, basoo
oo |o. ao goossos |t too' to s|o' a|| o t|o |otCo ob,octs.
MEYHOD. voId setUpGome()
// o'e tee ctCc c!,ects o! oe te
CREAYE t|oo |otCo ob,octs.
5EY a oao o oac| |otCo.
ADD t|o |otCos to t|o dotComsL|st ( t|o /a||st).
REPEAY .|t| oac| o t|o |otCo ob,octs |o t|o dotComsL|st aa
CALL t|o p|oceuotCom(j ot|oo oo t|o |o|po ob,oct, to got a aooo|-so|octoo
|ocat|oo o t||s |otCo (t|oo co||s, vot|ca|| o |o|zoota|| a||gooo, oo a g|o).
5EY t|o |ocat|oo o oac| |otCo basoo oo t|o oso|t o t|o p|oceuotCom(j ca||.
||| ||||/T
||| ||TC|

Thc DoiComBusi class has ihicc main |ols: sci u ihc gamc, lay ihc gamc
uniil ihc DoiComs aic ucau, anu cnu ihc gamc. Alihough wc coulu ma
ihosc ihicc |ols uiiccily inio ihicc mcihous, wc slii ihc miuulc |ol lay ihc
gamc) inio mcihous, io Icc ihc gianulaiiiy smallci. Smallci mcihous
mcaning smallci chunIs ol lunciionaliiy) hcl us icsi, uclug, anu mouily
ihc couc moic casily.
|rcp re4c fer !hc rcz| Pe!0emBes! r|zss
Variable
Declarations
Method
Declarations
Method
mplementations
the DotComBust cIass (the game)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 145
MEYHOD. voId checkUserGuess(StrIng userGuess)
// (! c.t , tees o t (o! ''') c o, ctCc
INCREMENY t|o oobo o oso goossos |o t|o num0fCuesses va|ab|o
5EY t|o |oca| resu|t va|ab|o (a Str|ng) to '|ss', asso|og t|at t|o oso's gooss .||| bo a |ss.
REPEAY .|t| oac| o t|o |otCb,octs |o t|o dotComsL|st aa
EVALUAYE t|o oso's gooss b ca|||og t|o |otCo ob,oct's checkourse|f(j ot|oo
5EY t|o oso|t va|ab|o to '||t' o ''|||' | appop|ato
IF t|o oso|t |s ''|||', REMOVE t|o |otCo o t|o dotComsL|st
||| ||||/T
DI5PLAY t|o resu|t va|oo to t|o oso
||| ||TC|
MEYHOD. voId nIshGome()
DI5PLAY a gooo|c 'gao ovo' ossago, t|oo.
IF oobo o oso goossos |s sa||,
DI5PLAY a coogato|at|oos ossago
EL5E
DI5PLAY ao |oso|t|og ooo
||| ||
||| ||TC|
prep code test code reaI code prep code
MEYHOD. voId stortPIoyIng()
REPEAY .|||o ao |otCos o|st
GEY oso |opot b ca|||og t|o |o|po getUserlnput(j ot|oo
EVALUAYE t|o oso's gooss b checkUserCuess(j ot|oo
||| ||||/T
||| ||TC|
Mc!he4 |mp|cmcn!z!|ens ren!|nec4:
+,-+ :+ ,-+:.|
How should we go from prep code to the
final codeI Pirst we start with test code, and
then test and build up our methods bit by
bit. we won't keep showing you test code
in this book, so now it's up to you to think
about what you'd need to know to test these
methods. And which method do you test
and write firstI See if you can work out some
prep code for a set of tests. Prep code or
even bullet points are good enough for this
exercise, but if you want to try to write the
test code (in 1ava), knock yourself out.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
146 chapter 6
import java.util.*;
public class DotComBust {
private GameHelper helper = new GameHelper();
private ArrayList<DotCom> dotComsList = new ArrayList<DotCom>();
private int numOfGuesses = 0;
private void setUpGame() {
// h rst make some dot coms and give them locations
DotCom one = new DotCom();
one.setName(Pets.com);
DotCom two = new DotCom();
two.setName(eToys.com);
DotCom three = new DotCom();
three.setName(Go2.com);
dotComsList.add(one);
dotComsList.add(two);
dotComsList.add(three);
System.out.println(Your goal is to sink three dot coms.);
System.out.println(Pets.com, eToys.com, Go2.com);
System.out.println(Try to sink them all in the fewest number of guesses);

for (DotCom dotComToSet : dotComsList) {
ArrayList<String> newLocation = helper.placeDotCom(3);
dotComToSet.setLocationCells(newLocation);
} // close for loop
} // close setUpGame method
private void startPlaying() {
while(!dotComsList.isEmpty()) {
String userGuess = helper.getUserInput(Enter a guess);
checkUserGuess(userGuess);
} // close while
h nishGame();
} // close startPlaying method
prep code test code reaI code reaI code
1
2
3
4
5
6

10
9
.: |-- .: l- l-lc--
|:l : N61 --l]
-l -:-- --l
:.|| --- --- :-:c:--6--:: --l-
:.|| --- --- -:6.-- --l-
--l --
-:l--:l--: --
-:--
-:|.-- .- -l.|--
l- .-.|-: --'|| ---
---.l -l -.: l-lc-- - l- |:l
-.- l--- l-lc-- --:l:, - '--
-.--:, .- :l: '-- - l- A--.]|:l
.: l- -|-- -- . l-lc-- |-:.l--
:.|| l- :-ll-- --l- -- l: l-lc--
l- - l l- |-:.l-- ]-- -:l -l
--- l- -|--
+,-+ :+ ,-+:.|
Annotate the code
yourselfl
Match the
annotations at the
bottom of each page
with the numbers
in the code. Write
the number in the
slot in front of the
corresponding
annotation.
You'll use each
annotation ]ust once,
and you'll need all of
the annotations.
the DotComBust code (the game)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 147
private void checkUserGuess(String userGuess) {

numOfGuesses++;

String result = miss;
for (DotCom dotComToTest : dotComsList) {
result = dotComToTest.checkYourself(userGuess);
if (result.equals(hit)) {
break;
}
if (result.equals(kill)) {
dotComsList.remove(dotComToTest);
break;
}
} // close for
System.out.println(result);
} // close method


private void nishGame() {
System.out.println(All Dot Coms are dead! Your stock is now worthless.);
if (numOfGuesses <= 18) {
System.out.println(It only took you + numOfGuesses + guesses.);
System.out.println( You got out before your options sank.);
} else {
System.out.println(Took you long enough. + numOfGuesses + guesses.);
System.out.println(Fish are dancing with your options.);
}
} // close method

public static void main (String[] args) {
DotComBust game = new DotComBust();
game.setUpGame();
game.startPlaying();
} // close method
}
-:-----l l- ----- - --::-: l- -:-- .: -.-
.::--- l': . '-::', --|-:: l-| -l---:-
---.l -l .|| l-lc--: - l- |:l
.: l- l-lc-- l- :-: l- -:-- --::,
|--- -- . l |-- ||`
-l --l - l- |--
-.-|], -- --l - l-:l-
l- -l--:
l: -]': -., :- l.- - --l - l-
l-lc--: |:l l-- -l --l - l- |--
--l l-
--:-|l --
l- -:--
--l . --::.- l-||- l-
-:-- -- - - l- .--
l-|| l- .-- --:l l- :l.-l l- -.-
.-- |.] |-- |--: .:- -- -:--
--l .- :-:- l- --::`
prep code test code reaI code reaI code
12
13
14
15
16
17
18
19
20
21
l-|| l- .-- --:l
l- :-l - l- .--
:--.l- l- .-- --:l
11
Whatever you do,
DON'T turn the
pagel
Not until you've
hnished this
exercise.
Our version is on
the next page.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
148 chapter 6
import java.util.*;
public class DotComBust {
private GameHelper helper = new GameHelper();
private ArrayList<DotCom> dotComsList = new ArrayList<DotCom>();
private int numOfGuesses = 0;
private void setUpGame() {
// h rst make some dot coms and give them locations
DotCom one = new DotCom();
one.setName(Pets.com);
DotCom two = new DotCom();
two.setName(eToys.com);
DotCom three = new DotCom();
three.setName(Go2.com);
dotComsList.add(one);
dotComsList.add(two);
dotComsList.add(three);
System.out.println(Your goal is to sink three dot coms.);
System.out.println(Pets.com, eToys.com, Go2.com);
System.out.println(Try to sink them all in the fewest number of guesses);

for (DotCom dotComToSet : dotComsList) {

ArrayList<String> newLocation = helper.placeDotCom(3);

dotComToSet.setLocationCells(newLocation);

} // close for loop
} // close setUpgame method
private void startPlaying() {

while(!dotComsList.isEmpty()) {

String userGuess = helper.getUserInput(Enter a guess);
checkUserGuess(userGuess);

} // close while
h nishGame();
} // close startPlaying method
prep code test code reaI code reaI code
l-:|.-- .- -l.|--
l- .-.|-: --'|| ---
M.- l--- l-lc-- --:l:,
- '-- -.--:, .- :l: '--
- l- A--.]|:l
|--l --
-:l--:l--: -- -:--
A: l- -|-- -- .
l-lc-- |-:.l-- |.-
A--.]|:l - l--:`
c.|| l- :-ll-- --l- -- l: l-lc-- l- - l l- |-:.l-- ]--
-:l -l --- l- -|--
--.l -l -.: l-lc-- - l- |:l
A: |-- .: l- l-lc-- |:l : N61 --l] |l- ' --.-: N61, l':
l- :.-- .: |-lc--:|:l:!-l]|` == .|:-`
6-l -:-- --l
c.|| --- --- :-:c:--6--:: --l-
c.|| --- --- -:6.-- --l-
the DotComBust code (the game)
M.- .- A--.]|:l -
l-lc-- --:l: |- -l--
---:, . |:l l.l -|| -|
6N|/ l-lc-- --:l:,
-:l .: l-lc--|1 ---|
--.- .- .--.] - l-lc--
--:l:`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 149
private void checkUserGuess(String userGuess) {

numOfGuesses++;

String result = miss;
for (DotCom dotComToTest : dotComsList) {
result = dotComToTest.checkYourself(userGuess);

if (result.equals(hit)) {

break;
}
if (result.equals(kill)) {

dotComsList.remove(dotComToTest);
break;
}
} // close for
System.out.println(result);
} // close method


private void nishGame() {
System.out.println(All Dot Coms are dead! Your stock is now worthless.);
if (numOfGuesses <= 18) {
System.out.println(It only took you + numOfGuesses + guesses.);
System.out.println( You got out before your options sank.);
} else {
System.out.println(Took you long enough. + numOfGuesses + guesses.);
System.out.println(Fish are dancing with your options);
}
} // close method


public static void main (String[] args) {
DotComBust game = new DotComBust();
game.setUpGame();
game.startPlaying();
} // close method
}
-:-----l l- ----- - --::-: l- -:-- .: -.-
.::--- l': . '-::', --|-:: l-| -l---:-
---.l -l .|| l-lc--: - l- |:l
.: l- l-lc-- l- :-: l- -:--
--::, |--- -- . l |-- ||`
-l --l - l- |-- -.-|], -- --l
- l-:l- l- -l--:
l: -]': -., :- l.- - --l - l-
l-lc--: |:l l-- -l --l - l- |--
--l l- --:-|l -- l- -:--
--l . --::.- l-||- l-
-:-- -- - - l- .--
:--.l- l- .-- --:l
l-|| l- .-- --:l l- :-l - l- .--
l-|| l- .-- --:l l- :l.-l l- -.-
.-- |.] |-- |--: .:- -- -:--
--l .- :-:- l- --::`
prep code test code reaI code reaI code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
150 chapter 6
import java.util.*;
public class DotCom {
private ArrayList<String> locationCells;
private String name;
public void setLocationCells(ArrayList<String> loc) {
locationCells = loc;
}
public void setName(String n) {
name = n;
}
public String checkYourself(String userInput) {
String result = miss;
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);

if (locationCells.isEmpty()) {
result = kill;
System.out.println(Ouch! You sunk + name + : ( );
} else {
result = hit;
} // close if
} // close if
return result;
} // close method
} // close class
l-lc--': -:l.-:- .-.|-:
~ .- A--.]|:l - :-|| |-:.l--:
~ l- l-lc--': -.--
A :-ll-- --l- l.l -.l-:
l- l-lc--': |-:.l--
|.--- |-:.l-- --- ]
l- 6.--+-|-- |.:-l-lc--| `
--l-`
/--- .:: :-ll-- --l-
1- A--.]|:l --6| ` --l- -
.:l--' | l- -:-- --:: : --- - l-
--l--: - l- A--.]|:l, --6| `
-|| --l--- l: A--.]|:l |-:.l-- |
--l, --6| ` -|| --l--- ~|
1-|| l- -:-- --- . l-lc-- .: --- :--
c:- l- :!-l]| ` --l- l- :-- .||
- l- |-:.l--: .- --- --::-
c:- A--.]|:l': -----| ` --l- l- -|-l- .- --l-]
Ihc f|nz| vcrs|en ef !hc
Pe!0em r|zss
-l--- '-::' -- 'l' -- '||'
prep code test code reaI code reaI code
the DotCom code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 151
8epcr |ewcrfe| Bee|czn Irprcss|ens
So far, when we've used boolean expressions for our loops or
tests, they've been pretty simple. we will be using more
powerful boolean expressions in some of the Peady-8ake code
you're about to see, and even though we know you wouldn't
peek, we thought this would be a good time to discuss how to
energize your expressions.
And' and Or' Operators { &&, || }
Let's say you're writing a chooseCamera( ) method, with lots of rules
about which camera to select. Maybe you can choose cameras
ranging from $50 to $l000, but in some cases you want to limit the
price range more precisely. ou want to say something like:
'|f the price tone is between $300 nnJ $400 then choose X.'
if {price >= 300 && price < 400} [
camera = "X",
]
Let's say that of the ten camera brands available, you have some
logic that applies to only a lew of the list:
if {brand.eguals{"A"} [[ brand.eguals{"B"} } [
// do stuff for brand A brand B
]
8oolean expressions can get really big and complicated:
if {{zoomType.eguals{"optical"} &&
{zoomDegree >= 3 && zoomDegree <= 8}} [[
{zoomType.eguals{"digital"} &&
{zoomDegree >= 5 && zoomDegree <= 12}}} [
// do appropriate zoom stuff
]
|f you want to get teolly technical, you might wonder about the
teceJence of these operators. |nstead of becoming an expert
in the arcane world of precedence, we recommend that you use
nrenrheses to make your code clear.
Not equals { l= and l }
Let's say that you have a logic like, "of the ten available
camera models, a certain thing is ttue lot oll out one. "
if {model != 2000} [
// do non-model 2000 stuff
]
or for comparing ob|ects like strings...
if {!brand.eguals{"X"}} [
// do non-brand X stuff
]
8hort Circuit Operators { && , || }
The operators we've looked at so far, && and ||, are
known as sherr circuir operators. |n the case of &&,
the expression will be true only if ooth sides of the &&
are true. So if the 1vM sees that the left side of a &&
expression is false, it stops right there! Doesn't even
bother to look at the right side.
Similarly, with ||, the expression will be true if e|thet side is
true, so if the 1vM sees that the left side is true, it declares
the entire statement to be true and doesn't bother to
check the right side.
why is this greatI Let's say that you have a reference
variable and you're not sure whether it's been assigned
to an ob|ect. |f you try to call a method using this null
reference variable (i.e. no ob|ect has been assigned), you'll
get a NullPointerLxception. So, try this:
if {refVar != null &&
refVar.isValidType{} } [
// do 'got a valid type' stuff
]
Non 8hort Circuit Operators { & , | }
when used in boolean expressions, the & and | operators
act like their && and || counterparts, except that
they force the 1vM to olwoys check ooth sides of the
expression. Typically, & and | are used in another context,
for manipulating bits.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
152 chapter 6
import java.io.*;
import java.util.*;
public class {
private static h nal String alphabet = abcdefg;
private int gridLength = 7;
private int gridSize = 49;
private int [] grid = new int[gridSize];
private int comCount = 0;
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + );
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0 ) return null;
} catch (IOException e) {
System.out.println(IOException: + e);
}
return inputLine.toLowerCase();
}

public ArrayList<String> placeDotCom(int comSize) {
ArrayList<String> alphaCells = new ArrayList<String>();
String [] alphacoords = new String [comSize]; // holds `f6' type coords
String temp = null; // temporary String for concat
int [] coords = new int[comSize]; // current candidate coords
int attempts = 0; // current attempts counter
boolean success = false; // H ag = found a good location ?
int location = 0; // current starting location

comCount++; // nth dot com to place
int incr = 1; // set horizontal increment
if ((comCount % 2) == 1) { // if odd dot com (place vertically)
incr = gridLength; // set vertical increment
}
while ( !success & attempts++ < 200 ) { // main search loop (32)
location = (int) (Math.random() * gridSize); // get random starting point
//System.out.print(` try ` + location);
int x = 0; // nth position in dotcom to place
success = true; // assume success
while (success && x < comSize) { // look for adjacent unused spots
if (grid[location] == 0) { // if not already used
0zsJj-hskz
0aJz
This is fhe heIper cIoss for fhe gome. 8esides fhe user inpuf mefhod
(fhof prompfs fhe user ond reods inpuf from fhe commond-Iine), fhe
heIper's 8ig Service is fo creofe fhe ceII Iocofions for fhe DofComs.
If we were you, we'd jusf bock owoy sIowIy from fhis code, excepf
fo fype if in ond compiIe if. We fried fo keep if foirIy smoII fo you
wouIdn'f hove fo fype so much, buf fhof meons if isn'f fhe mosf
reodobIe code. And remember, you won'f be obIe fo compiIe fhe
DofCom8usf gome cIoss unfiI you hove fhis cIoss.
N-l- |-- -l-. :--l, ]-- -l
l-] '--~:-----l-' l-
]:l----l--l||-`': - l-
|.:-l-lc--| ` --l-, -:l
l- -.l: l ---' 1-:- --l
:l.l----l: -|| |-l ]-- :-.l'
] - ]-- l- |-:.l-- - l-
l-lc--:, -l l -|| -| ]-- l-:l l
Ready-bake: GameHeIper
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
get to know the Java API
you are here 153
coords[x++] = location; // save location
location += incr; // try `next' adjacent
if (location >= gridSize){ // out of bounds - `bottom'
success = false; // failure
}
if (x>0 && (location % gridLength == 0)) { // out of bounds - right edge
success = false; // failure
}
} else { // found already used location
// System.out.print(` used ` + location);
success = false; // failure
}
}
} // end while

int x = 0; // turn location into alpha coords
int row = 0;
int column = 0;
// System.out.println(`\n");
while (x < comSize) {
grid[coords[x]] = 1; // mark master grid pts. as `used'
row = (int) (coords[x] / gridLength); // get row value
column = coords[x] % gridLength; // get numeric column value
temp = String.valueOf(alphabet.charAt(column)); // convert to alpha

alphaCells.add(temp.concat(Integer.toString(row)));
x++;
// System.out.print(` coord `+x+" = ` + alphaCells.get(x-1));
}

// System.out.println(`\n");

return alphaCells;
}
}
0zsJj-hskz
0aJz
0zmcHc|pcr r|zss re4c ren!|nec4...
1: : l- :l.l----l l.l
l-||: ]-- -.:l|] ---- l-
l-lc-- : |-:.l-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
154 chapter 6
API packages
0s|n] !hc I||rzry |!hc 1zvz ||I
n the Java AP, classes
are grouped into packages.
To use a class in the AP, you
have to know which package
the class is in.
Evciy class in ihc ]ava liliaiy lclongs io a acIagc.
Thc acIagc has a namc, liIc javax.swing a
acIagc ihai holus somc ol ihc Swing GUI classcs
you`ll lcain aloui soon). AiiayIisi is in ihc acIagc
callcu java.utiI, which suiiisc suiiisc, holus a
ilc ol u.I., classcs. You`ll lcain a loi moic aloui
acIagcs in chaici 16, incluuing how io ui youi
owr classcs inio youi owr acIagcs. Ioi now ihough,
wc`ic |usi looIing io ue somc ol ihc classcs ihai comc
wiih ]ava.
Using a class liom ihc API, in youi own couc, is
simlc. You |usi iicai ihc class as ihough you wioic
ii youiscll... as ihough you comilcu ii, anu ihcic ii
siis, waiiing loi you io usc ii. Wiih onc lig uillcicncc:
somcwhcic in youi couc you havc io inuicaic ihc uII
namc ol ihc liliaiy class you wani io usc, anu ihai
mcans acIagc namc + class namc.
Evcn il you uiun`i Inow ii, you`ve oIreody been using
cIosses [rom o pochoge. Sysicm Sysicm.oui.iiniln),
Siiing, anu Maih Maih.ianuom)), all lclong io ihc
java.Iang acIagc.
You mauc ii all ihc way ihiough ihc DoiComBusi gamc,
ihanIs io ihc hcl ol AiiayIisi. Anu now, as iomiscu,
ii`s iimc io lcain how io lool aiounu in ihc ]ava liliaiy.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 155
import java.util.ArrayList;
public class MyClass {... }
You have to know the full name*
of the class you want to use in
your code.
AiiayIisi is noi ihc namc ol AiiayIisi, |usi as Kaihy`
isn`i a lull namc unlcss ii`s liIc Mauonna oi Chci, lui wc
won`i go ihcic). Thc lull namc ol AiiayIisi is aciually:
java.util.ArrayList
You have to tell Java which ArrayList you
want to use. You have two options:
MPORT
TYPE
java.util.ArrayList<Dog> list = new java.util.ArrayList<Dog>();
Type the full name everywhere in your code. Each time
you use it. you use it.
OR
Put an import statement at the top of your source code fle:

When you declare and/or instantiate it:


public void go(java.util.ArrayList<Dog> list) { }
When you use it as an argument type:
public java.util.ArrayList<Dog> foo() {...}

When you use it as a return type:
.:.- -.--
:|.:: -.--
(-,- a,- |
oa|| qa--(:|-

Why does there have to


be a fuII name! Is that the onIy
purpose of a package!

Packages are important


for three main reasons. Pirst, they
help the overall organization of a
pro|ect or library. Pather than |ust
having one horrendously large
pile of classes, they're all grouped
into packages for specific kinds
of functionality (like GU|, or data
structures, or database stuff, etc.)
Second, packages give you a name-
scoping, to help prevent collisions
if you and l2 other programmers
in your company all decide to
make a class with the same name.
|f you have a class named Set and
someone else (including the 1ava
AP|) has a class named Set, you
need some way to tell the 1vM
Set class you're trying to use.
Third, packages provide a level of
security, because you can restrict
the code you write so that only
other classes in the same package
can access it. ou'll learn all about
that in chapter l6.

Dk, back to the name


coIIision thing. How does a fuII
name reaIIy heIp! What's to
prevent two peopIe from giving a
cIass the same package name!

1ava has a naming convention


that usually prevents this from
happening, as long as developers
adhere to it. we'll get into that in
more detail in chapter l6.
*Unless the class is in the java.lang package.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
156 chapter 6
|n the first and second versions of 1ava (l.02
and l.l), all classes that shipped with 1ava (in
other words, the standard library) were in packages
that began with jnvn. There was always jnvn.lnng, of course
the one you don't have to import. And there was jnvn.ner,
jnvn.ie, jnvn.uril (although there was no such thing as ArrayList
way back then), and a few others, including the jnvn.nwr
package that held GU|-related classes.
Looming on the horizon, though, were other packages not
included in the standard library. These classes were known as
exrensiens, and came in two main flavors: , and
standard. Standard extensions were those that Sun considered
official, as opposed to experimental, early access, or beta
packages that might or might not ever see the light of day.
Standard extensions, by convention, all began with an 'x'
appended to the regular jnvn package starter. The mother of all
standard extensions was the Swing library. |t included several
packages, all of which began with jnvnx.swing.
8ut standard extensions can get promoted to first-class, ships-
with-1ava, standard-out-of-the-box library packages. And that's
what happened to Swing, beginning with version l.2 (which
eventually became the first version dubbed '1ava 2').
"Cool, everyone thought (including us). "Now everyone who has
1ava will have the Swing classes, and we won't have to figure
out how to get those classes installed with our end-users.
Trouble was lurking beneath the surface, however, because
when packages get promoted, well of COUPSL they have to
start with jnvn, not jnvnx. Lveryone KNOwS that packages in
the standard library don't have that "x, and that only extensions
have the "x. So, |ust (and we mean |ust) before version l.2
went final, Sun changed the package names and deleted the
"x (among other changes). 8ooks were printed and in stores
featuring Swing code with the new names. Naming conventions
were intact. All was right with the 1ava world.
Lxcept the 20,000 or so screaming developers who realized
that with that simple name change came disaster! All of their
Swing-using code had to be changed! The horror! Think of all
those import statements that started with jnvnx...
And in the final hour, desperate, as their hopes grew thin, the
developers convinced Sun to "screw the convention, save our
code. The rest is history. So when you see a package in the
library that begins with jnvnx, you know it started life as an
extension, and then got a promotion.
Where'd that x' come from?
{or, what does it mean when
a package starts with ]avax?}
ArrayL|st |s a c|ass |r l|e Java APl.
To pul sorel||r |rlo ar ArrayL|sl, use add(}.
To rerove sorel||r lror ar ArrayL|sl use
remove(}.
To l|rd oul W|ere sorel||r |s (ard |l |l |s) |r ar
ArrayL|sl, use |ndex0f(}.
To l|rd oul |l ar ArrayL|sl |s erply, use
|sEmpty(}.
To el l|e s|ze (ruroer ol e|ererls) |r ar
ArrayL|sl, use l|e s|ze(} .
To el l|e |ength (ruroer ol e|ererls) |r a
reu|ar o|d array, rereroer, you use l|e |erl|
var|ab|e.
Ar ArrayL|sl res|zes dynam|ca||y lo W|al-
ever s|ze |s reeded. ll roWs W|er oojecls
are added, ard |l shr|nks W|er oojecls are
reroved.
You dec|are l|e lype ol l|e array us|r a type
parameter, W||c| |s a lype rare |r ar|e
orac|els. Exarp|e: ArrayL|sl<8ullor> rears
l|e ArrayL|sl W||| oe ao|e lo |o|d or|y oojecls ol
lype 8ullor (or suoc|asses ol 8ullor as you'||
|earr |r l|e rexl coup|e ol c|aplers).
A|l|ou| ar ArrayL|sl |o|ds oojecls ard rol
pr|r|l|ves, l|e corp||er W||| auloral|ca||y 'Wrap
(ard 'urWrap W|er you la|e |l oul) a pr|r|-
l|ve |rlo ar 0ojecl, ard p|ace l|al oojecl |r l|e
ArrayL|sl |rslead ol l|e pr|r|l|ve. (Vore or l||s
lealure |aler |r l|e ooo|.)
C|asses are rouped |rlo pac|aes.
A c|ass |as a lu|| rare, W||c| |s a coro|ra-
l|or ol l|e pac|ae rare ard l|e c|ass rare.
C|ass ArrayL|sl |s rea||y java.ul||.ArrayL|sl.
To use a c|ass |r a pac|ae ol|er l|ar java.
|ar, you rusl le|| Java l|e lu|| rare ol l|e
c|ass.
You use e|l|er ar |rporl slalererl al l|e lop ol
your source code, or you car lype l|e lu|| rare
every p|ace you use l|e c|ass |r your code.
8ll P0lk5
when arrays aren't enough
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 157

koses ote teJ,


oles ote t|e,
|l you Jont |mott
youll just hove to tye
You must teII 1ava the fuII name of every cIass
you use, unless that class is in the |ava.lang
package. An import statement for the class
or package at the top of your source code is the
easy way. Otherwise, you have to type the full
name of the class, everywhere you use it!
One more time, in the unlikely
event that you don't already
have this down:
(-,- a,- |
oa|| qa--(:|-
Does import make my
cIass bigger! Does it actuaIIy
compiIe the imported cIass or
package into code!
Perhaps you're a C pro-
grammerI An import is not the
same as an include. So the
answer is no and no. Pepeat after
me: "an import statement saves
you from typing. That's really it.
ou don't have to worry about
your code becoming bloated, or
slower, from too many imports.
An import is simply the way you
give 1ava the lull nome ol o closs.
Dk, how come I never had
to import the String cIass! Dr
System!
Pemember, you get the
|ava.lang package sort of "pre-
imported for free. 8ecause
the classes in |ava.lang are so
fundamental, you don't have to
use the full name. There is only
one |ava.lang.String class, and one
|ava.lang.System class, and 1ava
darn well knows where to find
them.
Do I have to put my own
cIasses into packages! How do I
do that! I do that!
|n the real world (which
you should try to avoid), yes, you
w|ll want to put your classes into
packages. we'll get into that in
detail in chapter l6. Por now, we
won't put our code examples in a
package.
import
or
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
158 chapter 6
Hew !e p|zy w| !h !hc ||
getting to know the API
CooJ o Irow Le.e` nr A..n,1. .r
Le n.n.u.I nIne. Bu b, ,eI, Low
wouIJ Ln.e u.eJ Ln ou:`
Two things you want to know:
- JuIio, 3I, hond modeI

Browse a Book

Use the HTML AP docs


What classes are in the library?
Once you hnd a class, how do
you know what it can do?

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 159

Browse a Book
FIipping fhrough o
reference book is fhe
besf woy fo fnd ouf
whof's in fhe Jovo
Iibrory. You con eosiIy
sfumbIe on o cIoss fhof
Iooks usefuI, jusf by
browsing poges.
.:.- -.--
:|.:: -.--
:|.:: -::-l--
--l-: |.- -l-- l-:
--'|| l.| .--l |.l--`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
160 chapter 6
using the Java API documentation

Use the HTML AP docs


:--|| l--- l- .:.-:
.- :-|-:l --- |:|: l`
l- --:l-:l l- |:l - l-
|---- -.-- l- --|] :|.::-:
--- l.l .:.-
]ava comcs wiih a lalulous sci ol onlinc uocs
callcu, siiangcly, ihc ]ava API. Thcy`ic aii ol
a laigci sci callcu ihc ]ava Sianuaiu Euiiion
Documcniaiion which, uccnuing on whai
uay ol ihc wccI you looI, Sun may lc iclci-
iing io as ]ava 2 Sianuaiu Euiiion .0"), anu
you havc io uownloau ihc uocs scaiaicly,
ihcy uon`i comc shiinI-wiacu wiih ihc ]ava
uownloau. Il you havc a high-sccu inicinci
conncciion, oi ions ol aiicncc, you can also
liowsc ihcm ai |ava.sun.com. Tiusi us, you
iolally wani ihcsc on youi haiu uiivc.
Thc API uocs aic ihc lcsi iclcicncc loi gci-
iing moic uciails aloui a class anu iis mcihous.
Ici`s say you wcic liowsing ihiough ihc iclci-
cncc looI anu lounu a class callcu Calcnuai,
in |ava.uiil. Thc looI iclls you a liiilc aloui ii,
cnough io Inow ihai ihis is inuccu whai you
wani io usc, lui you siill nccu io Inow moic
aloui ihc mcihous.
Thc iclcicncc looI, loi cxamlc, iclls you
whai ihc mcihous iaIc, as aigumcnis, anu whai
ihcy iciuin. IooI ai AiiayIisi, loi cxamlc.
In ihc iclcicncc looI, you`ll hnu ihc mcihou
inucxOl), ihai wc uscu in ihc DoiCom class.
Bui il all you Incw is ihai ihcic is a mcihou
callcu inucxOl) ihai iaIcs an ol|cci anu ic-
iuins ihc inucx an ini) ol ihai ol|cci, you siill
nccu io Inow onc ciucial ihing: whai hacns
il ihc ol|cci is noi in ihc AiiayIisi. IooIing
ai ihc mcihou signaiuic alonc won`i icll you
how ihai woiIs. Bui ihc API uocs will mosi ol
ihc iimc, anyway). Thc API uocs icll you ihai
ihc inucxOl) mcihou iciuins a -1 il ihc ol|cci
aiamcici is noi in ihc AiiayIisi. Thai`s how
wc Incw wc coulu usc ii loih as a way io chccI
il an ol|cci is cvcn in ihc AiiayIisi, anu io gci
iis inucx ai ihc samc iimc, il ihc ol|cci was
ihcic. Bui wiihoui ihc API uocs, wc mighi havc
ihoughi ihai ihc inucxOl) mcihou woulu
llow u il ihc ol|cci wasn`i in ihc AiiayIisi.
:--|| l--- l- :|.::-:
.- :-|-:l --- |:|: l` l-
:--:- l- :|.:: l.l -
|| ||
l- -
.- ---
:-- -.-
-
1
: : ---- .|| l-
-- :l- : /
-- :.-
::--|| l--- l-
--l-: -- . --
:---.-], -- :|: --
. --l- l- -l -||
-l.|:
1
2
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 161
Can you reconstruct the code snippets to make a
working 1ava program that produces the output
listed belowI ND7: To do this exercise, you need
one NLw piece of infoif you look in the AP| for
ArrayList, you'll find a seconJ add method that takes
two arguments:
add(int index, Dbject o)
|t lets you specify to the
ArrayList whete to put the ob|ect you're adding.

CaJe Kagaets
if (a.contains(three)) {
a.add(four);
}
import java.util.*;
public class ArrayListMagnet {
ArrayList<String> a = new ArrayList<String>();
public static void main (String[] args) {
a.add(0,zero);
a.add(1,one);
a.add(2,two);
a.add(3,three);
printAL(a);
a.remove(2);
if (a.indexOf(four) != 4) {
a.add(4, 4.2);
}
if (a.contains(two)) { a.add(2.2);
}
public static void printAL(ArrayList<String> al) {
for (String element : al) {
System.out.print(element + );
}
System.out.println( );
}
}
}
printAL(a);
printAL(a);
printAL(a);
File Edit Window Help Dance
% java ArrayListMagnet
zero one two three
zero one three four
zero one three four 4.2
zero one three four 4.2
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
162 chapter 6
]||(iss ).c
How does this crossword puzzle help you learn
1avaI well, all of the words are 1ava related
(except one red herring).
Hint: when in doubt, remember ArrayList.
Down
2. where the 1ava action is.
3. Addressable unit
4. 2nd smallest
5. Practional default
8. Library's grandest
l0. Must be low density
ll. He's in there somewhere
l5. As if
l6. dearth method
l8. what shopping and arrays have in common
20. Library acronym
2l. what goes around
l7
24
l2
8
2l
l6
ll
l9
22
l8
l3
l0
l5
2
23
9
3 l
6
l4
5
4
20
Across
l. | can't behave
6. Or, in the courtroom
7. where it's at baby
9. A fork's origin
l2. Grow an ArrayList
l3. wholly massive
l4. value copy
l6. Not an ob|ect
l7. An array on steroids
l9. Lxtent
2l. l9's counterpart
22. Spanish geek snacks (Note: This has
nothing to do with 1ava.)
23. Por lazy ngers
24. where packages roam
7
More Hints:
A c r o s s D o w n
l . 8 v a r i e t i e s 2 . w h a t ' s o v e r r i d a b l e I
7 . T h i n k A r r a y L i s t 3 . T h i n k A r r a y L i s t
l 6 . C o m m o n p r i m i t i v e 4 . & l 0 . P r i m i t i v e
2 l . A r r a y ' s e x t e n t l 6 . T h i n k A r r a y L i s t
2 2 . N o t a b o u t 1 a v a - S p a n i s h a p p e t i z e r s l 8 . H e ' s m a k i n g a _ _ _ _ _ _
puzzIe: crossword
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
get to know the Java API
you are here 163
File Edit Window Help Dance
% java ArrayListMagnet
zero one two three
zero one three four
zero one three four 4.2
zero one three four 4.2
]e;ejze o|ajoz
if (a.contains(three)) {
a.add(four);
}
import java.util.*;
public class ArrayListMagnet {
ArrayList<String> a = new ArrayList<String>();
public static void main (String[] args) {
a.add(0,zero);
a.add(1,one);
a.add(2,two);
a.add(3,three);
printAL(a);
a.remove(2);
if (a.indexOf(four) != 4) {
a.add(4, 4.2);
}
if (a.contains(two)) {
a.add(2.2);
}
public static void printAL(ArrayList<String> al) {
for (String element : al) {
System.out.print(element + );
}
System.out.println( );
}
}
}
printAL(a);
printAL(a);
printAL(a);
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
164 chapter 6
l7
24
l2
8
2l
l6
ll
l9
22
l8
l3
l0
l5
2
23
9
3 l
6
l4
5
4
20
7
| | M | 1 | / !
l ! | +
6 B ) ! c 1 | N l ! x 6 |
c + M
B | 6 | | ! 1 c
| A l l | 6 N 6 6
6 ! 1 c 6 1 N
r / A | N 1
A A / | | 1 | A
6 | _ ! |
A | ! N 6 1 + M N
| 6 c 1 A | A
| M | 6 1 A 1
| | | B A /
]||(iss
|nsacis
+,-+ :+ ,-+:.|

2. ___________________________________
3. ___________________________________
4. ___________________________________
5. ___________________________________
8. ___________________________________
l0. ___________________________________
ll. ___________________________________
l5. ___________________________________
l6. ___________________________________
l8. ___________________________________
20. ___________________________________
2l. ___________________________________

l. ___________________________________
6. ___________________________________
7. ___________________________________
9. ___________________________________
l2. ___________________________________
l3. ___________________________________
l4. ___________________________________
l6. ___________________________________
l7. ___________________________________
l9. ___________________________________
2l. ___________________________________
22. ___________________________________
23. ___________________________________
24. ___________________________________
write your OwN set of clues! Look at each word, and try to
write your own clues. Try making them easier, or harder, or
more technical than the ones we have.
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 165
7 inheritance and poIymorphism
PIan your programs with the future in mind. |f there were a way to write
1ava code such that you could take more vacations, how much would it be worth to youI what
if you could write code that someone could extend, I And if you could write code
that was flexible, for those pesky last-minute spec changes, would that be something you're
interested inI Then this is your lucky day. Por |ust three easy payments of 60 minutes time, you
can have all this. when you get on the Polymorphism Plan, you'll learn the 5 steps to better class
design, the 3 tricks to polymorphism, the 8 ways to make flexible code, and if you act nowa
bonus lesson on the 4 tips for exploiting inheritance. Don't delay, an offer this good will give
you the design freedom and programming flexibility you deserve. |t's quick, it's easy, and it's
available now. Start today, and we'll throw in an extra level of abstraction!
Better Living in
Ob]ectville
We were underpoid,
overworked coders 'fiII we
fried fhe PoIymorphism PIon. 8uf
fhonks fo fhe PIon, our fufure is
brighf. Yours con be fool
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
166 chapter 7
0hz| r Wzrs Kcv|s| !c4...
Remember woy boch in chopter 2, when Lorry )proceduroI guy;
ond Brod )OO guy; were vying [or the Aeron choir Let`s Iooh ot
o [ew pieces o[ thot story to review the bosics o[ inheritonce.
LARRY: You`vc goi uulicaicu couc! Thc ioiaic ioccuuic
is in all loui Shac ihings. Ii`s a siuiu ucsign. You havc io
mainiain loui uillcicni ioiaic mcihous". How can ihai
cvci lc goou.
BRAD: Oh, I gucss you uiun`i scc ihc hnal ucsign. Ici mc
show you how OO inhcritancc woiIs, Iaiiy.
Ihcyrc 8hzpcs, zn4 !hcy z| | re!z!c zn4
p|zy8een4. 8e | z|s!rzr!c4 ee! !hc
remmen fcz!ercs zn4 pe! !hcm |n!e z
ncw r|zss rz| |c4 8hzpc.
3|ape
rolale()
p|ay3ourd()
Tr|ar|e 3quare C|rc|e Aroeoa
3|ape
rolale()
p|ay3ourd()
sepcrr|zss
se|r|zsscs
Ihcn | ||nkc4 !hc e!hcr
feer shzpc r|zsscs !e
!hc ncw 8hzpc r|zss,
|n z rc|z!|ensh|p rz||c4
|nhcr| !znrc.
Tr|ar|e
rolale()
p|ay3ourd()
3quare
rolale()
p|ay3ourd()
C|rc|e
rolale()
p|ay3ourd()
| |eekc4 z! whz! z|| feer
r|zsscs hzvc |n remmen.
Aroeoa
rolale()
p|ay3ourd()

You car read l||s as, "8quare |nher|ts from 8hape",


"6|rc|e |nher|ts from 8hape", ard so or. l reroved
rolale() ard p|ay3ourd() lror l|e ol|er s|apes, so roW
l|ere's or|y ore copy lo ra|rla|r.
T|e 3|ape c|ass |s ca||ed l|e superc|ass ol l|e ol|er lour
c|asses. T|e ol|er lour are l|e subc|asses ol 3|ape. T|e
suoc|asses |r|er|l l|e rel|ods ol l|e superc|ass. lr ol|er
Words, |l rne $nae o|ass nas rne lunor|ona||ry, rnen rne
suoo|asses auromar|oa||y ger rnar same lunor|ona||ry.
the power of inheritance
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 167
Whz! z|ee! !hc mec|z re!z!c| I!
Wasn`i ihai ihc wholc iollcm hcic - ihai ihc amocla shac
hau a comlcicly uillcicni ioiaic anu laySounu ioccuuic.
How can amocla uo somcihing uillcicni il ii .rLe.. iis
lunciionaliiy liom ihc Shac class.
Thai`s ihc lasi sic. Thc Amocla class ihc
mcihous ol ihc Shac class. Thcn ai iuniimc, ihc ]VM Inows
cxacily which .one() mcihou io iun whcn somconc iclls ihc
Amocla io ioiaic.
O
v
e
r
ride
N
o
w
A
s
k
Me
H
o
w
| mz4c !hc mec|z r|zss evcrr|4c
!hc re!z!c|I mc!he4 ef !hc
sepcrr|zss 8hzpc.
0vcrr|4|n] jes! mczns !hz! z
se|r|zss rc4cf|ncs enc ef | !s
|nhcr| !c4 mc!he4s whcn | ! ncc4s
!e rhzn]c er cr!cn4 !hc |chzv|er
ef !hz! mc!he4.

Tr|ar|e 3quare C|rc|e Aroeoa


rotate(}
// aroeoa-spec|l|c
// rolale code
p|ay8ound(}
// aroeoa-spec|l|c
// sourd code
3|ape
rolale()
p|ay3ourd()
sepcrr|zss
|merc z|s!rzr!I
se|r|zsscs
|merc spcr|f|rI
0vcrr|4|n] mc!he4s
How would you represent a house cat and a tiger, in an
inheritance structure. |s a domestic cat a specialized
version of a tigerI which would be the subclass and
which would be the superclassI Or are they both
subclasses to some classI
How would you design an inheritance structureI what
methods would be overriddenI
Think about it. you turn the page.
| mz4c !hc mec|z r|zss evcrr|4c !hc
re!z!c|I zn4 p|zy8een4|I mc!he4s
ef !hc sepcrr|zss 8hzpc. 0vcrr|4|n]
jes! mczns !hz! z se|r|zss rc4cf|ncs
enc ef | !s |nhcr| !c4 mc!he4s whcn
| ! ncc4s !e rhzn]c er cr!cn4 !hc
|chzv|er ef !hz! mc!he4.
WWkm
Qw&W
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
168 chapter 7
0n4crs!zn4| n] |nhcr| !znrc
When you oesign with inheritance, you put common cooe in
a class ano then tell other more specilic classes that the
common ,more abstract, class is their superclass. When one
class inherits lrom another, thc suhcIass inhcrits fron thc
supcrcIass.
In Java, we say that the subclnss tho suporclnss.
An inheritance relationship means that the subclass inherits
the ncnhcrs ol the superclass. When we say members ol
a class we mean the instance variables ano methoos.
Ior example, il FantherMan is a subclass ol SuperHero, the
FantherMan class automatically inherits the instance variables
ano methoos common to all superheroes incluoing suit,
tights, specialPower, useSpecialPowers(), ano
so on. But the FantherMan suhcIass can add ncv
ncthods and instancc variahIcs ol its own, ano it can
ovcrridc thc ncthods it inhcrits fron thc supcrcIass
SuperHero.
3uperlero
su|l
l||ls
spec|a|PoWer
use3pec|a|PoWer()
pul0r3u|l()
sepcrr|zss
|merc z|s!rzr!I
se|r|zsscs
|merc spcr|f|rI
0vcrr|4|n]
mc!he4s
Parl|erVar
use8pec|a|Power(}
put0n8u|t(}
|ns!znrc vzr|z||cs
|s!z!c, z!!r||e!csI
mc!he4s
||chzv|erI
IrieoEggMan ooesn`t neeo any behavior that`s unique,
so he ooesn`t overrioe any methoos. The methoos ano
instance variables in SuperHero are sullicient.
FantherMan, though, has specilic requirements lor his suit
ano special powers, so useSpecialPower() ano
putOnSuit() are both overriooen in the FantherMan
class.
Instancc variahIcs arc not ovcrriddcn because they
oon`t neeo to be. They oon`t oeline any special behavior, so a
subclass can give an inheriteo instance variable any value it
chooses. FantherMan can set his inheriteo tights to
purple, while IrieoEggMan sets his to white.
Fr|edEVar
the way inheritance works

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 169
sepcrr|zss
0oclor
Wor|sAllosp|la|
lrealPal|erl ()
Adds ore reW
|rslarce var|ao|e
Adds ore reW rel|od
se|r|zsscs
0verr|des l|e |r|er|led
lrealPal|erl() rel|od
Adds ore reW rel|od
3ureor
lrealPal|erl ()
ra|elrc|s|or()
Far||y0oclor
ra|eslouseCa||s
|veAdv|ce ()
enc |ns!znrc vzr|z||c
enc mc!he4
+,-+ :+ ,-+:.|
loW rary |rslarce var|ao|es does
3ureor |ave?
loW rary |rslarce var|ao|es does
Far||y0oclor |ave?
loW rary rel|ods does 0oclor |ave?
loW rary rel|ods does 3ureor |ave?
loW rary rel|ods does Far||y0oclor
|ave?
Car a Far||y0oclor do lrealPal|erl()?
Car a Far||y0oclor do ra|elrc|s|or()?
public class Doctor {
boolean worksAtHospital;
void treatPatient() {
// perform a checkup
}
}
public class FamilyDoctor extends Doctor {
boolean makesHouseCalls;
void giveAdvice() {
// give homespun advice
}
}
public class Surgeon extends Doctor{

void treatPatient() {
// perform surgery
}
void makeIncision() {
// make incision (yikes!)
}
}
I inherifed my
procedures so I didn'f
bofher wifh medicoI schooI.
PeIox, fhis won'f hurf o bif.
(now where did I puf fhof
power sow...)
n |nhcr| !znrc crzmp|c:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
170 chapter 7
Whut do these si types huve in
common? This heIps you to ubstruct
out behuviors, {step Z}
How ure these types reIuted? This
heIps you to dehne the inheritunce
tree reIutionships {step 4-}
Ic!s 4cs|]n !hc |nhcr| !znrc !rcc fer
zn n|mz| s|me|z!|en pre]rzm
Imaginc you`ic asIcu io ucsign a simulaiion iogiam ihai
lcis ihc usci ihiow a lunch ol uillcicni animals inio an
cnviionmcni io scc whai hacns. Wc uon`i havc io couc ihc
ihing now, wc`ic mosily inicicsicu in ihc ucsign.
Wc`vc lccn givcn a lisi ol ol ihc animals ihai will lc
in ihc iogiam, lui noi all. Wc Inow ihai cach animal will
lc icicscnicu ly an ol|cci, anu ihai ihc ol|ccis will movc
aiounu in ihc cnviionmcni, uoing whaicvci ii is ihai cach
aiiiculai iyc is iogiammcu io uo.
And we wont other progrommers to be obIe to odd new
hinds o[ onimoIs to the progrom ot ony time.
Iiisi wc havc io hguic oui ihc common, alsiiaci
chaiaciciisiics ihai all animals havc, anu luilu ihosc
chaiaciciisiics inio a class ihai all animal classcs can cxicnu.

Look for objecfs fhof hove common


offribufes ond behoviors.
designing for inheritance
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 171
These objects ure uII unimuIs so
we'II muke u common supercIuss
cuIIed AnimuI,
We'II put in methods und instunce
vuriubIes thut uII unimuIs might
need,

Design o cIoss fhof represenfs


fhe common sfofe ond behovior.

picture
food
hunger
boundaries
location
makeNoise()
eat()
sleep()
roam()
Wc havc hvc instonce voriobIes:
picture - ihc hlc namc icicscniing ihc ]PEG ol ihis animal
[ood - ihc iyc ol loou ihis animal cais. Righi now, ihcic
can lc only iwo valucs: oi .
hunger - an ini icicscniing ihc hungci lcvcl ol ihc animal.
Ii changcs uccnuing on whcn anu how much) ihc
animal cais.
boundories - valucs icicscniing ihc hcighi anu wiuih ol
ihc sacc` loi cxamlc, 640 x 4S0) ihai ihc animals will
ioam aiounu in.
Iocotion - ihc X anu Y cooiuinaics loi whcic ihc animal is
in ihc sacc.
Wc havc loui methods:
moheNoise ) - lchavioi loi whcn ihc animal is suoscu io
maIc noisc.
eot); - lchavioi loi whcn ihc animal cncounicis iis
iclciicu loou souicc, oi .
sIeep); - lchavioi loi whcn ihc animal is consiucicu aslcc.
room); - lchavioi loi whcn ihc animal is noi caiing oi
slccing iolally |usi wanuciing aiounu waiiing io lum
inio a loou souicc oi a lounuaiy).
0s|n] |nhcr| !znrc !e zve|4
4ep||rz!|n] re4c |n se|r|zsscs
size
picture
food
prey
Dog
size
picture
food
prey
WoIf
size
picture
food
prey
Cat
size
picture
food
prey
Tiger
size
picture
food
prey
Hippo
size
picture
food
prey
Lion
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
172 chapter 7
Assumc ihai wc all agicc on onc ihing: ihc insiancc
vaiiallcs will woiI loi nII Animal iycs. A lion will
havc his own valuc loi iciuic, loou wc`ic ihinIing
en), hungci, lounuaiics, anu locaiion. A hio
will havc uillcicni .nIue loi his insiancc vaiiallcs,
lui hc`ll siill havc ihc samc vaiiallcs ihai ihc oihci
Animal iycs havc. Samc wiih uog, iigci, anu so on.
Bui whai aloui beLn..o..
Wh|rh mc!he4s shee|4 wc evcrr|4c!
Docs a lion maIc ihc samc as a uog. Docs
a cai liIc a hio. Maylc in ,ou. vcision, lui
in ouis, caiing anu maIing noisc aic Animal-iyc-
sccihc. Wc can`i hguic oui how io couc ihosc
mcihous in such a way ihai ihcy`u woiI loi any
animal. OK, ihai`s noi iiuc. Wc coulu wiiic ihc
maIcNoisc) mcihou, loi cxamlc, so ihai all ii uocs
is lay a sounu hlc uchncu in an insiancc vaiiallc
loi ihai iyc, lui ihai`s noi vciy sccializcu. Somc
animals mighi maIc uillcicni noiscs
loi uillcicni siiuaiions liIc onc
loi caiing, anu anoihci whcn
luming inio an cncmy, cic.)
So |usi as wiih ihc Amocla
ovciiiuing ihc Shac class ioiaic)
mcihou, io gci moic amocla-sccihc in
oihci woius, ur.que) lchavioi, wc`ll havc
io uo ihc samc loi oui Animal sulclasscs.
Pe z| | zn|mz|s cz! !hc szmc wzy!

I'm one bod*ss


pIonf-eofer.
In fhe dog
communify, borking is on
imporfonf porf of our cuIfuroI
idenfify. We hove o unique sound,
ond we wonf fhof diversify fo
be recogni;ed ond respecfed.
picture
food
hunger
boundaries
location
makeNoise()
eat()
sleep()
roam()
w- -ll-- ----- l-:- l-- --l-:, -.l|`
.- -.-N-:-|`, :- l.l -.: .--.| l]- :.-
--- l: --- :-:: -.-- -- -.l- .-
-.- --:- |-- ---, l |--: |- :|--|` .-
--.-|` :.- :l.] ----:
Looking ut the AnimuI cIuss
we decide thut eut{} und
mukeNoise{} shouId be overridden
by the individuuI subcIusses,

Decide if o subcIoss
needs behoviors (mefhod
impIemenfofions) fhof ore specifc
fo fhof porficuIor subcIoss fype.
designing for inheritance
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
inheritance and poIymorphism
you are here 173
We Iook ut our cIusses und see
thut WoIf und Dog might huve some
behuvior in common und the sume goes
for Lion Tiger und Cut,

Look for more opporfunifies fo use


obsfrocfion, by fnding fwo or more
subcIosses fhof mighf need common
behovior.
Thc class hiciaichy is siaiiing io shac u. Wc
havc cach sulclass ovciiiuc ihc nIeNo.e() anu
en() mcihous, so ihai ihcic`s no misiaIing a Dog
laiI liom a Cai mcow quiic insuliing io loih
aiiics). Anu a Hio won`i cai liIc a Iion.
Bui cihas ihcic`s moic wc can uo. Wc havc io
looI ai ihc sulclasscs ol Animal, anu scc il iwo
oi moic can lc gioucu iogcihci in somc way,
anu givcn couc ihai`s common io only Ln ncw
giou. Woll anu Dog havc similaiiiics. So uo
Iion, Tigci, anu Cai.
Ieek|n] fer merc |nhcr| !znrc
epper!en| !|cs

size
picture
food
prey
Dog
size
picture
food
prey
WoIf
size
picture
food
prey
Cat
size
picture
food
prey
Tiger
size
picture
food
prey
Hippo
size
picture
food
prey
Lion
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
+
-
-
-
| -
--
--
|
--,
1
--, .-
c
.l
-
--|

.-
:--
-l

- - :--
-
--
w-| .- l- .-- -l :.---:
-.]- l---': :---l- l.l
B61+ :|.::-: :--| -:-
picture
food
hunger
boundaries
location
makeNoise()
eat()
sleep()
roam()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
174 chapter 7
Finish fhe cIoss hierorchy

FeIine
roam()
Canine
size
picture
food
prey
Lion
size
picture
food
prey
Tiger
size
picture
food
prey
Cat
size
picture
food
prey
WoIf
size
picture
food
prey
Dog
Since onimoIs oIreody hove on orgoni;ofionoI
hierorchy (fhe whoIe kingdom, genus, phyIum
fhing), we con use fhe IeveI fhof mokes fhe mosf
sense for cIoss design. We'II use fhe bioIogicoI
"fomiIies" fo orgoni;e fhe onimoIs by moking o
FeIine cIoss ond o Conine cIoss.
We decide thut Cunines couId use u common
roum{} method becuuse they tend to move in
pucks, We uIso see thut FeIines couId use u
common roum{} method becuuse they tend to
uvoid others of their own kind, We'II Iet Hippo
continue to use its inherited roum{} method
the generic one it gets from AnimuI,
So we're done with the design for now; we'II
come buck to it Iuter in the chupter,

size
picture
food
prey
Hippo
makeNoise()
eat()
roam()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
picture
food
hunger
boundaries
location
makeNoise()
eat()
sleep()
roam()
designing for inheritance
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 175
Wolf w = new Wolf();
w.makeNoise();
w.roam();
w.eat();
w.sleep();
Wh|rh mc!he4 |s rz||c4!
Thc Woll class has loui mcihous. Onc
inhciiicu liom Animal, onc inhciiicu liom
Caninc which is aciually an ovciiiuucn
vcision ol a mcihou in class Animal), anu
iwo ovciiiuucn in ihc Woll class. Whcn
you cicaic a Woll ol|cci anu assign ii io
a vaiiallc, you can usc ihc uoi ociaioi
on ihai iclcicncc vaiiallc io invoIc all
loui mcihous. Bui which ol ihosc
mcihous gcis callcu.
-.- . --- w-| --:l
:.||: l- --:-- - w-|
:.||: l- --:-- - c.---
:.||: l- --:-- - w-|
:.||: l- --:-- - A--.|
size
picture
food
prey
WoIf
Canine
roam()
makeNoise()
eat()

makeNoise()
eat()
sleep()
roam()
Whcn you call a mcihou on an ol|cci
iclcicncc, you`ic calling ihc mosi sccihc
vcision ol ihc mcihou loi ihai ol|cci iyc.
In oihci woius, the Iowest one wins:
Iowcsi" mcaning lowcsi on ihc
inhciiiancc iicc. Caninc is lowci ihan
Animal, anu Woll is lowci ihan Caninc,
so invoIing a mcihou on a iclcicncc
io a Woll ol|cci mcans ihc ]VM siaiis
looIing hisi in ihc Woll class. Il ihc ]VM
uocsn`i hnu a vcision ol ihc mcihou in
ihc Woll class, ii siaiis walIing lacI u
ihc inhciiiancc hiciaichy uniil ii hnus a
maich.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
176 chapter 7
0raW ar |r|er|larce d|arar |ere.
practice designing an inheritance tree
(-,- a,- |
oa|| qa--(:|-

You said that the 1VM starts
waIking up the inheritance tree,
starting at the cIass type you invoked
the method on (Iike the WoIf exampIe
on the previous page). ut what
happens if the 1VM doesn't ever nd
a match!

Good question! 8ut you don't


have to worry about that. The compiler
guarantees that a particular method
is callable for a specific reference type,
but it doesn't say (or care) from which
closs that method actually comes from
at runtime. with the wolf example, the
compiler checks for a sleep() method,
but doesn't care that sleep() is actually
defined in (and inherited from) class
Animal. Pemember that if a class
|nhet|ts a method, it hos the method.
whete the inherited method is defined
(in other words, in which superclass
it is defined) makes no difference to
the compiler. 8ut at runtime, the 1VM
wiII aIways pick the right one. And
the right one means, rhe mesr seciIic
versien Ier rhnr nrriculnr ebjecr.
\,-+ :+ ,-+:.|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 177
0s|n] |8- zn4 H8-
Rcmcmlci ihai whcn onc class
inhciiis liom anoihci, wc say ihai ihc
sulclass e:erJ ihc suciclass. Whcn
you wani io Inow il onc ihing shoulu
cxicnu anoihci, aly ihc IS-A icsi.
Tiianglc IS-A Shac, ycah, ihai woiIs.
Cai IS-A Iclinc, ihai woiIs ioo.
Suigcon IS-A Docioi, siill goou.
Tul cxicnus Baihioom, sounus
icasonallc.
Ur.I ,ou nI, Le IS-A e.
To Inow il you`vc ucsigncu youi iycs
coiiccily, asI, Docs ii maIc scnsc io
say iyc X IS-A iyc Y." Il ii uocsn`i,
you Inow ihcic`s somcihing wiong
wiih ihc ucsign, so il wc aly ihc IS -A
icsi, Tul IS-A Baihioom is uchniicly
lalsc.
Whai il wc icvcisc ii io Baihioom
cxicnus Tul. Thai siill uocsn`i woiI,
Baihioom IS-A Tul uocsn`i woiI.
Tul anu Baihioom n.e iclaicu, lui
noi ihiough inhciiiancc. Tul anu
Baihioom aic |oincu ly a HAS-A
iclaiionshi. Docs ii maIc scnsc io
say Baihioom HAS-A Tul". Il ycs,
ihcn ii mcans ihai Baihioom has a
Tul insiancc vaiiallc. In oihci woius,
Baihioom has a .ee.ere io a Tul, lui
Baihioom uocs noi e:erJ Tul anu
vicc-vcisa.
Does if moke sense fo
soy o Tub IS-A 8ofhroom7 Or o
8ofhroom IS-A Tub7 WeII if doesn'f fo
me. The reIofionship befween my Tub
ond my 8ofhroom is HAS-A. 8ofhroom
HAS-A Tub. Thof meons 8ofhroom
ho s o Tub insfonce voriobIe.
athroom
Tuo oal|luo,
3|r| l|e3|r|,
Tub
|rl s|ze,
8uoo|es o,
ubb|es
|rl rad|us,
|rl co|orArl,
8al|roor lA3-A Tuo ard Tuo lA3-A 8uoo|es.
8ul rooody |r|er|ls lror (exlerds) aryoody e|se.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
expIoiting the power of objects
178 chapter 7
Be! wz| !| Ihcrcs merc|
Thc IS-A icsi woiIs nr,wLe.e in ihc inhciiiancc iicc. Il youi
inhciiiancc iicc is wcll-ucsigncu, ihc IS-A icsi shoulu maIc
scnsc whcn you asI nr, sulclass il ii IS-A nr, ol iis suciiycs.
f class B extends class A, class B 8-A class A.
This is true anywhere in the inheritance tree. f
class C extends class B, class C passes the 8-A
test for both B and A.
size
picture
food
prey
WoIf
Canine
roam()
makeNoise()
eat()
Animal
makeNoise()
eat()
sleep()
roam()
Canine extends Animal
Wolf extends Canine
Wolf extends Animal
Canine S-A Animal
Wolf S-A Canine
Wolf S-A Animal
Wiih an inhciiiancc iicc liIc ihc
onc shown hcic, you`ic nIwn,
allowcu io say WolI cxtcnds
Animal oi WolI IS-A Animal.
Ii maIcs no uillcicncc il Animal
is ihc suciclass ol ihc suciclass
ol Woll. In laci, as long as Animal
is in thc inhcritancc
hicrarchy abovc WolI, WolI IS-A
Animal will always bc truc.
Thc siiuciuic ol ihc Animal
inhciiiancc iicc says io ihc woilu:
Woll IS-A Caninc, so Woll can uo
anyihing a Caninc can uo. Anu
Woll IS-A Animal, so Woll can uo
anyihing an Animal can uo."
Ii maIcs no uillcicncc il Woll
ovciiiucs somc ol ihc mcihous
in Animal oi Caninc. As lai as
ihc woilu ol oihci couc) is
conccincu, a Woll can uo ihosc
loui mcihous. How hc uocs ihcm,
oi .r wL.L In Le,`.e o.e...JJer
maIcs no uillcicncc. A Woll can
maIcNoisc), cai), slcc), anu
ioam) lccausc a Woll cxicnus
liom class Animal.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 179
l|nr. a|y rne l$-/ resr
Pul a c|ec| rexl lo l|e re|al|ors||ps l|al
ra|e serse.
0ven extends K|tchen
Cu|tar extends |nstrument
Person extends Emp|oyee
Ferrar| extends Eng|ne
Fr|edEgg extends Food
eag|e extends Pet
6onta|ner extends Jar
Heta| extends T|tan|um
Cratefu|0ead extends and
|onde extends 8mart
everage extends Hart|n|
\,-+ :+ ,-+:.|
Hew 4e yee knew |f yeevc ]e!
yeer |nhcr| !znrc r|]h!!
Thcic`s olviously moic io ii ihan whai wc`vc
covcicu so lai, lui wc`ll looI ai a loi moic OO
issucs in ihc ncxi chaici whcic wc cvcniually
ichnc anu imiovc on somc ol ihc ucsign woiI
wc uiu in chaici).
Ioi now, ihough, a goou guiuclinc is io usc ihc
IS-A icsi. Il X IS-A Y" maIcs scnsc, loih classcs
X anu Y) shoulu iolally livc in ihc samc
inhciiiancc hiciaichy. Chanccs aic, ihcy havc
ihc samc oi ovcilaing lchaviois.
Keep in mind that the
inheritance 8-A relationship
works in only one directionl
Tiianglc IS-A Shac maIcs scnsc, so you can
havc Tiianglc cxicnu Shac.
Bui ihc icvcisc-Shac IS-A Tiianglc-uocs
maIc scnsc, so Shac shoulu noi cxicnu
Tiianglc. Rcmcmlci ihai ihc IS-A iclaiionshi
imlics ihai il X IS-A Y, ihcn X can uo anyihing
a Y can uo anu ossilly moic).

koses ote teJ, v|olets ote olue.


5qunre |s-o 5hne, the tevetse |snt ttue.
koses ote teJ, v|olets ote Jeot.
8eer |s-o rink, out not oll Jrinks ote beer.
OK, your turn. M
ake one that shows the one-
way-ness of the |S-A relationship. Pem
em
ber, if
X exrenJs , X l5-A m
ust m
ake sense.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
180 chapter 7
Acccss IcvcIs controI uho sees uhat, ano are crucial
to having well-oesigneo, robust Java cooe. Ior now we`ll
locus just on public ano private. The rules are simple lor
those two:
When a subclass inherits a member, it is as If the
subclass defIned the nenber Itself. In the Shape
example, Square inheriteo the rotate() ano
playSound() methoos ano to the outsioe worlo ,other
cooe, the Square class simply a rotate() ano
playSound() methoo.
The members ol a class incluoe the variables ano
methoos oelineo in the class plus anything inheriteo
lrom a superclass.
public members inherited
private members are inherited
Whe ]c!s !hc |ersrhc, whe ]c!s !hc perrc| z| n!
|hew !e knew whz! z se|r| zss rzn
| nhcr| ! frem | !s sepcrr| zssI
A subclass inherits members ol the
superclass. Members incluoe instance
variables ano methoos, although later in
this book we`ll look at other inheriteo members. A
superclass can choose whether or not it wants a
subclass to inherit a particular member by the level ol
access the particular member is given.
There are lour access levels that we`ll cover in this book.
Moving lrom most restrictive to least, the lour access
levels are:
private defauIt protected pubIic
who inherits what
(-,- a,- |
oa|| qa--(:|-

So we see how a subcIass gets


to inherit a supercIass method, but
what if the supercIass wants to use
the subcIass version of the method!
A superclass won't necessarily
lnow about any of its subclasses.
ou might write a class and much
later someone else comes along and
extends it. 8ut even if the superclass
creator does know about (and wants
to use) a subclass version of a method,
there's no sort of tevetse or ooclwotJs
inheritance. Think about it, children
inherit from parents, not the other way
around.

In a subcIass, what if I want to


use D7H the supercIass version and
my overriding subcIass version of a
method! In other words, I don't want
to compIeteIy the supercIass
version, I just want to add more stuff
to it.
ou can do this! And it's an
important design feature. Think of the
word "extends as meaning, "| want
to extenJ the functionality of the
superclass.
ou can design your superclass
methods in such a way that they
contain method implementations
that will work for any subclass, even
though the subclasses may still need
to 'append' more code. |n your subclass
overriding method, you can call the
superclass version using the keyword
super. |t's like saying, "first go run the
superclass version, then come back and
finish with my own code...
public void roam() {
super.roam();
// my own roam stuff
}
l: :.||: l- ---l- --:-- -
--.-|`, l-- :---: .: l- -
]--- --- :-:|.::~:-:: :--
N-l- -l ---- -l.|: .--l -.-|l .- --l-:l- - :.l--
|| |-|-]---l` .- .-- B
|hew !e knew whz! z se|r|zss rzn
|nhcr| ! frem | !s sepcrr|zssI
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 181
8ll P0lk5
A suoc|ass exrenos a superc|ass.
A suoc|ass |r|er|ls a|| uo||o |rslarce
var|ao|es ard rel|ods ol l|e superc|ass, oul
does rol |r|er|l l|e r|vare |rslarce var|ao|es
ard rel|ods ol l|e superc|ass.
lr|er|led rel|ods oan oe overr|dder, |rslarce
var|ao|es oannor oe overr|dder (a|l|ou| l|ey
car oe reoel|neo |r l|e suoc|ass, oul l|al's
rol l|e sare l||r, ard l|ere's a|rosl rever a
reed lo do |l.)
use l|e l3-A lesl lo ver|ly l|al your
|r|er|larce ||erarc|y |s va||d. ll X exrenos Y,
l|er X l$-/ Y rusl ra|e serse.
T|e l3-A re|al|ors||p Wor|s |r or|y ore
d|recl|or. A l|ppo |s ar Ar|ra|, oul rol a||
Ar|ra|s are l|ppos.
w|er a rel|od |s overr|dder |r a suoc|ass,
ard l|al rel|od |s |rvo|ed or ar |rslarce ol
l|e suoc|ass, l|e overr|dder vers|or ol l|e
rel|od |s ca||ed. (Tne |ouesr one u|ns.)
ll c|ass 8 exlerds A, ard C exlerds 8, c|ass
8 l3-A c|ass A, ard c|ass C l3-A c|ass 8, ard
c|ass C a|so l3-A c|ass A.
Alihough somc ol ihc icasons lchinu ihcsc iulcs won`i lc
icvcalcu uniil laici in ihis looI, loi now, simly Irow.r a
lcw iulcs will hcl you luilu a lciici inhciiiancc ucsign.
usc inhciiiancc whcn onc class is a moic sccihc iyc
ol a suciclass. Examlc: Willow . n moic sccihc iyc ol
Ticc, so Willow e:erJ Ticc maIcs scnsc.
consiuci inhciiiancc whcn you havc lchavioi
imlcmcnicu couc) ihai shoulu lc shaicu among
muliilc classcs ol ihc samc gcncial iyc. Examlc:
Squaic, Ciiclc, anu Tiianglc all nccu io ioiaic anu lay
sounu, so uiiing ihai lunciionaliiy in a suciclass Shac
mighi maIc scnsc, anu maIcs loi casici mainicnancc anu
cxicnsililiiy. Bc awaic, howcvci, ihai whilc inhciiiancc is
onc ol ihc Icy lcaiuics ol ol|cci-oiicnicu iogiamming,
ii`s noi ncccssaiily ihc lcsi way io achicvc lchavioi icusc.
Ii`ll gci you siaiicu, anu olicn ii`s ihc iighi ucsign choicc,
lui ucsign aiicins will hcl you scc oihci moic sulilc
anu ucxillc oiions. Il you uon`i Inow aloui ucsign
aiicins, a goou lollow-on io ihis looI woulu lc HenJ E..
De.r Pne.r.
usc inhciiiancc |usi so ihai you can icusc
couc liom anoihci class, il ihc iclaiionshi lciwccn ihc
suciclass anu sulclass violaic ciihci ol ihc alovc iwo
iulcs. Ioi cxamlc, imaginc you wioic sccial iiniing
couc in ihc Alaim class anu now you nccu iiniing couc
in ihc Piano class, so you havc Piano cxicnu Alaim so ihai
Piano inhciiis ihc iiniing couc. Thai maIcs no scnsc! A
Piano is ro a moic sccihc iyc ol Alaim. So ihc iiniing
couc shoulu lc in a Piinici class, ihai all iiniallc ol|ccis
can iaIc auvaniagc ol via a HAS-A iclaiionshi.)
usc inhciiiancc il ihc sulclass anu suciclass
uo noi ass ihc IS-A icsi. Always asI youiscll il ihc sulclass
IS-A moic sccihc iyc ol ihc suciclass. Examlc: Tca IS-
A Bcvciagc maIcs scnsc. Bcvciagc IS-A Tca uocs noi.
Whcn 4cs|]n|n] w| !h |nhcr| !znrc,
zrc yee es|n] er z|es|n]!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
expIoiting the power of objects
182 chapter 7
8e whz! 4ecs z| | !h|s
|nhcr| !znrc rcz| | y |ey yee!
You gci a loi ol OO milcagc ly ucsigning
wiih inhciiiancc. You can gci iiu ol uulicaic
couc ly alsiiaciing oui ihc lchavioi common
io a giou ol classcs, anu siicIing ihai couc
in a suciclass. Thai way, whcn you nccu io
mouily ii, you havc only onc lacc io uuaic,
anu Le Lnre . n.nII, .eeeJ .r nII Le
Ine Ln .rLe.. Ln beLn..o.. Wcll, ihcic`s
no magic involvcu, lui ii . iciiy simlc:
maIc ihc changc anu comilc ihc class
again. Thai`s ii. You don't havc to touch thc
subclasscs!
]ust dclivcr thc ncwly-changcd supcrclass, and
all classcs that cxtcnd it will automatically usc
thc ncw vcrsion.
A ]ava iogiam is noihing lui a ilc ol classcs,
so ihc sulclasscs uon`i havc io lc iccomilcu
in oiuci io usc ihc ncw vcision ol ihc
suciclass. As long as ihc suciclass uocsn`i
b.enI anyihing loi ihc sulclass, cvciyihing`s
hnc. Wc`ll uiscuss whai ihc woiu licaI`
mcans in ihis conicxi, laici in ihc looI. Ioi
now, ihinI ol ii as mouilying somcihing in
ihc suciclass ihai ihc sulclass is uccnuing
on, liIc a aiiiculai mcihou`s aigumcnis oi
iciuin iyc, oi mcihou namc, cic.)
1
You avoid duplicate
code.
Puf common code in one pIoce, ond Ief
fhe subcIosses inherif fhof code from o
supercIoss. When you wonf fo chonge fhof
behovior, you hove fo modify if in onIy
one pIoce, ond everybody eIse (i.e. oII fhe
subcIosses) see fhe chonge.
2
You dehne a common
protocol for a group of
classes.
Um, whof
fhe heck does
THAT meon7
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
inheritance and poIymorphism
you are here 183
|nhcr| !znrc |c!s yee ]ezrzn!cc !hz!
z| | r|zsscs ]reepc4 en4cr z rcr!z|n
sepcr!ypc hzvc z| | !hc mc!he4s !hz!
!hc sepcr!ypc hzs.'
|n e!hcr wer4s, yee 4cf|nc z remmen pre!ere| fer z
sc! ef r|zsscs rc|z!c4 !hree]h |nhcr| !znrc.
Whcn you uchnc mcihous in a suciclass, ihai can lc
inhciiicu ly sulclasscs, you`ic announcing a Iinu ol
ioiocol io oihci couc ihai says, All my suliycs i.c.
sulclasscs) can uo ihcsc ihings, wiih ihcsc mcihous
ihai looI liIc ihis..."
In oihci woius, you csiallish a or.n.
Class Animal csiallishcs a common ioiocol loi all
Animal suliycs:
Animal
makeNoise()
eat()
sleep()
roam()
/--'-- l-||- l- ---| l.l
.-] A--.| :.- - l-:- ---
l-: 1.l -:|--: l- --l-
.-----l: .- --l--- l]-:
w|er We say 'a|| l|e rel|ods We rear 'a|| l|e |nner|rao|e rel|ods, W||c|
lor roW aclua||y rears, 'a|| l|e uo||o rel|ods, a|l|ou| |aler We'|| rel|re l|al
del|r|l|or a o|l rore.
Anu icmcmlci, whcn wc say nr, Ar.nI, wc mcan
Animal nrJ nr, In Ln e:erJ .o Ar.nI. Which
again mcans, nr, In Ln Ln Ar.nI oewLe.e nbo.e .
.r Le .rLe..nre L.e.n.L,.
Bui wc`ic noi cvcn ai ihc ically cool aii yci, lccausc
wc savcu ihc lcsi-oI,o.L.-loi lasi.
Whcn you uchnc a suciiyc loi a giou ol classcs,
nr, ubIn o Ln ue.,e nr be ub.ueJ wLe.e Le
ue.,e . e:eeJ.
Say, whai.
Don`i woiiy, wc`ic nowhcic ncai uonc cxlaining ii.
Two agcs liom now, you`ll lc an cxcii.
And care because...
8ecause you get to take advantage of
polymorphism.
Which matters to me
because...
8ecause you get to refer to a subclass
ob|ect using a reference declared as the
supertype.
And that means to me...
ou get to write really nexible code.
Code that's cleaner (more efcient,
simpler). Code that's not |ust easier to
Jevelo, but also much, much easier to
extenJ, in ways you never imagined at
the time you originally wrote your code.
That means you can take that tropical
vacation while your co-workers update
the program, and your co-workers might
not even need your source code.
ou'll see how it works on the next page.
we don't know about you, but
personally, we nd the whole
tropical vacation thing
particularly motivating.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
184 chapter 7
the way poIymorphism works
Dog myDog = new Dog();
Tells the 1vM to allocate space for a
reference variable. The reference variable
is, forever, of type Dog. |n other words,
a remote control that has buttons to
control a Dog, but not a Cat or a 8utton
or a Socket.

DecIore o reference
voriobIe
Dog

Dog myDog = new Dog();


Tells the 1vM to allocate space for
a new Dog ob|ect on the garbage
collectible heap.

Creofe on objecf
Dog myDog = new Dog();
The 3 steps of ob]ect
declaration and assignment
1
2
3
Dog objecf
Dog myDog = new Dog();
Assigns the new Dog to the refer-
ence variable myDog. |n other words,
regrnm rhe remere cenrrel.

Link fhe objecf


ond fhe reference
Dog objecf
Dog

To see how polymorphism


works, we have to step back
and look at the way we
normally declare a reference
and create an ob]ect...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 185
The important point is that the
reference type AND the ob]ect
type are the same.
n this example, both are Dog.
Dog

D
o
g
o
bj
e
c
f

1-:- l-- .-- l- :.-- l]- 1- ------:-
.-.|- l]- : -:|.-- .: l-, .- l- --:l
: :--.l- .: --- l-|`
But with polymorphism, the
reference and the ob]ect can
be different.
Animal myDog = new Dog();
AnimoI

D
o
g
o
bj
e
c
f

1-:- l-- .-- N61 l- :.-- l]- 1-
------:- .-.|- l]- : -:|.-- .: A--.|,
-l l- --:l : :--.l- .: --- l-|`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
186 chapter 7
With polymorphism, the reference
type can be a superclass of the
actual ob]ect type.
uh... nope.
SfiII nof geffin' if.
OK, OK maybe an example will help.
poIymorphism in action
Animal[] animals = new Animal[5];
animals [0] = new Dog();
animals [1] = new Cat();
animals [2] = new Wolf();
animals [3] = new Hippo();
animals [4] = new Lion();
for (int i = 0; i < animals.length; i++) {

animals[i].eat();

animals[i].roam();
}
l
-:|.-- .- .--.] - l]- A--.| |- -l-- ---:,
.- .--.] l.l -|| -| --:l: - l]- A--.|
B-l |-- -.l ]-- -l l- - ]-- :.- -l AN/
:-:|.:: - A--.| - l- A--.| .--.]'
A- ---': l- -:l -|]---: .-l |l-
-.:-- 'l-- -- l- --|- -.-|-`, ]--
-l l- |-- l--- l- .--.] .- :.|| ---
- l- A--.|~:|.:: --l-:, .- ---]
--:l --: l- -l l-'
w-- '' : o, . l- : .l -- o - l- .--.], :-
]-- -l l- l-': -.l|` --l- w-- '' : |, ]--
-l l- c.l': -.l|` --l-
.-- -l --.-|`
Whcn you ucclaic a iclcicncc vaiiallc,
any ol|cci ihai asscs ihc IS-A icsi loi ihc
ucclaicu iyc ol ihc iclcicncc vaiiallc
can lc assigncu io ihai iclcicncc. In
oihci woius, anyihing ihai e:erJ ihc
ucclaicu iclcicncc vaiiallc iyc can
lc n.reJ io ihc iclcicncc
vaiiallc. This Iets you do
things Iihe mohe poIymorphic
orroys.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 187

But waitl There's morel


You can have polymorphic
arguments and return types.
Il you can ucclaic a iclcicncc vaiiallc
ol a suciiyc, say, Animal, anu assign a
sulclass ol|cci io ii, say, Dog, ihinI ol how
ihai mighi woiI whcn ihc iclcicncc is an
aigumcni io a mcihou...
class Vet {
public void giveShot(Animal a) {
// do horrible things to the Animal at
// the other end of the `a' parameter
a.makeNoise();
}
}
class PetOwner {
public void start() {
Vet v = new Vet();
Dog d = new Dog();
Hippo h = new Hippo();
v.giveShot(d);
v.giveShot(h);
}
}
1- A--.| .-.--l-- :.- l.- AN/
A--.| l]- .: l- .-----l A- ---
l- /-l : --- - l- :-l, l l-||: l-
A--.| l- -.-N-:-|`, .- -.l--- A--.|
: --.||] --l l--- -- l- -., l.l':
--:- -.-N-:-|` --l- -|| ---
1- /-l': --l|` --l- :.- l.- .-]
A--.| ]-- - l A: |-- .: l- --:l
]-- .:: - .: l- .-----l : . :-:|.:: -
A--.|, l -|| ---
l-': -.-N-:-|` ---:
+-': -.-N-:-|` ---:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
188 chapter 7
MOW I gef ifl If I wrife
my code using poIymorphic orgumenfs,
where I decIore fhe mefhod poromefer os o
supercIoss fype, I con poss in ony subcIoss objecf of
runfime. CooI. 8ecouse fhof oIso meons I con wrife my
code, go on vocofion, ond someone eIse con odd new
subcIoss fypes fo fhe progrom ond my mefhods wiII
sfiII work... (fhe onIy downside is I'm jusf moking Iife
eosier for fhof idiof Jim).
expIoiting the power of poIymorphism
W| !h pe|ymerph|sm, yee rzn wr| !c re4c !hz! 4ecsn!
hzvc !e rhzn]c whcn yee |n!re4erc ncw se|r|zss
!ypcs |n!e !hc pre]rzm.
Rcmcmlci ihai Vci class. Il you wiiic ihai Vci class using
aigumcnis ucclaicu as iyc Ar.nI, youi couc can hanulc any
Animal ubIn. Thai mcans il oihcis wani io iaIc auvaniagc ol
youi Vci class, all ihcy havc io uo is maIc suic Le.. ncw Animal
iycs cxicnu class Animal. Thc Vci mcihous will siill woiI, cvcn
ihough ihc Vci class was wiiiicn wiihoui any Inowlcugc ol ihc
ncw Animal suliycs ihc Vci will lc woiIing on.
why is polymorphism guaranteed to work this wayI why is
it always safe to assume that any suocloss type will have the
methods you think you're calling on the suetcloss type (the
superclass reference type you're using the dot operator on)I
WWkm
Qw&W
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 189

Are there any practicaI Iimits


on the IeveIs of subcIassing! How
deep can you go!
|f you look in the 1ava AP|,
you'll see that most inheritance
hierarchies are wide but not deep.
Most are no more than one or two
levels deep, although there are
exceptions (especially in the GU|
classes). ou'll come to realize that
it usually makes more sense to keep
your inheritance trees shallow, but
there isn't a hard limit (well, not one
that you'd ever run into).
Hey, I just thought of
something... if you don't have
access to the source code for a cIass,
but you want to change the way a
method of that cIass works, couId
you use subcIassing to do that! 7o
extend the "bad" cIass and override
the method with your own better
code!
ep. That's one cool feature
of OO, and sometimes it saves you
from having to rewrite the class
from scratch, or track down the
programmer who hid the source code.

Can you extend nny cIass! Dr


is it Iike cIass members where if the
cIass is private you can't inherit it...
There's no such thing as a
private class, except in a very special
case called an |nnet class, that we
haven't looked at yet. 8ut there ote
three things that can prevent a class
from being subclassed.
The first is access control. Lven though
a class cont be marked private, a
class con be non-public (what you
get if you don't declare the class as
public). A non-public class can be
subclassed only by classes in the
same package as the class. Classes in
a different package won't be able to
subclass (or even use, for that matter)
the non-public class.
The second thing that stops a class
from being subclassed is the keyword
modifier hnal. A final class means
that it's the end of the inheritance
line. Nobody, ever, can extend a final
class.
The third issue is that if a class has
only private constructors (we'll
look at constructors in chapter 9), it
can't be subclassed.

Why wouId you ever want to


make a naI cIass! What advantage
wouId there be in preventing a cIass
from being subcIassed!
Typically, you won't make your
classes final. 8ut if you need security
the security of knowing that the
methods will always work the way
that you wrote them (because they
can't be overridden), a final class
will give you that. A lot of classes in
the 1ava AP| are final for that reason.
The String class, for example, is final
because, well, imagine the havoc if
somebody came along and changed
the way Strings behave!

Can you make a merheJ naI,


without making the whoIe clnss
naI!
|f you want to protect a specific
method from being overridden, mark
the methoJ with the hnalmodifier.
Mark the whole closs as final if you
want to guarantee that none of the
methods in that class will ever be
overridden.
(-,- a,- |
oa|| qa--(:|-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
190 chapter 7
Whcn you ovciiiuc a mcihou liom a suciclass, you`ic agiccing io
lulhll ihc coniiaci. Thc coniiaci ihai says, loi cxamlc, I iaIc no
aigumcnis anu I iciuin a loolcan." In oihci woius, ihc aigumcnis
anu iciuin iycs ol youi ovciiiuing mcihou musi looI io ihc ouisiuc
woilu e:nI, liIc ihc ovciiiuucn mcihou in ihc suciclass.
Thc mcthods ore thc contract.
Il olymoihism is going io woiI, ihc Toasici`s vcision ol ihc
ovciiiuucn mcihou liom Aliancc has io woiI ai iuniimc.
Rcmcmlci, ihc comilci looIs ai ihc iclcicncc iyc io ucciuc
whcihci you can call a aiiiculai mcihou on ihai iclcicncc. Wiih
an Aliancc iclcicncc io a Toasici, ihc comilci caics only il class
AI.nre has ihc mcihou you`ic invoIing on an Aliancc iclcicncc.
Bui ai iuniimc, ihc ]VM looIs noi ai ihc .ee.ere iyc Aliancc) lui
ai ihc aciual Tone. ol|cci on ihc hca. So il ihc comilci has alicauy
n.o.eJ ihc mcihou call, ihc only way ii can woiI is il ihc ovciiiuing
mcihou has ihc samc aigumcnis anu iciuin iycs. Oihciwisc,
somconc wiih an Aliancc iclcicncc will call iuinOn) as a no-
aig mcihou, cvcn ihough ihcic`s a vcision in Toasici ihai iaIcs an
ini. Which onc is callcu ai iuniimc. Thc onc in Aliancc. In oihci
woius, the turnOn)int IeveI; method in Tooster is not on override:
Kccp|n] !hc ren!rzr!: re|cs fer evcrr|4|n]
Toaster
ooo|ear lurr0r(|rl |eve|)
1
: : N61
.-
-----'
c.-'l :.-- l-
.-----l: - .-
----- --l-'
AppIiance
ooo|ear lurr0r()
ooo|ear lurr0ll()
1
Arguments must be the same, and return
types must be compatible.
The contract of superclass defnes how other code can use a method.
Whatever the superclass takes as an argument, the subclass over-
riding the method must use that same argument. And whatever the
superclass declares as a return type, the overriding method must de-
clare either the same type, or a subclass type. Remember, a subclass
object is guaranteed to be able to do anything its superclass declares,
so it's safe to return a subclass where the superclass is expected.
2
The method can't be less accessible.
That means the access level must be the same, or friendlier. That
means you can't, for example, override a public method and make
it private. What a shock that would be to the code invoking what it
thinks (at compile time) is a public method, if suddenly at runtime
the JVM slammed the door shut because the overriding version
called at runtime is private!
So far we've learned about two access levels: private and public.
The other two are in the deployment chapter (Release your Code)
and appendix B. There's also another rule about overriding related
to exception handling, but we'll wait until the chapter on exceptions
(Risky Behavior) to cover that.
1: : .:l-.||] . |-.|
---|6Al, -l --l .-
---|l!
Toaster
pr|vale ooo|ear lurr0r()
AppIiance
puo||c ooo|ear lurr0r()
puo||c ooo|ear lurr0r()
N61 |!6A|'
|l': --l . |-.|
----- -:.-:- ]--
--:l-:l- l- .::-::
|--| N-- : l . |-.|
---|6Al, -:.-:-
]-- -'l :.--
.-----l:
overriding methods
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 191
Mcihou ovciloauing is noihing moic ihan having
iwo mcihous wiih ihc samc namc lui uillcicni
aigumcni lisis. Pciiou. Thcic`s no olymoihism
involvcu wiih ovciloaucu mcihous!
Ovciloauing lcis you maIc muliilc vcisions
ol a mcihou, wiih uillcicni aigumcni lisis, loi
convcnicncc io ihc callcis. Ioi cxamlc, il you
havc a mcihou ihai iaIcs only an ini, ihc calling
couc has io convcii, say, a uoullc inio an ini
lcloic calling youi mcihou. Bui il you ovciloaucu
ihc mcihou wiih anoihci vcision ihai iaIcs a
uoullc, ihcn you`vc mauc ihings casici loi ihc
callci. You`ll scc moic ol ihis whcn wc looI inio
consiiuciois in ihc ol|cci lilccyclc chaici.
Sincc an ovciloauing mcihou isn`i iiying io
lulhll ihc olymoihism coniiaci uchncu ly iis
suciclass, ovciloaucu mcihous havc much moic
ucxililiiy.
0vcr|ez4|n] z mc!he4
1
The return types can be
different.
You're free to change the return types in
overloaded methods, as long as the argument lists
are different.
2
You can't change ONLY the
return type.
f only the return type is different, it's not a
valid overloadthe compiler will assume
you're trying to override the method. And even
that won't be legal unless the return type is
a subtype of the return type declared in the
superclass. To overload a method, you MUST
change the argument list, although you can
change the return type to anything.
3
You can vary the access
levels in any direction.
You're free to overload a method with a method
that's more restrictive. t doesn't matter, since the
new method isn't obligated to fulfll the contract of
the overloaded method.
public class Overloads {
String uniqueID;
public int addNums(int a, int b) {
return a + b;
}
public double addNums(double a, double b) {
return a + b;
}
public void setUniqueID(String theID) {
// lots of validation code, and then:
uniqueID = theID;
}
public void setUniqueID(int ssNumber) {
String numString = + ssNumber;
setUniqueID(numString);
}
}
Legal examples of method
overloading:
jn v]z]] ([] j,
ja,( z ]j||n( ([] ([z(
[zn, ( [zv ([ ,z
([] nz. ]( [z, n([jng
( ] wj([ jn[j(zne zn]
]y[j,. jn v]z]]
([] j, 0[ ([ ,z z,
zn vj]]n ([].
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
192 chapter 7
a = 6, 56
b = 5, ll
a = 5, 65
!hc pre]rzm:
A short 1ava program is listed below. One block of
the program is missing! our challenge is to match
the candidate block of code (on the left), with the
output that you'd 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.
rzn4|4z!c re4c
]ecs hcrc
|!hrcc ||ncsI
class A {
int ivar = 7,
void ml{| {
System.out.print{"A's ml, "|,
}
void m2{| {
System.out.print{"A's m2, "|,
}
void m3{| {
System.out.print{"A's m3, "|,
}
}
class B extends A {
void ml{| {
System.out.print{"B's ml, "|,
}
}
class C extends B {
void m3{| {
System.out.print{"C's m3, "+{ivar + 6||,
}
}
public class Mixed2 {
public static void main{String args| {
A a = new A{|,
B b = new B{|,
C c = new C{|,
A a2 = new C{|,
}
}
re4c
rzn4|4z!cs:
ee!pe!:
b.ml{|,
c.m2{|,
a.m3{|,
c.ml{|,
c.m2{|,
c.m3{|,
a.ml{|,
b.m2{|,
c.m3{|,
a2.ml{|,
a2.m2{|,
a2.m3{|,
A's ml, A's m2, C's m3, 6
B's ml, A's m2, A's m3,
A's ml, B's m2, A's m3,
B's ml, A's m2, C's m3, l3
B's ml, C's m2, A's m3,
B's ml, A's m2, C's m3, 6
A's ml, A's m2, C's m3, l3
}
}
}
}

exerc|se: H|xed Hessages


d
g
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
inheritance and poIymorphism
you are here 193
y[je[ | ([ j-@ zj, | ([], ]j,(] n ([ jg[(, j|
jn,(] jn( ([ e]z,,, n ([ ]|(, wa]] ej] zn]
]ae ([ a(a( ,[wn/ ([[ j ([] jn,(] jn(
e]z,, pn,(, ([ @ ([] jn,(] jn( e]z,, Vzj.)
] ge [omgj|e;
public class MonsterTestDrive {
public static void main{String args| {
Monster ma = new Monster3,
ma0 = new Vampire{|,
mal = new Dragon{|,
ma2 = new Monster{|,
for{int x = 0, x < 3, x++| {
max.frighten{x|,
}
}
}
class Monster {
}
class Vampire extends Monster {
}
class Dragon extends Monster {
boolean frighten{int degree| {
System.out.println{"breath re"|,
return true,
}
}
File Edit Window Help Sleep
% java TestArrays
island = Fiji
island = Cozumel
island = Bermuda
island = Azores
File Edit Window Help SaveYourself
% java MonsterTestDrive
a bite?
breath fire
arrrgh
boolean frighten{int d| {
System.out.println{"arrrgh"|,
return true,
}
boolean frighten{int x| {
System.out.println{"a bite?"|,
return false,
}
boolean frighten{int x| {
System.out.println{"arrrgh"|,
return true,
}
int frighten{int f| {
System.out.println{"a bite?"|,
return l,
}
boolean frighten{int x| {
System.out.println{"arrrgh"|,
return false,
}
boolean scare{int x| {
System.out.println{"a bite?"|,
return true,
}
boolean frighten{int z| {
System.out.println{"arrrgh"|,
return true,
}
boolean frighten{byte b| {
System.out.println{"a bite?"|,
return true,
}

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
194 chapter 7
Powboat
Sailboat
8oat
subclasses
int length
int bl
extends
stroke natasha
Testboats
drift
return
int len
public
int b2
private
hoist sail
continue
int b2
int b3
break
length
bl
b2
b3
len
move
rowThe8oat
setLength
getLength
String
int
void
static

our is to take code snippets from the pool and place them into
the blank lines in the code. ou may use the same snippet more
than once, and you might not need to use all the snippets. our
is to make a set of classes that will compile and run together
as a program. Don't be fooled - this one's harder than it looks.
public class Rowboat ________ ________ {
public ___________ rowTheBoat{| {
System.out.print{"stroke natasha"|,
}
}
public class ________ {
private int __________ ,
_______ void _________ { ______ | {
length = len,
}
public int getLength{| {
________ _________ ,
}
public ___________ move{| {
System.out.print{"___________"|,
}
}

public class TestBoats {
______ ______ _______ main{String args|{
_________ bl = new Boat{|,
Sailboat b2 = new __________{|,
Rowboat ________ = new Rowboat{|,
b2.setLength{32|,
bl.__________{|,
b3.__________{|,
_______.move{|,
}
}
public class __________ ________ Boat {
public _______ _________{| {
System.out.print{"___________"|,
}
}
drift drift hoist sail
puzzIe: PooI PuzzIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 195
re4c
rzn4|4z!cs:
ee!pe!:
b.ml{|,
c.m2{|,
a.m3{|,
c.ml{|,
c.m2{|,
c.m3{|,
a.ml{|,
b.m2{|,
c.m3{|,
a2.ml{|,
a2.m2{|,
a2.m3{|,
A's ml, A's m2, C's m3, 6
B's ml, A's m2, A's m3,
A's ml, B's m2, A's m3,
B's ml, A's m2, C's m3, l3
B's ml, C's m2, A's m3,
B's ml, A's m2, C's m3, 6
A's ml, A's m2, C's m3, l3
}
}
}
Sef I wiII work.
Set 2 will not compile because of Vampire's return
type (int).
The Vampire's frighten() method (B) is not a legal
override OR overload of Monster's frighten() method.
Changing ONLY the return type is not enough
to make a valid overload, and since an int is not
compatible with a boolean, the method is not a valid
override. (Remember, if you change ONLY the return
type, it must be to a return type that is compatible
with the superclass version's return type, and then it's
an over.
Sets 3 and 4 will compile, but produce:
arrrgh
breath re
arrrgh
Remember, class Vampire did not over class
Monster's frighten() method. (The frighten() method
in Vampire's set 4 takes o byfe, nof on inf.)
] ge [omgj|e;
d
g
]e;ejze
o|ajoz
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
196 chapter 7
public class Rowboat exfends 8oof {
public void rowTheBoat{| {
System.out.print{"stroke natasha"|,
}
}
public class 8oof {
private int Iengfh ,
pubIic void sefLengfh { inf Ien | {
length = len,
}
public int getLength{| {
refurn Iengfh ,
}
public void move{| {
System.out.print{"driff "|,
}
}
public class TestBoats {
pubIic sfofic void main{String args|{
8oof bl = new Boat{|,
Sailboat b2 = new SoiIboof{|,
Rowboat b3 = new Rowboat{|,
b2.setLength{32|,
bl.move{|,
b3.move{|,
bZ.move{|,
}
}
public class SoiIboof exfends Boat {
public void move{| {
System.out.print{"hoisf soiI "|,
}
}
drift drift hoist sail
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 197
8 interfaces and abstract cIasses
Inheritance is just the beginning. To exploit polymorphism, we need interfaces
(and not the GU| kind). we need to go beyond simple inheritance to a level of flexibility and
extensibility you can get only by designing and coding to interface specifications. Some of the
coolest parts of 1ava wouldn't even be possible without interfaces, so even if you don't design
with them yourself, you still have to use them. 8ut you'll to design with them. ou'll
to design with them. Yeull wenJer hew yeu ever liveJ wirheur rhem. what's an interfaceI |t's
a l00% abstract class. what's an abstract classI |t's a class that can't be instantiated. what's that
good forI ou'll see in |ust a few moments. 8ut if you think about the end of the last chapter,
and how we used polymorphic arguments so that a single vet method could take Animal
subclasses of all types, well, that was |ust scratching the surface. |nterfaces are the ely in
polymorphism. The nb in abstract. The cnIIeine in 1ava.
8erious Polymorphism
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
198 chapter 8

FeIine
roam()
Canine
size
picture
food
prey
Lion
size
picture
food
prey
Tiger
size
picture
food
prey
Cat
size
picture
food
prey
WoIf
size
picture
food
prey
Dog
size
picture
food
prey
Hippo
makeNoise()
eat()
roam()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
picture
food
hunger
boundaries
location
makeNoise()
eat()
sleep()
roam()
designing with inheritance
P|4 wc fer]c! z|ee! semc!h|n]
whcn wc 4cs|]nc4 !h|s!
Thc class siiuciuic isn`i ioo lau. Wc`vc ucsigncu
ii so ihai uulicaic couc is Ici io a minimum,
anu wc`vc ovciiiuucn ihc mcihous ihai wc ihinI
shoulu havc sulclass-sccihc imlcmcniaiions.
Wc`vc mauc ii nicc anu ucxillc liom a
olymoihic ciscciivc, lccausc wc can ucsign
Animal-using iogiams wiih Animal aigumcnis
anu aiiay ucclaiaiions), so ihai any Animal
suliyc-incIuding those we never imogined ot the
time we wrote our code-can lc asscu in anu uscu
ai iuniimc. Wc`vc ui ihc common ioiocol loi
all Animals ihc loui mcihous ihai wc wani ihc
woilu io Inow all Animals havc) in ihc Animal
suciclass, anu wc`ic icauy io siaii maIing ncw
Iions anu Tigcis anu Hios.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 199
Wolf aWolf = new Wolf();
We know we can say:
A w-| ------:- l- .
w-| --:l WoIf
eWell

W
o
If
obj
e
c
f

1-:- l-- .-- l- :.-- l]-
Animal aHippo = new Hippo();
And we know we can say:
A--.| ------:- l-
. +- --:l
AnimoI
ehijje
H
i
p
p
o
obj
e
c
f

1-:- l-- .-- N61 l- :.-- l]-
Animal anim = new Animal();
But here's where it gets weird:
A--.| ------:- l-
.- A--.| --:l
AnimoI
erim
A
n
i
m
oI ob
j
e
c
f

1-:- l-- .-- l- :.-- l]-, -l
-.l l- -: --: .- A--.| --:l |-- |-

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
200 chapter 8
,ezy je(,
What does a new Animal{} ob]ect
look like?
when objects go bad
Ii maIcs scnsc io cicaic a Woll ol|cci oi a Hio
ol|cci oi a Tigci ol|cci, lui whai cxacily . an
Animal ol|cci. Whai shac is ii. Whai coloi, sizc,
numlci ol lcgs...
Tiying io cicaic an ol|cci ol iyc Animal is liIc a
nightmarc Star Trck transportcr accidcnt. Thc
onc whcic somcwhcic in ihc lcam-mc--u ioccss
somcihing lau hacncu io ihc lullci.
Bui how uo wc ucal wiih ihis. Wc reeJ an Animal
class, loi inhciiiancc anu olymoihism. Bui wc
wani iogiammcis io insianiiaic only ihc lcss
alsiiaci ubIne ol class Animal, noi Animal iiscll.
Wc wani Tigci ol|ccis anu Iion ol|ccis, not AnimoI
objects.
Ioiiunaicly, ihcic`s a simlc way io icvcni a class
liom cvci lcing insianiiaicu. In oihci woius, io sio
anyonc liom saying new" on ihai iyc. By maiIing
ihc class as abstract, ihc comilci will sio any
couc, anywhcic, liom cvci cicaiing an insiancc ol
ihai iyc.
You can siill usc ihai alsiiaci iyc as a iclcicncc iyc.
In laci,ihai`s a lig aii ol why you havc ihai alsiiaci
class in ihc hisi lacc io usc ii as a olymoihic
aigumcni oi iciuin iyc, oi io maIc a olymoihic
aiiay).
Whcn you`ic ucsigning youi class inhciiiancc
siiuciuic, you havc io ucciuc which classcs aic
nb.n anu which aic or.ee. Concicic classcs aic
ihosc ihai aic sccihc cnough io lc insianiiaicu. A
or.ee class |usi mcans ihai ii`s OK io maIc ol|ccis
ol ihai iyc.
MaIing a class alsiiaci is casy-ui ihc Icywoiu
abstract lcloic ihc class ucclaiaiion:
abstract class Canine extends Animal {
public void roam() { }
}
What are the instance variable values?
8ome classes ]ust should not be
instantiatedl
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 201
Ihc remp||cr wen! |c! yee |ns!zn!|z!c
zn z|s!rzr! r|zss
An alsiiaci class mcans ihai nolouy can cvci maIc a ncw
insiancc ol ihai class. You can siill usc ihai alsiiaci class as a
ucclaicu iclcicncc iyc, loi ihc uiosc ol olymoihism, lui
you uon`i havc io woiiy aloui somclouy maIing ol|ccis ol ihai
iyc. Thc comilci un.nree ii.
abstract public class Canine extends Animal
{
public void roam() { }
}
public class MakeCanine {
public void go() {
Canine c;
c = new Dog();
c = new Canine();
c.roam();
}
}
File Edit Window Help BeamMeUp
% javac MakeCanine.java
MakeCanine.java:5: Canine is abstract;
cannot be instantiated
c = new Canine();
^
1 error
:|.:: c.--- : -.-- .:l-.:l,
:- l- :--|-- -|| N61
|-l ]-- - l:
An abstract class has virtually* no use, no value, no
purpose in life, unless it is extended.
With an abstract class, the guys doing the work at runtime
are instances of a subclass of your abstract class.
1
: : 6r, -:.-:- ]-- :.- .|-.]: .::-
. :-:|.:: --:l l- . :---:|.:: ------:-,
--- l- :---:|.:: : .:l-.:l
1--- : .- -:-l-- l- l:-.- .:l-.:l :|.:: :.-
.- :l.l: -----: |:-- :.l-- |o`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
202 chapter 8
|s!rzr! vs. 0enrrc!c
A class ihai`s noi alsiiaci is callcu
a or.ee class. In ihc Animal
inhciiiancc iicc, il wc maIc
Animal, Caninc, anu Iclinc
alsiiaci, ihai lcavcs Hio, Woll,
Dog, Tigci, Iion, anu Cai as ihc
concicic sulclasscs.
Ili ihiough ihc ]ava API anu
you`ll hnu a loi ol alsiiaci classcs,
csccially in ihc GUI liliaiy. Whai
uocs a GUI Comoncni looI
liIc. Thc Comoncni class is ihc
suciclass ol GUI-iclaicu classcs
loi ihings liIc luiions, icxi aicas,
sciolllais, uialog loxcs, you namc
ii. You uon`i maIc an insiancc ol
a gcnciic Coorer anu ui ii on
ihc sciccn, you maIc a ]Buiion. In
oihci woius, you insianiiaic only a
or.ee ubIn ol Comoncni, lui
ncvci Comoncni iiscll.
Tiger
Animal
Canine
.:l-.:l
.:l-.:l
.:l-.:l
Hippo
:--:--l-
Dog
WoIf
:--:--l-
Cat
Lion
:--:--l-
Hmmmm... do I
feeI Iike red or
whife fonighf7
Hmmmm... fhe ComeIof
Vineyords I997 Pinof
Moir wos o preffy
decenf yeor...
How do you know when a class should be
abstractI wine is probably abstract. 8ut what
about ReJ and whireI Again probably abstract
(for some of us, anyway). 8ut at what point in the
hierarchy do things become concreteI
Do you make PinerNeir concrete, or is it abstract
tooI |t looks like the Camelot vineyards l997
Pinot Noir is probably concrete no matter what.
8ut how do you know for sureI
Look at the Animal inheritance tree above. Do the
choices we've made for which classes are abstract
and which are concrete seem appropriateI
would you change anything about the Animal
inheritance tree (other than adding more Animals,
of course)I
abstract or concrete?
:--:--l-
:--:--l-
abstract and concrete cIasses
FeIine
:--:--l-
WWkm
Qw&W
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
interfaces and poIymorphism
you are here 203
|s!rzr! mc!he4s
Bcsiucs classcs, you can maiI eLoJ alsiiaci, ioo. An alsiiaci
class mcans ihc class musi lc e:erJeJ, an alsiiaci mcihou mcans
ihc mcihou musi lc o.e...JJer. You mighi ucciuc ihai somc oi all)
lchaviois in an alsiiaci class uon`i maIc any scnsc unlcss ihcy`ic
imlcmcnicu ly a moic sccihc sulclass. In oihci woius, you can`i
ihinI ol any gcnciic mcihou imlcmcniaiion ihai coulu ossilly lc
usclul loi sulclasscs. Whai woulu a gcnciic en() mcihou looI liIc.
An abstract method has no bodyl
Bccausc you`vc alicauy ucciucu ihcic isn`i any couc ihai woulu maIc
scnsc in ihc alsiiaci mcihou, you won`i ui in a mcihou louy. So no
cuily liaccs- |usi cnu ihc ucclaiaiion wiih a scmicolon.
public abstract void eat();
N- --l- -]'
!- l -l . :--:-|--
f you declare an abstract method, you MU8T
mark the class abstract as well. You can't have
an abstract method in a non-abstract class.
Il you ui cvcn a singlc alsiiaci mcihou in a class, you havc io
maIc ihc class alsiiaci. Bui you nr mix loih alsiiaci anu non-
alsiiaci mcihous in ihc alsiiaci class.
What is the of an abstract method! I thought
the whoIe point of an abstract cIass was to have common
code that couId be inherited by subcIasses.
|nheritable method implementations (in other words,
methods with actual ooJ|es) are A Good Thing to put in a
superclass. when |t moles sense. And in an abstract class, it
often Joesnt make sense, because you can't come up with
any generic code that subclasses would find useful. The
point of an abstract method is that even though you haven't
put in any actual method code, you've still defined part of
the totocol for a group of subtypes (subclasses).
Which is good because...
Polymorphism! Pemember, what you want is the
ability to use a superclass type (often abstract) as a method
argument, return type, or array type. That way, you get to
add new subtypes (like a new Animal subclass) to your
program without having to rewrite (or add) new methods
to deal with those new types. |magine how you'd have to
change the vet class, if it didn't use Animal as its argument
type for methods. ou'd have to have a separate method
for every single Animal subclass! One that takes a Lion, one
that takes a wolf, one that takes a... you get the idea. So with
an abstract method, you're saying, "All subtypes of this type
have TH|S method. for the benefit of polymorphism.
(-,- a,- |
oa|| qa--(:|-
If reoIIy sucks fo
be on obsfrocf mefhod.
You don'f hove o body.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
204 chapter 8
you must impIement abstract methods
Yee M08I |mp|cmcn! z|| z|s!rzr! mc!he4s
Alsiiaci mcihous uon`i havc a louy, ihcy cxisi solcly loi olymoihism. Thai
mcans ihc hisi concicic class in ihc inhciiiancc iicc musi imlcmcni nII alsiiaci
mcihous.
You can, howcvci, ass ihc lucI ly lcing alsiiaci youiscll. Il loih Animal anu
Caninc aic alsiiaci, loi cxamlc, anu loih havc alsiiaci mcihous, class Caninc
uocs noi havc io imlcmcni ihc alsiiaci mcihous liom Animal. Bui as soon as wc
gci io ihc hisi concicic sulclass, liIc Dog, ihai sulclass musi imlcmcni nII ol ihc
alsiiaci mcihous liom loih Animal anu Caninc.
Bui icmcmlci ihai an alsiiaci class can havc loih alsiiaci anu ror-alsiiaci
mcihous, so Caninc, loi cxamlc, coulu imlcmcni an alsiiaci mcihou liom
Animal, so ihai Dog uiun`i havc io. Bui il Caninc says noihing aloui ihc alsiiaci
mcihous liom Animal, Dog has io imlcmcni all ol Animal`s alsiiaci mcihous.
mplementing an abstract
method is ]ust like
overriding a method.
Whcn wc say you musi imlcmcni ihc alsiiaci mcihou", ihai mcans you u
.o..Je n boJ,. Thai mcans you musi cicaic a non-alsiiaci mcihou in youi class
wiih ihc samc mcihou signaiuic namc anu aigumcnis) anu a iciuin iyc ihai is
comaiillc wiih ihc ucclaicu iciuin iyc ol ihc alsiiaci mcihou. Whai you ui .r
ihai mcihou is u io you. All ]ava caics aloui is ihai ihc mcihou is Le.e, in youi
concicic sulclass.
I hove wonderfuI news,
mofher. Joe fnoIIy impIemenfed
oII his obsfrocf mefhodsl Mow
everyfhing is working jusf fhe
woy we pIonned...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 205
+,-+ :+ ,-+:.|
Let's put all this abstract rhetoric into some concrete use. |n the middle
column we've listed some classes. our |ob is to imagine applications
where the listed class might be concrete, and applications where the listed
class might be abstract. we took a shot at the rst few to get you going.
Por example, class Tree would be abstract in a tree nursery program, where
differences between an Oak and an Aspen matter. 8ut in a golf simulation
program, Tree might be a concrete class (perhaps a subclass of Obstacle),
because the program doesn't care about or distinguish between different
types of trees. (There's no one right answer, it depends on your design.)
Concrete SampIe cIass Abstract
]e|f reersc s|me|z!|en Tree !rcc nerscry zpp||rz!|en
____________________ House zrrh| !cr! zpp||rz!|en
sz!c||| !c phe!e zpp||rz!|en Town _____________________
____________________ Pootball Player rezrh|n] zpp||rz!|en
____________________ Chair _____________________
____________________ Customer _____________________
____________________ Sales Order _____________________
____________________ 8ook _____________________
____________________ Store _____________________
____________________ Supplier _____________________
____________________ Golf Club _____________________
____________________ Carburetor _____________________
____________________ Oven _____________________
Abstract vs. Concrete CIasses
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
206 chapter 8
poIymorphism exampIes
|e|ymerph|sm |n zr!|en
Ici`s say ihai wc wani io wiiic oui owr Iinu ol lisi class, onc ihai will holu
Dog ol|ccis, lui icicnu loi a momcni ihai wc uon`i Inow aloui ihc
AiiayIisi class. Ioi ihc hisi ass, wc`ll givc ii |usi an nJJ() mcihou. Wc`ll usc
a simlc Dog aiiay Dog ]|) io Icc ihc auucu Dog ol|ccis, anu givc ii a
lcngih ol . Whcn wc icach ihc limii ol Dog ol|ccis, you can siill call ihc
nJJ() mcihou lui ii won`i uo anyihing. Il wc`ic ro ai ihc limii, ihc nJJ()
mcihou uis ihc Dog in ihc aiiay ai ihc ncxi availallc inucx osiiion, ihcn
incicmcnis ihai ncxi availallc inucx ncxiInucx).
public class MyDogList {
private Dog [] dogs = new Dog[5];
private int nextIndex = 0;

public void add(Dog d) {
if (nextIndex < dogs.length) {
dogs[nextIndex] = d;
System.out.println(Dog added at + nextIndex);
nextIndex++;
}
}
}
Hy0ogL|st
0o[| dos
|rl rexllrdex
add(0o d)
c:- . |.- -| l- .--.]
-- l- ::---:
w-'|| -:-----l l: -.:
l-- . --- l- : .-
| --'-- --l .|--.] .l l- |-l
- l- -: .--.], . l- l-
.- --l . --::.-
-:-----l, l- - -: l-
--l -- l- -:-
Building our own Dog-specihc list
(Perhaps the worId's worst attempt at making our
own ArrayList kind of cIass, from scratch.)

1
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 207
public class MyAnimalList {
private Animal[] animals = new Animal[5];
private int nextIndex = 0;

public void add(Animal a) {
if (nextIndex < animals.length) {
animals[nextIndex] = a;
System.out.println(Animal added at + nextIndex);
nextIndex++;

}
}
}
HyAn|ma|L|st
An|ma|[j ar|ra|s
|rl rexllrdex
add(An|ma| a)
Building our own Animal-specihc list

2
0h-eh, new wc ncc4 !e kccp 0z!s, !ee.
Wc havc a lcw oiions hcic:
1) MaIc a scaiaic class, MyCaiIisi, io holu Cai ol|ccis. Piciiy clunIy.
2) MaIc a singlc class, DogAnuCaiIisi, ihai Iccs iwo uillcicni aiiays as insiancc
vaiiallcs anu has iwo uillcicni auu) mcihous: auuCaiCai c) anu auuDogDog
u). Anoihci clunIy soluiion.
S) MaIc hciciogcncous AnimalIisi class, ihai iaIcs nr, Iinu ol Animal sulclass
sincc wc Inow ihai il ihc scc changcu io auu Cais, soonci oi laici wc`ll havc
somc oLe. Iinu ol animal auucu as wcll). Wc liIc ihis oiion lcsi, so lci`s changc
oui class io maIc ii moic gcnciic, io iaIc Animals insicau ol |usi Dogs. Wc`vc
highlighicu ihc Icy changcs ihc logic is ihc samc, ol couisc, lui ihc iyc has
changcu liom Dog io Animal cvciywhcic in ihc couc.
public class AnimalTestDrive{
public static void main (String[] args) {
MyAnimalList list = new MyAnimalList();
Dog a = new Dog();
Cat c = new Cat();
list.add(a);
list.add(c);
}
}

File Edit Window Help Harm
% java AnimalTestDrive
Animal added at 0
Animal added at 1
l--'l .-: w-'-- --l -.- .
--- A--.| --:l. --'-- -.- .
--- .--.] --:l, - l]- A--.|
|------, ]-- :.---l -.- . ---
-:l.-:- - .- .:l-.:l l]-, -l
]-- cAN -.- .- .--.] --:l
-:|.-- l- +6|l l.l l]-`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
208 chapter 8
You Inow whcic ihis is hcauing. Wc wani io changc ihc
iyc ol ihc aiiay, along wiih ihc nJJ() mcihou aigumcni, io
somcihing nbo.e Animal. Somcihing cvcn o.e gcnciic, o.e
alsiiaci ihan Animal. Bui how can wc uo ii. Wc uon`i Ln.e a
suciclass loi Animal.
Thcn again, maylc wc uo...
Rcmcmlci ihosc mcihous ol AiiayIisi.
IooI how ihc icmovc, coniains, anu
inucxOl mcihou all usc an ol|cci ol iyc...
Object:
Every class in Java extends
class Ob]ect.
Class Ol|cci is ihc moihci ol all classcs, ii`s
ihc suciclass ol e.e.,L.r.
v
e
rsio
n
3
Whz! z|ee! nen-n|mz|s! Why ne! mzkc
z r|zss ]cncr|r cnee]h !e !zkc zny!h|n]!
M.-] - l- A--.]|:l --l-: -:- l-
-|l-.l- -|]---: l]-, 6-:l -:-
---] :|.:: - ).. : . :-:|.:: - 6-:l,
l-:- A--.]|:l --l-: :.- l.- .-]l-'
|N-l- .: - ).. -o, l- -l|` .- .|`
--l-: .:l-.||] |-- . |ll|- ----l
l.- l- ---: :--- ---, -l -- --- l:
: l- -.] l- l- .--l l w-'|| -l -l-
l- -|| :l--] . |ll|- |.l--`
the uItimate supercIass: Object
ArrayList
|1-:- .-- -:l . -- - l-
--l-: - A--.]|:ll---
.-- -.-] ----`
Evcn il you iaIc auvaniagc ol olymoihism,
you siill havc io cicaic a class wiih mcihous
ihai iaIc anu iciuin ,ou. olymoihic iyc.
Wiihoui a common suciclass loi cvciyihing
in ]ava, ihcic`u lc no way loi ihc ucvclocis
ol ]ava io cicaic classcs wiih mcihous ihai
coulu iaIc ,ou. cusiom iycs... ,e Le, re.e.
Irew nbou wLer Le, w.oe Le A..n,1. In.
So you wcic maIing sulclasscs ol class Ol|cci
liom ihc vciy lcginning anu you uiun`i cvcn
Inow ii. Every cIoss you write extends Object,
wiihoui youi cvci having io say ii. Bui you can
ihinI ol ii as ihough a class you wiiic looIs liIc
ihis:
public class Dog extends Object { }
Bui waii a minuic, Dog nI.enJ, cxicnus somcihing, Cnr.re.
Thai`s OK. Thc comilci will maIc Cnr.re cxicnu Ol|cci
insicau. Excci Cnr.re cxicnus Animal. No iollcm, ihcn ihc
comilci will |usi maIc Ar.nI cxicnu Ol|cci.
Any class that doesn't explicitly extend another
class, implicitly extends Ob]ect.
So, sincc Dog cxicnus Caninc, ii uocsn`i J..eI, cxicnu Ol|cci
alihough ii uocs cxicnu ii inuiiccily), anu ihc samc is iiuc
loi Caninc, lui Animal Joe uiiccily cxicnu Ol|cci.
Pemoves the ob|ect at the index parameter. Peturns
'true' if the element was in the list.
Peturns 'true' if there's a match for the ob|ect parameter.
Peturns 'true' if the list has no elements.
Peturns either the index of the ob|ect parameter, or -l.
Peturns the element at this position in the list.
Adds the element to the list (returns 'true').
booIean remove(Dbject eIem)
booIean contains(Dbject eIem)
booIean ismpty()
int indexDf(Dbject eIem)
Dbject get(int index)
booIean add(Dbject eIem)
// more
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 209
8e whz!s |n !h|s e| !rz-sepcr-mc]zr|zss 0|jcr!!
0bject
ooo|ear equa|s()
C|ass elC|ass()
|rl |as|Code()
3lr|r lo3lr|r()
Il you wcic ]ava, whai lchavioi woulu you wani
ol|cci io havc. Hmmmm... lci`s scc... how aloui a
mcihou ihai lcis you hnu oui il onc ol|cci is cqual
io anoihci ol|cci. Whai aloui a mcihou ihai can
icll you ihc aciual class iyc ol ihai ol|cci. Maylc a
mcihou ihai givcs you a hashcouc loi ihc ol|cci, so
you can usc ihc ol|cci in hashiallcs wc`ll ialI aloui
]ava`s hashiallcs in chaici 17 anu acnuix B).
Oh, hcic`s a goou onc-a mcihou ihai iinis oui a
Siiing mcssagc loi ihai ol|cci.
Anu whai uo you Inow. As il ly magic, class Ol|cci
uocs inuccu havc mcihous loi ihosc loui ihings.
Thai`s noi all, ihough, lui ihcsc aic ihc oncs wc
ically caic aloui.
)-:l 6M! - l- --l-:
- :|.:: 6-:l
Dog a = new Dog();
Cat c = new Cat();

if (a.equals(c)) {
System.out.println(true);
} else {
System.out.println(false);
}
equals{Ob]ect o} 1
Cat c = new Cat();
System.out.println(c.getClass());
getClass{} 2
File Edit Window Help Stop
% java TestObject
false
File Edit Window Help Faint
% java TestObject
class Cat
Cat c = new Cat();
System.out.println(c.hashCode());
hashCode{} 3
File Edit Window Help Drop
% java TestObject
8202111
Cat c = new Cat();
System.out.println(c.toString());
to8tring{} 4
File Edit Window Help LapsentoComa
% java TestObject
Cat@7d277f
|--l: --l . .::--
-- l- --:l |--
---, l- - l .: .
---- |l`
1-||: ]-- l-- --:l: .--
:--:--- '--.|' |--'|| l.|
.--l -.l '--.|' --.||]
--.-: - .-- B`
6-: ]-- .: l-
:|.:: l.l --:l -.:
-:l.-l.l- ---
|--l: --l . l-- --::.-
-l l- -.-- - l- :|.::
.- :--- -l-- ----- --
-.--|] :.-- .--l
Your6|asshere !--] :|.:: ]-- --l- ---l: .|| l-
--l-: - :|.:: 6-:l 1- :|.::-:
]--'- --ll-- ---l- --l-: ]--
-'l --- --- ]-- .
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
210 chapter 8
(-,- a,- |
oa|| qa--(:|-
Is cIass Dbject abstract!
No. well, not in the formal
1ava sense anyway. Ob|ect is a
non-abstract class because it's
got method implementation
code that all classes can inherit
and use out-of-the-box, without
having to override the methods.
7hen cnn you override
the methods in Dbject!
Some of them. 8ut some of
them are marked , which
means you can't override them.
ou're encouraged (strongly) to
override hashCode(), equals(),
and toString() in your own
classes, and you'll learn how to
do that a little later in the book.
8ut some of the methods, like
getClass(), do things that must
work in a specific, guaranteed
way.
If ArrayList methods are
generic enough to use Dbject,
then what does it mean to say
ArrayList<DotCom>! I thought
I was restricting the ArrayList to
hoId onIy DotCom objects!
ou wete restricting it.
Prior to 1ava 5.0, ArrayLists
couldn't be restricted. They
were all essentially what you
get in 1ava 5.0 today if you write
ArrayList<Ob|ect>. |n other
words, nn ArrnyLisr resrricreJ
re nnyrhing rhnrs nn 0bjecr,
which means ony ob|ect in 1ava,
instantiated from ony class type!
we'll cover the details of this new
<type> syntax later in the book.
Dk, back to cIass Dbject
being non-abstract (so I guess
that means it's concrete), HDW
can you Iet somebody make an
Dbject object! Isn't that just
as weird as making an AnimaI
object!
Good question! why is
it acceptable to make a new
Ob|ect instanceI 8ecause
sometimes you |ust want a
generic ob|ect to use as, well, as
an ob|ect. A l|htwe|ht ob|ect.
8y far, the most common use of
an instance of type Ob|ect is for
thread synchronization (which
you'll learn about in chapter l5).
Por now, |ust stick that on the
back burner and assume that
you will rarely make ob|ects of
type Ob|ect, even though you
con.

So is it fair to say that the


main purpose for type Dbject
is so that you can use it for a
poIymorphic argument and
return type! Like in ArrayList!
The Ob|ect class serves
two main purposes: to act as a
polymorphic type for methods
that need to work on any class
that you or anyone else makes,
and to provide teol method code
that all ob|ects in 1ava need at
runtime (and putting them in
class Ob|ect means all other
classes inherit them). Some of
the most important methods in
Ob|ect are related to threads,
and we'll see those later in the
book.

If it's so good to use


poIymorphic types, why
don't you just make ALL your
methods take and return type
Dbject!
Ahhhh... think about what
would happen. Por one thing,
you would defeat the whole
point of 'type-safety', one
of 1ava's greatest protection
mechanisms for your code. with
type-safety, 1ava guarantees that
you won't ask the wrong ob|ect
to do something you meont to
ask of another ob|ect type. Like,
ask a lettot| (which you think is a
7oostet) to cool |tsell.
8ut the truth is, you Jont have
to worry about that fiery Perrari
scenario, even if you Jo use
Ob|ect references for everything.
8ecause when ob|ects are
referred to by an Ob|ect
reference type, 1ava th|nls it's
referring to an instance of type
Ob|ect. And that means the
only methods you're allowed to
call on that ob|ect are the ones
declared in class Ob|ect! So if
you were to say:
Object o = new Ferrari();
o.goFast(); //Not legal!
ou wouldn't even make it past
the compiler.
8ecause 1ava is a strongly-typed
language, the compiler checks
to make sure that you're calling
a method on an ob|ect that's
actually capable of tesonJ|n.
|n other words, you can call a
method on an ob|ect reference
only if the class of the reference
type actually hos the method.
we'll cover this in much greater
detail a little later, so don't worry
if the picture isn't crystal clear.
Object and abstract cIasses
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 211
Bcloic you iun oll anu siaii using iyc Ol|cci loi all youi uliia-ucxillc aigumcni anu iciuin
iycs, you nccu io consiuci a liiilc issuc ol using iyc Ol|cci as a iclcicncc. Anu Icc in minu
ihai wc`ic noi ialIing aloui maIing insianccs ol iyc Ol|cci, wc`ic ialIing aloui maIing
insianccs ol somc oihci iyc, lui using a iclcicncc ol iyc Ol|cci.
Whcn you ui an ol|cci inio an AiiayIisi<Dog>, ii gocs in as a Dog, anu comcs oui as a Dog:
ArrayList<Dog> myDogArrayList = new ArrayList<Dog>();
Dog aDog = new Dog();
myDogArrayList.add(aDog);
Dog d = myDogArrayList.get(0);
Bui whai hacns whcn you ucclaic ii as AiiayIisi<Objcct>. Il you wani io maIc an AiiayIisi
ihai will liicially iaIc Iinu ol Ol|cci, you ucclaic ii liIc ihis:
ArrayList<Object> myDogArrayList = new ArrayList<Object>();
Dog aDog = new Dog();
myDogArrayList.add(aDog);
Bui whai hacns whcn you iiy io gci ihc Dog ol|cci anu assign ii io a Dog iclcicncc.
Dog d = myDogArrayList.get(0);
Everything comes out o[ on ArroyList<Object> os o re[erence o[ type Object, regordIess o[ whot the
octuoI object is, or whot the re[erence type wos when you odded the object to the Iist.
0s|n] pe|ymerph|r rcfcrcnrcs ef !ypc 0|jcr! hzs z pr|rc...
Ob]ects come out of
an ArrayList<Ob]ect>
acting like they're
generic instances
of class Ob]ect. The
Compiler cannot
assume the ob]ect
that comes out is of
any type other than
Ob]ect.
ArrayList<Ob]ect>
The objects go IN
as 8occerBall,
Fish, Guitar, and
Car.
Ob]ect Ob]ect Ob]ect Ob]ect
M.- .- A--.]|:l -:|.--
l- -| l- --:l:
M.- . l-
A l- l- l- l- |:l
A::- l- l- --- l- |:l l- . --- l- ------:- .-.|-
|1- - l .: l-- l- -l|` --l- -:|.--: . l- --l---
l]- -:.-:- ]-- -:- A--.]|:ll-`
M.- .- A--.]|:l -:|.--
l- -| .-] l]- - 6-:l
M.- . l-
A l- l- l- l- |:l
|1-:- l-- :l-: .-- l- :.--`
N6'' w--'l :--|-'' w-- ]-- -:- A--.]|:l6-:l, l- -l|` --l-
--l---: l]- 6-:l 1- c--|-- ---: --|] l.l l- --:l ---l: ---
6-:l |:------- - l: ---l.-:- l---` -l l --:-'l --- l': . l- ''
d = m d = myD = m
But they come
OUT as though
they were of type
Ob]ect.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
212 chapter 8
public void go() {
Dog aDog = new Dog();
Object sameDog = getObject(aDog);
}
public Object getObject(Object o) {
return o;
}
public void go() {
Dog aDog = new Dog();
Dog sameDog = getObject(aDog);
}
public Object getObject(Object o) {
return o;
}
Thc iollcm wiih having cvciyihing iicaicu
olymoihically as an Ol|cci is ihai ihc ol|ccis
nen. io losc lui noi cimancnily) ihcii
iiuc csscncc. TLe Do nen. o Ioe . Jore.
Ici`s scc whai hacns whcn wc ass a Dog io
a mcihou ihai iciuins a iclcicncc io ihc samc
Dog ol|cci, lui ucclaics ihc iciuin iyc as iyc
Ol|cci iaihci ihan Dog.
Whcn z Pe] wen! zr! ||kc z Pe]
1
: |-- ---'l ---' !-- l-- l- --l-
--l---- . ------:- l- l- --] :.-- l
- l-
.-----l ------ l-, l- --l--- l]- 6-:l
--.-: l- :--|-- ---'l |-l ]-- .::- l- --l----
------:- l- .-]l- -l 6-:l
File Edit Window Help Remember
DogPolyTest.java:10: incompatible types
found : java.lang.Object
required: Dog
Dog sameDog = takeObjects(aDog);
1 error ^
1- :--|-- --:-'l --- l.l l-
l- --l---- --- l- --l- :
.:l-.||] . l-, :- l ---'l |-l ]--
.::- l l- . l- ------:- |/--'||
:-- -] -- l- --l .-`
BAl
1: ---: |.|l-- l -.] --l - --]
-:--|, .: ]--'|| :-- - . -----l` -:.-:- ]--
:.- .::- AN/1+|N6 l- . ------:- - l]-
6-:l, :-:- ---] :|.:: .::-: l- |~A l-:l
-- 6-:l !--] --:l - ).. : .- -:l.-:-
- l]- 6-:l, -:.-:- ---] :|.:: - ).. .:
6-:l .l l- l- - l: ---l.-:- l---
666l

I don'f know whof you're


foIking obouf. Sif7 Sfoy7
bork7 Hmmmm... I don'f
recoII knowing fhose.
When a Dog Ioses its Dogness
= = g = g = g
w-'-- --l---- . ------:- l- l- :.-- l-, -l .: .
--l--- l]- - 6-:l 1: .-l : ---:l|] |-.| N-l-
l: : :-|.- l- -- l- -l|` --l- ---: --- ]-- .-
.- A--.]|:l6-:l -.l-- l.- .- A--.]|:ll-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
interfaces and poIymorphism
you are here 213
So now wc Inow ihai whcn an ol|cci is
iclcicnccu ly a vaiiallc ucclaicu as iyc
Ol|cci, ii can`i lc assigncu io a vaiiallc
ucclaicu wiih ihc aciual ol|cci`s iyc.
Anu wc Inow ihai ihis can hacn whcn
a iciuin iyc oi aigumcni is ucclaicu
as iyc Ol|cci, as woulu lc ihc casc,
loi cxamlc, whcn ihc ol|cci is ui
inio an AiiayIisi ol iyc Ol|cci using
AiiayIisiOl|cci>. Bui whai aic ihc
imlicaiions ol ihis. Is ii a iollcm io
havc io usc an Ol|cci iclcicncc vaiiallc
io iclci io a Dog ol|cci. Ici`s iiy io call
Dog mcihous on oui Dog-Thai-Comilci-
ThinIs-Is-An-Ol|cci:
0|jcr!s 4en! |zrk.
Object o = al.get(index);
int i = o.hashCode();
o.bark();
1
: : -- c|.:: 6-:l .: .
.:c--|` --l-, :- ]-- :.- :.||
l.l --l- -- AN/
--:l - )..
c.-'l - l:'' 1- 6-:l :|.:: .: -- -. -.l
l --.-: l- .-|` !-- l-- /6c --- l':
--.||] . l- .l l.l --, l- :--|-- --:-'l
Objecf




D
o
g
ob
j
e
c
f
w-- ]-- -l .- --:l ------:- ---
.- A--.]|:l6-:l |-- .-] --l-
l.l -:|.--: 6-:l .: l- --l--- l]-`,
l :---: .: .: . -|]---: ------:-
l]- - 6-:l - ]-- .- .- 6-:l
------:- l- |- l: :.:-` . l- -:l.-:-
w--'l :--|-'
The compiler decides whether
you can call a method based
on the reference type, not the
actual ob]ect type.
Evcn il you Irow ihc ol|cci is caallc
...lui ii ically a Dog, honcsi..."), ihc
comilci sccs ii only as a gcnciic Ol|cci.
Ioi all ihc comilci Inows, you ui a
Buiion ol|cci oui ihcic. Oi a Miciowavc
ol|cci. Oi somc oihci ihing ihai ically
uocsn`i Inow how io laiI.
Thc comilci chccIs ihc class ol ihc
.ee.ere iyc-noi ihc obe iyc-io
scc il you can call a mcihou using ihai
iclcicncc.
Objecf




D
o
g
ob
j
e
c
f

equa|s()
elC|ass()
|as|Code()
lo3lr|r()
1- --l- ]--'-- :.||- -- .
------:- Mc1 - - l- :|.:: -
l.l ------:- l]- l--:-'l -.ll--
-.l l- .:l-.| --:l :
o.hashCode();
1- -' ------:- -.: -:|.-- .: l]-
6-:l, :- ]-- :.- :.|| --l-: --|]
l-:- --l-: .-- - :|.:: 6-:l
o.b o.ba o.b
hoshCode( )
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
214 chapter 8
An ol|cci coniains e.e.,L.r ii inhciiis liom cach ol iis
suciclasscs. Thai mcans e.e., ol|cci-icgaiulcss ol iis
aciual class iyc-is nIo an insiancc ol class Ol|cci.Thai
mcans any ol|cci in ]ava can lc iicaicu noi |usi as a Dog,
Buiion, oi Snowloaiu, lui also as an Ol|cci. Whcn you
say new Snowboard(), you gci a singlc ol|cci on ihc
hca-a Snowloaiu ol|cci-lui ihai Snowloaiu wias
iiscll aiounu an innci coic icicscniing ihc Ol|cci
caiial O") oiiion ol iiscll.
0c! |n !eerh w| !h yeer |nncr 0|jcr!.
1--- : --|] 6N! --:l -- l- -. --- A ----.-
--:l B-l l :--l.-: -l l- ----.- :|.:: .-l: -
l:-| .- l- 6-:l :|.:: .-l: - l:-|
objects are Objects
0bject
equa|s()
elC|ass()
|as|Code()
lo3lr|r()
8nowboard
equa|s()
elC|ass()
|as|Code()
lo3lr|r()
lurr()
s|red()
elA|r()
|oseCorlro|()
----.- ---l: --l-:
--- :---:|.:: 6-:l, .-
.: --- ----
t
o
S
t
r
i
n
g
(
)
h
a
s
h
C
o
d
e
(
)
g
e
t
A
i
r
(
)
tu
r
n
(
)
s
h
r
e
d
(
)
e
q
u
a
l
s
(
)
g
etC
la
s
s
(
)
lo
se
C
o
n
t
r
o
l
(
)
Ob]ect
8nowboard
S
n
o
w
board
o
b
je
c
t
He freofs me Iike on
Objecf. 8uf I con do so
much more...if onIy he'd see
me for whof I reoIIy om.
A :-|- --:l
-- l- -.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 215
Snowboard s = new Snowboard();
Object o = s;
t
o
S
t
r
i
n
g
(
)
h
a
s
h
C
o
d
e
(
)
g
e
t
A
i
r
(
)
tu
r
n
(
)
s
h
r
e
d
(
)
e
q
u
a
l
s
(
)
g
etC
la
s
s
(
)
lo
se
C
o
n
t
r
o
l
(
)
Ob]ect
8nowboard
1- 6-:l ------:- :.- :-- --|] l-
6-:l .-l: - l- ----.- --:l
|l :.- .::-:: --|] l- --l-: - :|.::
6-:l |l .: ---- -ll--: l.- l-
----.- ----l- :--l--|
o
s
1- ----.- ----l- :--l--|
|------:-` .: ---- -ll--: l.-
.- 6-:l ----l- :--l--| 1-
----.- ----l- :.- :-- l- -||
----.---:: - l- ----.-
--:l |l :.- .::-:: .|| l- --l-:
- ----.-, -:|-- -l l-
---l- 6-:l --l-: .- l-
--l-: --- :|.:: ----.-
S
n
o
w
board
o
b
je
c
t
Il a iclcicncc is liIc a icmoic coniiol, ihc
icmoic coniiol iaIcs on moic anu moic luiions
as you movc uown ihc inhciiiancc iicc. A
icmoic coniiol iclcicncc) ol iyc Ol|cci has
only a lcw luiions-ihc luiions loi ihc cxoscu
mcihous ol class Ol|cci. Bui a icmoic coniiol
ol iyc Snowloaiu incluucs all ihc luiions liom
class Ol|cci, lus any ncw luiions loi ncw
mcihous) ol class Snowloaiu. Thc moic sccihc
ihc class, ihc moic luiions ii may havc.
Ol couisc ihai`s noi always iiuc, a sulclass mighi
noi auu any ncw mcihous, lui simly ovciiiuc
ihc mcihous ol iis suciclass. Thc Icy oini is
ihai cvcn il ihc obe is ol iyc Snowloaiu, an
Ol|cci .ee.ere io ihc Snowloaiu ol|cci can`i scc
ihc Snowloaiu-sccihc mcihous.
Polymorphism' means
many forms'.
You can treat a 8nowboard as a
8nowboard or as an Ob]ect.
When you put
an ob]ect in an
ArrayList<Ob]ect>, you
can treat it only as an
Ob]ect, regardless of
the type it was when
you put it in.
When you get a
reference from an
ArrayList<Ob]ect>, the
reference is always of
type Ob]ect.
That means you get an
Ob]ect remote control.
---- --l-: ---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
216 chapter 8
Woif o minufe... whof good
is o Dog if if comes ouf of on
ArroyLisfObjecf ond if con'f do
ony Dog fhings7 There's goffo be o
woy fo gef fhe Dog bock fo o sfofe
of Dogness...
I hope if doesn'f hurf.
And whof's so wrong wifh
sfoying on Objecf7 OI, I con'f
fefch, sure, buf I con give you
o reoI nice hoshcode.
casting objects
Casting an ob]ect reference
back to its real type.
Objecf

Ii`s ically siill a Dog obe, lui il you wani io call
Dog-sccihc mcihous, you nccu a .ee.ere ucclaicu
as iyc Dog. Il you`ic u.e` ihc ol|cci is ically a
Dog, you can maIc a ncw Dog iclcicncc io ii ly
coying ihc Ol|cci iclcicncc, anu loicing ihai
coy io go inio a Dog iclcicncc vaiiallc, using a
casi Dog). You can usc ihc ncw Do iclcicncc io
call Do mcihous.
Object o = al.get(index);
Dog d = (Dog) o;
d.roam();
Objecf




D
o
g
ob
j
e
c
f
Dog

*Il you`ic ro suic ii`s a Dog, you can usc ihc


instanceof ociaioi io chccI. Bccausc il
you`ic wiong whcn you uo ihc casi, you`ll gci a
ClassCasiExcciion ai iuniimc anu comc io a
giinuing hali.
if (o instanceof Dog) {
Dog d = (Dog) o;
}



D
o
g
ob
j
e
c
f
:.:l l- 6-:l .: l-
. l- -- --- : l---
c.:l l- :-~:.||- '6-:l' |-l
-- --- -': .:l-.||] . l-` l-
l]- l-, :- l.l ]-- :.- l--.l
- |- l- l- - --.||] :
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 217
Whcn you wiiic a class, you almosi always e:oe somc
ol ihc mcihous io couc ouisiuc ihc class. To e:oe a
mcihou mcans you maIc a mcihou ne.bIe, usually ly
maiIing ii ullic.
Imaginc ihis sccnaiio: you`ic wiiiing couc loi a small
lusincss accouniing iogiam. A cusiom alicaiion
loi Simon`s Suil Sho". Thc goou ic-
usci ihai you aic, you lounu an Accouni
class ihai acais io mcci youi nccus
cilccily, accoiuing io iis uocumcniaiion,
anyway. Each accouni insiancc icicscnis
an inuiviuual cusiomci`s accouni wiih ihc
sioic. So ihcic you aic minuing youi own
lusincss invoIing ihc .eJ.() anu Jeb.()
mcihous on an accouni ol|cci whcn you icalizc you
nccu io gci a lalancc on an accouni. No iollcm-
ihcic`s a eBnInre() mcihou ihai shoulu uo niccly.
Excci... whcn you invoIc ihc eBnInre() mcihou,
ihc wholc ihing llows u ai iuniimc. Ioigci ihc
uocumcniaiion, ihc class uocs noi havc ihai mcihou.
YiIcs!
Bui ihai won`i hacn io you, lccausc cvciyiimc you
usc ihc uoi ociaioi on a iclcicncc a.uoSiull)), ihc
comilci looIs ai ihc .ee.ere iyc ihc iyc a` was
ucclaicu io lc) anu chccIs ihai class io guaianicc ihc
class has ihc mcihou, anu ihai ihc mcihou uocs inuccu
iaIc ihc aigumcni you`ic assing anu iciuin ihc Iinu ol
valuc you`ic cxcciing io gci lacI.
]ust rcmcmbcr that thc compilcr chccks thc class oI thc
re[erence variablc, not thc class oI thc actual object at thc
othcr cnd oI thc rcIcrcncc.
Think of the public methods in your class as
your contract, your promise to the outside
world about the things you can do.

deo|l(douo|e arl)
cred|l(douo|e arl)
douo|e el8a|arce()
8o now you've seen how much Java
cares about the methods in the
class of the reference variable.
You can call a method on an ob]ect only if
the class of the reference variable has that
method.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
218 chapter 8
OK, icicnu you`ic a Dog. Youi Dog class
isn`i ihc orI, coniiaci ihai uchncs who you
aic. Rcmcmlci, you inhciii acccssillc which
usually mcans ubI.) mcihous liom all ol
youi suciclasscs.
Tiuc, youi Dog class uchncs a coniiaci.
Bui noi nII ol youi coniiaci.
Evcrything in class Conine is part oI your
contract.
Evcrything in class AnimoI is part oI your
contract.
Evcrything in class Object is part oI your
contract.
Accoiuing io ihc IS-A icsi, you n.e cach ol
ihosc ihings-Caninc, Animal, anu Ol|cci.
Bui whai il ihc cison who ucsigncu youi
class hau in minu ihc Animal simulaiion
iogiam, anu now hc wanis io usc you class
Dog) loi a Scicncc Iaii Tuioiial on Animal
ol|ccis.
Thai`s OK, you`ic iolally icusallc loi ihai.
Bui whai il laici hc wanis io usc you loi a
PciSho iogiam. You Jor` Ln.e nr, Pet
beLn..o.. A Pci nccus mcihous liIc beE..erJI,()
anu In,().
OK, now icicnu you`ic ihc Dog class
iogiammci. No iollcm, iighi. ]usi auu
somc moic mcihous io ihc Dog class. You
won`i lc licaIing anyonc clsc`s couc ly
nJJ.r mcihous, sincc you aicn`i iouching
ihc e:..r mcihous ihai somconc clsc`s couc
mighi lc calling on Dog ol|ccis.
Can you scc any uiawlacIs io ihai aioach
auuing Pci mcihous io ihc Dog class).
Whz! |f yee ncc4 !e rhzn]c
!hc ren!rzr!!
Think obouf whof YOU wouId do if YOU were
fhe Dog cIoss progrommer ond needed fo
modify fhe Dog so fhof if couId do Pef fhings,
foo. We know fhof simpIy odding new Pef be-
hoviors (mefhods) fo fhe Dog cIoss wiII work,
ond won'f breok onyone eIse's code.
8uf... fhis is o PefShop progrom. If hos more
fhon jusf Dogsl And whof if someone wonfs
fo use your Dog cIoss for o progrom fhof hos
wiId Dogs7 Whof do you fhink your opfions
mighf be, ond wifhouf worrying obouf how
Jovo hondIes fhings, jusf fry fo imogine how
you'd Iike fo soIve fhe probIem of modifying
some of your AnimoI cIosses fo incIude Pef
behoviors.
Sfop righf now ond fhink obouf if,
before you Iook ut the net puge where we
begin fo reveoI everyfhing.
(l|us rerder|r l|e W|o|e exerc|se corp|ele|y use|ess, rooo|r
you ol your 0re 8| C|arce lo ourr sore ora|r ca|or|es)
modifying a cIass tree
WWkm
Qw&W
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 219
On ihc ncxi lcw agcs, wc`ic going io walI ihiough
somc ossililiiics. Wc`ic noi yci woiiicu aloui
whcihci ]ava can aciually whai wc comc u wiih.
Wc`ll cioss ihai liiugc oncc wc havc a goou iuca ol
somc ol ihc iiaucolls.
Ic!s crp|erc semc 4cs|]n ep!|ens
fer rces|n] semc ef eer cr|s!|n]
r|zsscs |n z |c!8hep pre]rzm.
We foke fhe eosy pofh, ond puf pef
mefhods in cIoss AnimoI.
1
0p!|en enc
AII fhe AnimoIs wiII insfonfIy inherif
fhe pef behoviors. We won'f hove fo
fouch fhe exisfing AnimoI subcIosses
of oII, ond ony AnimoI subcIosses
creofed in fhe fufure wiII oIso gef fo
foke odvonfoge of inherifing fhose
mefhods. Thof woy, cIoss AnimoI con
be used os fhe poIymorphic fype in
ony progrom fhof wonfs fo freof fhe
AnimoIs os pefs
|res:
So... when wos fhe Iosf fime you
sow o Hippo of o pef shop7 Lion7
WoIf7 CouId be dongerous fo give
non-pefs pef mefhods.
AIso, we oImosf cerfoinIy WILL
hove fo fouch fhe pef cIosses
Iike Dog ond Cof, becouse (in
our house, onywoy) Dogs
ond Cofs fend fo impIe-
menf pef behoviors
VEPY differenfIy.
0ens:
Tiger

Canine
Hippo
Dog
WoIf
Cat
Lion
FeIine

-
l
.
|| l

-

-
l

-
-
l

:
-

-
-


-
-
-

-
-
-

-
-
l
.
-
:
-

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
220 chapter 8

We sforf wifh Opfion One, puffing fhe pef mefhods
in cIoss AnimoI, buf we moke fhe mefhods obsfrocf,
forcing fhe AnimoI subcIosses fo override fhem.
2
0p!|en ! we
Thof wouId give us oII fhe beneffs of Opfion One, buf wifh-
ouf fhe drowbock of hoving non-pef AnimoIs running oround
wifh pef mefhods (Iike beFriendIy()). AII AnimoI cIosses
wouId hove fhe mefhod (becouse if's in cIoss AnimoI), buf
becouse if's obsfrocf fhe non-pef AnimoI cIosses won'f
inherif ony funcfionoIify. AII cIosses MUST override fhe
mefhods, buf fhey con moke fhe mefhods "do-nofhings".
|res:
8ecouse fhe pef mefhods in fhe AnimoI cIoss ore oII
obsfrocf, fhe concrefe AnimoI subcIosses ore forced fo
impIemenf oII of fhem. (Pemember, oII obsfrocf mefhods
MUST be impIemenfed by fhe frsf concrefe subcIoss
down fhe inherifonce free.) Whof o wosfe of fimel
You hove fo sif fhere ond fype in eoch ond every
pef mefhod info eoch ond every concrefe non-
pef cIoss, ond oII fufure subcIosses os weII.
And whiIe fhis does soIve fhe probIem of
non-pefs ocfuoIIy DOIM0 pef fhings
(os fhey wouId if fhey inherifed pef
funcfionoIify from cIoss AnimoI), fhe
confrocf is bod. Every non-pef
cIoss wouId be onnouncing fo fhe
worId fhof if, foo, hos fhose
pef mefhods, even fhough
fhe mefhods wouIdn'f
ocfuoIIy DO onyfhing
when coIIed.
This opprooch doesn'f
Iook good of oII. If jusf
seems wrong fo sfuff
everyfhing info cIoss AnimoI
fhof more fhon one AnimoI fype
mighf need, UMLESS if oppIies fo
ALL AnimoI subcIosses.
0ens:
Tiger

Canine
Hippo
Dog
WoIf
Cat
Lion
FeIine

-
l
.
|| l

-

-
l
-
-
l

:
-


-
-
-
,
-
l
-
l

-
-

-

|-
-
-
-
l
.
l
-
-
: M
.

-
.
||

-
l
-
-
l

: .

:l
-
.
:
l

Ask me fo be friendIy.
Mo, seriousIy... osk me.
I hove fhe mefhod.
modifying existing cIasses
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 221
Puf fhe pef mefhods OMLY in fhe
cIosses where fhey beIong.
3
0p!|en !hrcc
Mo more worries obouf Hippos greefing you of fhe
door or Iicking your foce. The mefhods ore where
fhey beIong, ond OMLY where fhey beIong. Dogs con
impIemenf fhe mefhods ond Cofs con impIemenf fhe
mefhods, buf nobody eIse hos fo know obouf fhem.
|res:
Two 8ig ProbIems wifh fhis opprooch. Firsf off, you'd
hove fo ogree fo o profocoI, ond oII progrommers of
pef AnimoI cIosses now ond in fhe fufure wouId hove
fo IMOW obouf fhe profocoI. 8y profocoI, we meon
fhe exocf mefhods fhof we've decided oII pefs shouId
hove. The pef confrocf wifhouf onyfhing fo bock if up.
8uf whof if one of fhe progrommers gefs if jusf o finy
bif wrong7 Like, o mefhod fokes o Sfring when if wos
supposed fo foke on inf7 Or fhey nomed if doFriendIy()
insfeod of beFriendIy()7 Since if isn'f in o confrocf,
fhe compiIer hos no woy fo check you fo see if you've
impIemenfed fhe mefhods correcfIy. Someone
couId eosiIy come oIong fo use fhe pef AnimoI
cIosses ond fnd fhof nof oII of fhem work
quife righf.
And second, you don'f gef fo use
poIymorphism for fhe pef mefhods.
Every cIoss fhof needs fo use
pef behoviors wouId hove fo
know obouf eoch ond every
cIossl In ofher words,
you con'f use AnimoI
os fhe poIymorphic
fype now, becouse fhe
compiIer won'f Ief you coII
o Pef mefhod on on AnimoI
reference (even if if's reoIIy o
Dog objecf) becouse cIoss AnimoI
doesn'f hove fhe mefhod.
0ens:
|-l l- -l --l-: 6N|/ - l-
A--.| :|.::-: l.l :.- - -l:,
-:l-. - - A--.|
Tiger

Canine
Hippo
Dog
WoIf
Cat
Lion
FeIine
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
222 chapter 8
8o what we REALLY need is:
A Way lo |ave pel oe|av|or |r just l|e pel c|asses
A Way lo uararlee l|al a|| pel c|asses |ave a|| ol l|e sare
rel|ods del|red (sare rare, sare arurerls, sare relurr
lypes, ro r|ss|r rel|ods, elc.), W|l|oul |av|r lo cross your
l|rers ard |ope a|| l|e prorarrers el |l r||l.
A Way lo la|e advarlae ol po|yrorp||sr so l|al a|| pels car |ave
l|e|r pel rel|ods ca||ed, W|l|oul |av|r lo use arurerls, relurr
lypes, ard arrays lor eac| ard every pel c|ass.
Tiger
Animal
Canine
Hippo
Dog
WoIf
Cat Lion
FeIine
Pet
t looks like we need TWO
superclasses at the top
w
-

-
.

-

.

-
-
-

.

:l
-
.
:
l

:-

-
-
:
|.
::
:
.
||-


|
-
l
,
.
-

-

l

.
||
l

-
l

-
-
l

:
c.l --- -l--:
--- -l A--.|
ANl
|-l, :- l -l:
l- --l-: - -l
l
-

l
-
-

:
-
l


|
-
l
.
-

A
-
-
.
|
1- ---~-l A--.|:
--'l .- .-] ---l-
|-l :l-
muItipIe inheritance?
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
interfaces and poIymorphism
you are here 223
t's called multiple inheritance
and it can be a Really Bad Thing.
Thof is, if if were possibIe fo do in Jovo.
8uf if isn'f, becouse muIfipIe inherifonce hos o probIem
known os The DeodIy Diomond of Deofh.
There's jusf one probIem wifh fhe "fwo supercIosses" opprooch...
60urner
ourr()
0V0urner
0|g|ta|Recorder
|rl |
ourr()
ourr()
6ombo0r|ve
cl
B
----- .- l
/l
B
----- -l
---l --- l
l.|-:----,
.- -l ----- l- ---|`
--l- B
-l ---l l- '
-:l.-:- .-.|-
Deadly Diamond of Death
|--|-- -l --|l|- ---l.-:-
w
: ---|` --l- ---: --- ]--
:.|| ---|` -- l- c---l
--
|-
.-- l.l l- ' -:l.-:-
.-.|- : -:-
] -l c
l
B
-----
.-
l
/
l
B
-----, -
l

----l
.|--: w
.l .--:
c
--
-l
--
---
: l- -:- -l .|--: -
'
A languagc ihai allows ihc Dcauly Diamonu ol Dcaih can lcau io
somc ugly comlcxiiics, lccausc you havc io havc sccial iulcs io
ucal wiih ihc oicniial amliguiiics. Anu cxiia iulcs mcans cxiia
woiI loi you loih in Ien.r.r ihosc iulcs anu waiching oui loi
ihosc sccial cascs". ]ava is suoscu io lc .Ie, wiih consisicni
iulcs ihai uon`i llow u unuci somc sccnaiios. So ]ava unliIc
C++) ioiccis you liom having io ihinI aloui ihc Dcauly Dia-
monu ol Dcaih. Bui ihai liings us lacI io ihc oiiginal iollcm!
How Jo we LnrJIe Le Ar.nI/Pe L.r:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
224 chapter 8
|n!crfzrc !e !hc rcsrec|

aost|act vo|d oeF||end|y(I,


aost|act vo|d o|ay(I,
A Java interface is like a
100% pure abstract class.
A|| --l-: - .- -l--.:- .--
.:l-.:l, :- .-] :|.:: l.l |~A
|-l M
c1 -|----l |- -----`
l- --l-: - |-l
]ava givcs you a soluiion. An .re.ne. Noi a CUI inicilacc, noi ihc gcnciic
usc ol ihc wo.J inicilacc as in, Thai`s ihc ullic inicilacc loi ihc Buiion
class API," lui ihc ]ava Ie,wo.J interface.
A ]ava inicilacc solvcs youi muliilc inhciiiancc iollcm ly giving you
much ol ihc olymoihic bere ol muliilc inhciiiancc wiihoui ihc ain
anu sullciing liom ihc Dcauly Diamonu ol Dcaih DDD).
Thc way in which inicilaccs siuc-sic ihc DDD is suiiisingly simlc: mohe
oII the methods obstroct: Thai way, ihc sulclass must imlcmcni ihc mcihous
icmcmlci, alsiiaci mcihous u lc imlcmcnicu ly ihc hisi concicic
sulclass), so ai iuniimc ihc ]VM isn`i conluscu aloui wL.L ol ihc iwo
inhciiicu vcisions ii`s suoscu io call.
To DEFNE an interface:
To MPLEMENT an interface:
public interface Pet {...}
public class Dog extends Canine implements Pet {...}
c
:- l- -]--- -l--.:-'
-:l-. - :|.::'
c:- l- -]--- -|----l:' -||---
] l- -l--.:- -.-- N-l- l.l
--- ]-- -|----l .- -l--.:- ]--
:l|| -l l- -l-- . :|.::
interfaces
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 225
Mzk|n] zn4 |mp|cmcn!|n]
!hc |c! |n!crfzrc
public interface Pet {
public abstract void beFriendly();
public abstract void play();
}
public class Dog extends Canine implements Pet {
public void beFriendly() {...}
public void play() {..}
public void roam() {...}
public void eat() {...}
}
A|| -l--.:- --l-: .--
.:l-.:l, :- l-] M
c1 -- -
:--:-|--: ------, l-] .-
-- -]'
/-- :.] '-l--.:-' -:l-.
- ':|.::' ---
/-- :.] '-|----l:'
-||--- ] l- -.--
- l- -l--.:-
/-- A|l ]-- .-- . |-l, :- ]-- M
c1
-|----l l- |-l --l-: |l': ]---
:--l-.:l N-l:- l- :--|] -.:-:
-:l-. - :--:-|--:
l- |~A A--.|
.- l- |~A |-l
1-:- .-- -:l ----.|
----- --l-:
(-,- a,- |
oa|| qa--(:|-

Wait a minute, interfaces don't


reaIIy give you muItipIe inheritance,
because you can't put any
impIementation code in them. If aII
the methods are abstract, what does
an interface reaIIy buy you!
Polymorphism, polymorphism,
polymorphism. |nterfaces are the
ultimate in flexibility, because if you
use interfaces instead of concrete
subclasses (or even abstract superclass
types) as arguments and return
types, you can pass anything that
implements that interface. And think
about itwith an interface, a class
doesn't have to come from |ust one
inheritance tree. A class can extend
one class, and implement an interface.
8ut another class might implement
the same interface, yet come from a
completely different inheritance tree!
So you get to treat an ob|ect by the
role it plays, rather than by the class
type from which it was instantiated.
|n fact, if you wrote your code to use
interfaces, you wouldn't even have to
give anyone a superclass that they had
to extend. ou could |ust give them
the interface and say, "Here,' | don't
care what kind of class inheritance
structure you come from, |ust
implement this interface and you'll be
good to go.
The fact that you can't put in
implementation code turns out not to
be a problem for most good designs,
because most interface methods
wouldn't make sense if implemented
in a generic way. |n other words, most
interface methods would need to
be overridden even if the methods
weren't to be abstract.
-l--.:- --l-: .-- -|:l|] -|: .-
.:l-.:l, :- l]- - '-|:' .- '.:l-.:l'
: -l--.| |- .:l, l': --l :--:--- '--
:l]|-' l- l]- l- ---: -, -l -- ---
-:l l- -----:- l, .- -:.-:- --'- ----
--- :|.-: l- .:--`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
226 chapter 8
Classes from different inheritance trees
can implement the same interface.
Tiger
Animal
Canine
Hippo
Dog
WoIf
Cat Lion
FeIine
Pet
RoboDog
Robot
Agent
c|.:: --l- --:-'l
:--- --- l- A--.|
---l.-:- l---, -l l :l|| -l: l- - . |-l'
Whcn you usc a In as a olymoihic iyc liIc an
aiiay ol iyc Animal oi a mcihou ihai iaIcs a Caninc
aigumcni), ihc ol|ccis you can siicI in ihai iyc
musi lc liom ihc samc inhciiiancc iicc. Bui noi |usi
anywhcic in ihc inhciiiancc iicc, ihc ol|ccis musi lc
liom a class ihai is a sulclass ol ihc olymoihic iyc.
An aigumcni ol iyc Caninc can accci a Woll anu a
Dog, lui noi a Cai oi a Hio.
Bui whcn you usc an inter[oce as a olymoihic
iyc liIc an aiiay ol Pcis), ihc ol|ccis can lc
liom nr,wLe.e in ihc inhciiiancc iicc. Thc only
icquiicmcni is ihai ihc ol|ccis aic liom a class ihai
.Ieer ihc inicilacc. Allowing classcs in uillcicni
inhciiiancc iiccs io imlcmcni a common inicilacc
is ciucial in ihc ]ava API. Do you wani an ol|cci
io lc allc io savc iis siaic io a hlc. Imlcmcni ihc
Sciializallc inicilacc. Do you nccu ol|ccis io iun
ihcii mcihous in a scaiaic ihicau ol cxccuiion.
Imlcmcni Runnallc. You gci ihc iuca. You`ll
lcain moic aloui Sciializallc anu Runnallc in laici
chaicis, lui loi now, icmcmlci ihai classcs liom
nr, lacc in ihc inhciiiancc iicc mighi nccu io
imlcmcni ihosc inicilaccs. Ncaily nr, class mighi
wani io lc savcallc oi iunnallc.
Better still, a class can implement
multiple interfacesl
A Dog ol|cci IS-A Caninc, anu IS-A Animal, anu
IS-A Ol|cci, all ihiough inhciiiancc. Bui a Dog IS-A
Pci ihiough inicilacc imlcmcniaiion, anu ihc Dog
mighi imlcmcni oihci inicilaccs as wcll. You coulu
say:
public class Dog extends Animal implements
Pet, Saveable, Paintable { ... }
interface poIymorphism
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 227

koses ote teJ, v|olets ote olue.


xrenJ only ene, out im
lem
enr rw
e.
1ava w
eighs in on fam
ily values:
SingIe Parents D
nIyll A 1ava class can have
only ene parent (superclass), and that parent
class defines w
ho you ote. 8ut you can im
ple-
m
ent m
ultiple interfaces, and those interfaces
define toles you con loy.
How do you know whether to make a
class, a subclass, an abstract class, or
an interface?

Moke o cIoss fhof doesn'f exfend onyfhing


(ofher fhon Objecf) when your new cIoss doesn'f
poss fhe IS-A fesf for ony ofher fype.

Moke o subcIoss (in ofher words, exfend o cIoss)


onIy when you need fo moke o more specihc
version of o cIoss ond need fo override or odd
new behoviors.

Use on obsfrocf cIoss when you wonf fo defne


o tempIute for o group of subcIosses, ond you
hove of Ieosf some impIemenfofion code fhof oII
subcIosses couId use. Moke fhe cIoss obsfrocf
when you wonf fo guoronfee fhof nobody con
moke objecfs of fhof fype.

Use on inferfoce when you wonf fo defne o roIe


fhof ofher cIosses con pIoy, regordIess of where
fhose cIosses ore in fhe inherifonce free.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
228 chapter 8
class BuzzwordsReport extends Report {

void runReport() {
super.runReport();
buzzwordCompliance();
printReport();
}
void buzzwordCompliance() {...}
}
using super
What if you make a concrete subcIass
and you need to override a method, but you
want the behavior in the supercIass version of
the method! In other words, what if you don't
need to the method with an override,
but you just want to to it with some
additionaI specic code.
Ahhh... think about the meaning of the
word 'extends'. One area of good OO design looks
at how to design concrete code that's meont to
be overridden. |n other words, you write method
code in, say, an abstract class, that does work
that's generic enough to support typical concrete
implementations. 8ut, the concrete code isn't
enough to handle oll of the subclass-specific
work. So the subclass overrides the method
and extenJs it by adding the rest of the code.
The keyword super lets you invoke a superclass
version of an overridden method, from within the
subclass.
nvoking the superclass
version of a method
super.runReport();
BuzzwordReport
:-:|.:: -
-l- |-----:
l- :---:|.:: --:--`
super.runReport{};
1- :--- -]--- : --.||] . ------:-
l- l- :---:|.:: --l-- - .- --:l
w-- :-:|.:: :-- -:-: :---, .: -
:---------l|`, l- :---:|.:: --:-- -
l- --l- -|| ---
abstract class Report {
void runReport() {
// set-up report
}
void printReport() {
// generic printing
}
}
Report
rurReporl()
pr|rlReporl()
rurReporl()
ouzzWordCorp||arce() :---:|.:: --l-:
|-:|-- l- ------
------l|`
A ------:- l- l- :-:|.:: --:l
|B---------l` -|| .|-.]: :.||
l- :-:|.:: --:-- - .- ------
--l- 1.l': -|]---:-
B-l l- :-:|.:: :-- :.- :.||
:---------l|` l- --- l-
:---:|.:: --:--
| --l- :-- -:- .
B---------l :-:|.:: :.]:
l- ------l|` --l- -:-
l- :---:|.:: ---l -|| ---
:---:|.:: --:-- - l-
--l- --: ---l.-l :l-
l.l :-:|.::-: :--| -:-
:.|| :---:|.:: --:--,
l-- :--- .: .-
- :--- :-:|.::~
:-:: :l-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 229
8ll P0lk5

w|er you dor'l Warl a c|ass lo oe |rslarl|aled (|r ol|er Words, you dor'l
Warl aryore lo ra|e a reW oojecl ol l|al c|ass lype) rar| l|e c|ass W|l| l|e
abstract |eyWord.

Ar aoslracl c|ass car |ave ool| aoslracl ard ror-aoslracl rel|ods.

ll a c|ass |as ever one aoslracl rel|od, l|e c|ass rusl oe rar|ed aoslracl.

Ar aoslracl rel|od |as ro oody, ard l|e dec|aral|or erds W|l| a ser|co|or (ro
cur|y oraces).

A|| aoslracl rel|ods rusl oe |rp|ererled |r l|e l|rsl corcrele suoc|ass |r l|e
|r|er|larce lree.

Every c|ass |r Java |s e|l|er a d|recl or |rd|recl suoc|ass ol c|ass (java.|ar.


0ojecl).

Vel|ods car oe dec|ared W|l| 0ojecl arurerls ard/or relurr lypes.

You car ca|| rel|ods or ar oojecl on|y |l l|e rel|ods are |r l|e c|ass (or |rlerlace)
used as l|e relerenoe var|ao|e lype, reard|ess ol l|e aclua| oojeor lype. 3o, a
relererce var|ao|e ol lype 0ojecl car oe used or|y lo ca|| rel|ods del|red |r c|ass
0ojecl, reard|ess ol l|e lype ol l|e oojecl lo W||c| l|e relererce relers.

A relererce var|ao|e ol lype 0ojecl car'l oe ass|red lo ary ol|er relererce lype
W|l|oul a oasr. A casl car oe used lo ass|r a relererce var|ao|e ol ore lype lo a
relererce var|ao|e ol a suolype, oul al rurl|re l|e casl W||| la|| |l l|e oojecl or l|e
|eap |s N0T ol a lype corpal|o|e W|l| l|e casl.
Exarp|e: Dog d = (Dog) x.getObject(aDog);

A|| oojecls core oul ol ar ArrayL|sl<0ojecl> as lype 0ojecl (rear|r, l|ey car oe
relererced or|y oy ar 0ojecl relererce var|ao|e, ur|ess you use a oasr).

Vu|l|p|e |r|er|larce |s rol a||oWed |r Java, oecause ol l|e proo|ers assoc|aled W|l|
l|e '0ead|y 0|arord ol 0eal|. T|al rears you car exlerd or|y ore c|ass (|.e. you
car |ave or|y ore |rred|ale superc|ass).

Ar |rlerlace |s |||e a 100 pure aoslracl c|ass. ll del|res on|y aoslracl rel|ods.

Creale ar |rlerlace us|r l|e interface |eyWord |rslead ol l|e Word class.

lrp|ererl ar |rlerlace us|r l|e |eyWord implements


Exarp|e: Dog implements Pet

Your c|ass car |rp|ererl ru|l|p|e |rlerlaces.

A c|ass l|al |rp|ererls ar |rlerlace musr |rp|ererl a|| l|e rel|ods ol l|e
|rlerlace, s|rce ell interfece methods ere imlicitly ublic end ebstrect.

To |rvo|e l|e superc|ass vers|or ol a rel|od lror a suoc|ass l|al's overr|dder l|e
rel|od, use l|e super |eyWord. Exarp|e: super.runReport();

7here's stiII something


strange here... you never
expIained how it is that
ArrayList<Dog> gives back Dog
references that don't need to be
cast, yet the ArrayList cIass uses
Dbject in its methods, not Dog
(or DotCom or anything eIse).
What's the speciaI trick going on
when you say ArrayList<Dog>!
ou're right for calling it a
special trick. |n fact it is a special
trick that ArrayList<Dog> gives
back Dogs without you having
to do any cast, since it looks like
ArrayList methods don't know
anything about Dogs, or any type
besides Ob|ect.
The short answer is that the
com|let uts |n the cost lot youl
when you say ArrayList<Dog>,
there is no special class that has
methods to take and return Dog
ob|ects, but instead the <Dog>
is a signal to the compiler that
you want the compiler to let
you put ONL Dog ob|ects in
and to stop you if you try to add
any other type to the list. And
since the compiler stops you
from adding anything but Dogs
to the ArrayList, the compiler
also knows that its safe to cast
anything that comes out of that
ArrayList do a Dog reference. |n
other words, using ArrayList<Dog>
saves you from having to cast
the Dog you get back. 8ut it's
much more important than that...
because remember, a cast can
fail at runtime, and wouldn't you
rather have your errors happen
at compile time rather than, say,
when your customer is using it for
something criticalI
8ut there's a lot more to this story,
and we'll get into all the details in
the Collections chapter.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
230 chapter 8
1I

2I
JI
1I
5I
0| vcn:
public interface Foo { }
public class Bar implements Foo { }
public interface Vinn { }
public abstract class Vout implements Vinn { }
public abstract class Mufe implements Whufe { }
public class Flufe extends Mufe { }
public interface Whufe { }
public class Zoop { }
public class Boop extends Zoop { }
public class Goop extends Boop { }
public class Gamma extends Delta implements Epsilon { }
public interface Epsilon { }
public interface Beta { }
public class Alpha extends Gamma implements Beta { }
public class Delta { }
Whz!s !hc ||r!erc !
|-l--.:-`
|--
B.-
1I
2I
JI
1I
5I
Here's your chance to demonstrate your artistic abilities. On the left you'll
nd sets of class and interface declarations. our |ob is to draw the associated
class diagrams on the right. we did the rst one for you. Use a dashed line for
"implements and a solid line for "extends.

exerc|se: what's the P|cture?


Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 231
6||ck
Top
Fee
6|ack
T|p
F|
Foo
ar
az
Zete
8ete
A|pha
0e|ta
1
2
J
1
5
0| vcn:
Whz!s !hc Pcr|zrz!|en !
1I
2I
JI
1I
5I
-|: :|.:: c|: !
-|: :|.:: c|.: -l--: c|: !
On the left you'll nd sets of class diagrams. our |ob is to turn
these into valid 1ava declarations. we did number l for you
(and it was a tough one).
6|ack
Cleck
6|ack
extends
implements
class
interface
abstract class

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
232 chapter 8
public int iMethod( ) ,
public int iMethod } }
public int iMethod ( ) }
public int iMethod ( ) } }
class
extends
interface
implements
our is to take code snippets from the pool and
place them into the blank lines in the code and out-
put. ou may use the same snippet more than once,
and you won't need to use all the snippets. our
is to make a set of classes that will compile
and run and produce the output listed.
Note: ach snippet
from the pooI can be
used more than oncel
File Edit Window Help BeAfraid
%java ______________
5 class Acts
7 class Clowns
________Of76
Dutput
____________ Nose {
________________________
}
abstract class Picasso implements ______{
_________________________
return 7,
}
}
class _________ ________ __________ { }
class _________ ________ __________ {
___________________________
return 5,
}
}
public ___________ ________ extends Clowns {
public static void main{String args| {
____________________________
i0 = new __________
il = new __________
i2 = new __________
for{int x = 0, x < 3, x++| {
System.out.println{__________________
+ " " + _______.getClass{ | |,
}
}
}
Acts( ),
Nose( ),
Of76( ),
Clowns( ),
Picasso( ),
Acts
Nose
Of76
Clowns
Picasso
i
i( )
i(x)
i|x|
i.iMethod(x)
i(x).iMethod| |
i|x|.iMethod( )
i|x|.iMethod| |
Of76 | | i new Nose|3|,
Of76 | 3 | i,
Nose | | i new Nose( ),
Nose | | i new Nose|3|,
class
5 class
7 class
7 public class

puzzIe: PooI PuzzIe


Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
interfaces and poIymorphism
you are here 233
|-l--.:-`
/--
-|: .:l-.:l :|.:: 1- !
-|: :|.:: 1 -l--: 1- !
Whz!s !hc Pcr|zrz!|en !
Whz!s !hc ||r!erc !
2I
JI
1I
5I
||--
|-l--.:-`
!:|--
|-l--.:-`
B-l.
|-l--.:-`
w--
/--l
M--
B--
6--
A|.
_--
l-|l.
6.--.
-|: .:l-.:l :|.:: |-- !
-|: .:l-.:l :|.:: | -l--: |-- !
-|: -l--.:- |-- !
-|: :|.:: B.- -|----l: |-- !
-|: :|.:: B.- -l--: B.- !
-|: -l--.:- _-l. !
-|: :|.:: A|. -|----l: _-l. !
-|: -l--.:- B-l. !
-|: :|.:: l-|l. -l--: A|. -|----l: B-l. !
2I
JI
1I
5I
]e;ejze o|ajoz
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
234 chapter 8
public cIoss Of7o extends Clowns {
public static void main{String args| {
Mose [ ] i ~ new Mose [3] ,
i0 = new Acfs( ) ,
il = new CIowns( ) ,
i2 = new Of7o( ) ,
for{int x = 0, x < 3, x++| {
System.out.println{ i [x] . iMefhod( )
+ " " + i [x].getClass{ | |,
}
}
}
File Edit Window Help KillTheMime
java of76
5 class Acts
7 class Clowns
7 class of76

inferfoce Nose {
pubIic inf iMefhod( ) ,
}
abstract class Picasso implements Mose {
pubIic inf iMefhod( ) {
return 7,
}
}
class CIowns exfends Picosso { }
class Acfs exfends Picosso {
pubIic inf iMefhod( ) {
return 5,
}
}
puzzIe soIution
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 235
9 constructors and garbage coIIection
Objects are born and objects die. ou're in charge of an ob|ect's lifecycle.
ou decide when and how to construct it. ou decide when to destroy it. Lxcept you don't
actually Jesttoy the ob|ect yourself, you simply ooonJon it. 8ut once it's abandoned, the
heartless Carbage CoIIector (gc) can vaporize it, reclaiming the memory that ob|ect was
using. |f you're gonna write 1ava, you're gonna create ob|ects. Sooner or later, you're gonna
have to let some of them go, or risk running out of PAM. |n this chapter we look at how ob|ects
are created, where they live while they're alive, and how to keep or abandon them efficiently.
That means we'll talk about the heap, the stack, scope, constructors, super constructors, null
references, and more. warning: this chapter contains material about ob|ect death that some
may find disturbing. 8est not to get too attached.
Life and Death
of an Ob]ect
...fhen he soid,
"I con'f feeI my Iegsl" ond
I soid "Joel Sfoy wifh me Joel"
8uf if wos... foo Iofe. The gorboge
coIIecfor come ond... he wos gone.
8esf objecf I ever hod.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
236 chapter 9
Ihc 8!zrk zn4 !hc Hczp: whcrc !h|n]s || vc
Bcloic wc can unucisianu whai ically hacns whcn
you cicaic an ol|cci, wc havc io sic lacI a lii. Wc
nccu io lcain moic aloui whcic cvciyihing livcs
anu loi how long) in ]ava. Thai mcans wc nccu io
lcain moic aloui ihc SiacI anu ihc Hca. In ]ava, wc
iogiammcis) caic aloui iwo aicas ol mcmoiy-ihc
onc whcic ol|ccis livc ihc hca), anu ihc onc
whcic mcihou invocaiions anu local vaiiallcs livc
ihc siacI). Whcn a ]VM siaiis u, ii gcis a chunI ol
mcmoiy liom ihc unucilying OS, anu uscs ii io iun
youi ]ava iogiam. How uL mcmoiy, anu whcihci
oi noi you can iwcaI ii, is uccnucni on which
vcision ol ihc ]VM anu on which lailoim) you`ic
iunning. Bui usually you wor` havc anyihing io say
aloui ii. Anu wiih goou iogiamming, you iolally
won`i caic moic on ihai a liiilc laici).
Wc Inow ihai all obe livc on ihc gailagc-collcciillc
hca, lui wc havcn`i yci looIcu ai whcic .n..nbIe
livc. Anu whcic a vaiiallc livcs uccnus on whai I.rJ
ol vaiiallc ii is. Anu ly Iinu", wc uon`i mcan ,e
i.c. iimiiivc oi ol|cci iclcicncc). Thc iwo I.rJ ol
vaiiallcs whosc livcs wc caic aloui now aic .rnre
vaiiallcs anu IonI vaiiallcs. Iocal vaiiallcs aic also
Inown as nI vaiiallcs, which is a lig cluc loi whcic
ihcy livc.
Ihc 8!zrk
where method invocations
and local variables live
-.-|`
-l-|`
-|`
8
u
f
fon o
b
j
e
c
f

D
u
c
k ob
j
e
c
f
S
n
o
w
b
oord
o
b
j
e
c
f

Ihc Hczp
.|:- ---
- .:
1
- 6
.-.-~
c
-||-:l
|- +
-.'
where ALL ob|ects live
nstance Variables Local Variables
Instance variabIes are decIared inside a clnss but ner
inside a method. They represent the "elds that each
individual ob|ect has (which can be lled with different
values for each instance of the class). |nstance variables
live inside the ob|ect they belong to.
public class Duck {
int size;
}
!--] l
-: .: . :--'
-:l.-:- .-.|-
LocaI variabIes are decIared inside a merheJ, incIuding
method parameters. They're temporary, and live only as
long as the method is on the stack (in other words, as long as
the method has not reached the closing curly brace).
public void foo(int x) {
int i = x + 3;
boolean b = true;
}
1
- .-.-
-l-- .-
l- .-.|-: .-
.-- .|| |-:.| .-.|-:
the stack and the heap
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 237
public void doStuff() {
boolean b = true;
go(4);
}
public void go(int x) {
int z = x + 24;
crazy();
// imagine more code here
}
public void crazy() {
char c = `a';
}
Mc!he4s zrc s!zrkc4
Whcn you call a mcihou, ihc mcihou lanus on
ihc io ol a call siacI. Thai ncw ihing ihai`s
aciually ushcu onio ihc siacI is ihc siacI
.ne, anu ii holus ihc siaic ol ihc mcihou
incluuing which linc ol couc is cxccuiing, anu
ihc valucs ol all local vaiiallcs.
Thc mcihou ai ihc o ol ihc siacI is always
ihc cuiicnily-iunning mcihou loi ihai siacI
loi now, assumc ihcic`s only onc siacI,lui in
chaici 14 wc`ll auu moic.) A mcihou siays on
ihc siacI uniil ihc mcihou hiis iis closing cuily
liacc which mcans ihc mcihou`s uonc). Il
mcihou oo() calls mcihou bn.(), mcihou bn.() is
siacIcu on io ol mcihou oo().
.-|`
--|`
:l
.:
-.-
-:
-ll-- - l- :l.:
l- - l- :l.:
|-:.| .-.|-:
|-:|--
.-.--l-- `
A coII sfock wifh fwo mefhods
1
Code from onofher
cIoss coIIs doStuff{},
ond doStuff{} goes
info o sfock frome
of fhe fop of fhe
sfock.The booIeon
voriobIe nomed 'b'
goes on fhe doStuff{}
sfock frome.
:


-l-|`

-|`
-l-|`

-
2
doStuff{} coIIs go{},
go{} is pushed on
fop of fhe sfock.
VoriobIes '' ond 'z'
ore in fhe go{} sfock
frome.
:-.-]|`
:
-l-|`

-|` -
-|`
-l-|`

-
3
go{} coIIs cruzy{},
cruzy{} is now on fhe
fop of fhe sfock,
wifh voriobIe 'c' in
fhe frome.
4
cruzy{} compIefes,
ond ifs sfock frome is
popped off fhe sfock.
Execufion goes bock
fo fhe go{} mefhod,
ond picks up of fhe
Iine foIIowing fhe coII
fo cruzy{}.
Thc couc on ihc lcli is a snici wc uon`i caic whai ihc icsi ol ihc
class looIs liIc) wiih ihicc mcihous. Thc hisi mcihou JoSu()) calls
ihc scconu mcihou o()), anu ihc scconu mcihou calls ihc ihiiu
.n.,()). Each mcihou ucclaics onc local vaiiallc wiihin ihc louy
ol ihc mcihou, anu mcihou o() also ucclaics a aiamcici vaiiallc
which mcans o() has iwo local vaiiallcs).
s!zrk srcnzr|e
The method on the top of the
stack is always the currently-
executing method.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
238 chapter 9
Whz! z|ee! |erz| vzr|z||cs !hz! zrc e|jcr!s!
Rcmcmlci, a non-iimiiivc vaiiallc holus a .ee.ere io an
ol|cci, noi ihc ol|cci iiscll. You alicauy Inow whcic ol|ccis
livc-on ihc hca. Ii uocsn`i maiici whcic ihcy`ic ucclaicu oi
cicaicu. I[ the IocoI voriobIe is o re[erence to on object, onIy
the voriobIe )the re[erence,remote controI; goes on the stoch.
TLe obe .eI .II oe .r Le Len.
D
u
c
k ob
j
e
c
f

.-|`
--|`
public class StackRef {
public void foof() {
barf();
}
public void barf() {
Duck d = new Duck(24);
}
}

.-
|`
-:|.--: .-
:--.l
-: . ---

l
-: --
----:- .-.|- '
' |:-:- l
':

-:|.--
-:
- l
- -
-l
-
, l
': . |-:.|
.-.|- .-
--: -- l
- :l
.:
object references on the stack
8ll P0lk5

Java |as lWo areas ol rerory We care aooul:


l|e 3lac| ard l|e leap.

lrslarce var|ao|es are var|ao|es dec|ared


|rs|de a c|ass oul ouls|de ary rel|od.

Loca| var|ao|es are var|ao|es dec|ared |rs|de a


rel|od or rel|od parareler.

A|| |oca| var|ao|es ||ve or l|e slac|, |r l|e


lrare correspord|r lo l|e rel|od W|ere l|e
var|ao|es are dec|ared.

0ojecl relererce var|ao|es Wor| jusl |||e pr|r|-


l|ve var|ao|es|l l|e relererce |s dec|ared as a
|oca| var|ao|e, |l oes or l|e slac|.

A|| oojecls ||ve |r l|e |eap, reard|ess ol


W|el|er l|e relererce |s a |oca| or |rslarce
var|ao|e.
(-,- a,- |
oa|| qa--(:|-
Dne more time, WHY are we Iearning the
whoIe stack/heap thing! How does this heIp me!
Do I reaIIy need to Iearn about it!
Knowing the fundamentals of the 1ava
Stack and Heap is crucial if you want to understand
variable scope, ob|ect creation issues, memory
management, threads, and exception handling.
we cover threads and exception handling in later
chapters but the others you'll learn in this one. ou
do not need to know anything about the Stack
and Heap are implemented in any particular 1vM
and/or platform. Lverything you need to know
about the Stack and Heap is on this page and the
previous one. |f you nail these pages, all the other
topics that depend on your knowing this stuff will
go much, much, much easier. Once again, some day
you will SO thank us for shoving Stacks and Heaps
down your throat.
+
-
.

N- -.ll-- w+!! l- --:l ------:- .-.|- : -:|.-- |-:-


. --l- : .: .- -:l.-:- .-.|- - . :|.::` l- --:l .|-.]: .|-.]:
.|-.]: --: -- l- -.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 239
|f |erz| vzr|z||cs || vc en !hc s!zrk,
whcrc 4e |ns!znrc vzr|z||cs || vc!
Whcn you say ncw CcllPhonc), ]ava has io maIc
sacc on ihc Hca loi ihai CcllPhonc. Bui how uL
sacc. Enough loi ihc ol|cci, which mcans cnough io
housc all ol ihc ol|cci`s insiancc vaiiallcs. Thai`s iighi,
insiancc vaiiallcs livc on ihc Hca, insiuc ihc ol|cci
ihcy lclong io.
Rcmcmlci ihai ihc .nIue ol an ol|cci`s insiancc
vaiiallcs livc insiuc ihc ol|cci. Il ihc insiancc vaiiallcs
aic all iimiiivcs, ]ava maIcs sacc loi ihc insiancc
vaiiallcs lascu on ihc iimiiivc iyc. An ini nccus
S2 liis, a long 64 liis, cic. ]ava uocsn`i caic aloui ihc
valuc insiuc iimiiivc vaiiallcs, ihc lii-sizc ol an ini
vaiiallc is ihc samc S2 liis) whcihci ihc valuc ol ihc
ini is S2,000,000 oi S2.
Bui whai il ihc insiancc vaiiallcs aic obe. Whai il
CcllPhonc HAS-A Anicnna. In oihci woius, CcllPhonc
has a iclcicncc vaiiallc ol iyc Anicnna.
Whcn ihc ncw ol|cci has insiancc vaiiallcs ihai aic
ol|cci iclcicnccs iaihci ihan iimiiivcs, ihc ical
qucsiion is: uocs ihc ol|cci nccu sacc loi all ol
ihc ol|ccis ii holus iclcicnccs io. Thc answci is, ro
e:nI,. No maiici whai, ]ava has io maIc sacc loi ihc
insiancc vaiiallc .nIue. Bui icmcmlci ihai a iclcicncc
vaiiallc valuc is noi ihc wholc obe, lui mcicly a .eoe
or.oI io ihc ol|cci. So il CcllPhonc has an insiancc
vaiiallc ucclaicu as ihc non-iimiiivc iyc Anicnna,
]ava maIcs sacc wiihin ihc CcllPhonc ol|cci only loi
ihc Anicnna`s .eoe or.oI i.c. iclcicncc vaiiallc) lui
noi ihc Anicnna obe.
Wcll ihcn whcn uocs ihc Anicnna obe gci sacc on
ihc Hca. Iiisi wc havc io hnu oui wLer ihc Anicnna
ol|cci iiscll is cicaicu. Thai uccnus on ihc insiancc
vaiiallc ucclaiaiion. Il ihc insiancc vaiiallc is ucclaicu
lui no ol|cci is assigncu io ii, ihcn only ihc sacc loi
ihc iclcicncc vaiiallc ihc icmoic coniiol) is cicaicu.
private Antenna ant;
No aciual Anicnna ol|cci is mauc on ihc hca unlcss
oi uniil ihc iclcicncc vaiiallc is assigncu a ncw
Anicnna ol|cci.
private Antenna ant = new Antenna();

6-:l -l l-- --l- -:l.-:- .-.|-:
.:- -- l- .-.|-: |-: - l- --:l
6-:l -l --- ---~--l- -:l.-:- .-.|--
. ------:- l- .- A-l---. --:l, -l -- .:l-.|
A-l---. --:l 1: : -.l ]-- -l ]--
-:|.-- l- .-.|- -l --'l -l.|-- l -l
.- .:l-.| A-l---. --:l
Anfenno

public class CellPhone {


private Antenna ant;
}
public class CellPhone {
private Antenna ant = new Antenna();
}
6-:l -l --- ---~--l- -:l.-:- .-.|-,
.- l- A-l---. .-.|- : .::-- . ---
A-l---. --:l


Anfenno

CeIIPhone objecf
CeIIPhone objecf
Anfenno objecf
CeIIPhone objecf
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
240 chapter 9
object creation
Ihc m|rzr|c ef e|jcr! rrcz!|en
Now ihai you Inow whcic vaiiallcs anu ol|ccis livc, wc can uivc inio
ihc mysiciious woilu ol ol|cci cicaiion. Rcmcmlci ihc ihicc sics
ol ol|cci ucclaiaiion anu assignmcni: ucclaic a iclcicncc vaiiallc,
cicaic an ol|cci, anu assign ihc ol|cci io ihc iclcicncc.
Bui uniil now, sic iwo-whcic a miiaclc occuis anu ihc ncw ol|cci
is loin"-has icmaincu a Big Mysiciy. Picaic io lcain ihc lacis ol
ol|cci lilc. Hoe ,ou`.e ro quen.L.

DecIore o reference
voriobIe
Duck reference

Duck myDuck = new Duck();


Creofe on objecf
Review the 3 steps of ob]ect
declaration, creation and assignment:
Duck objecf
Duck myDuck = new Duck();
Duck myDuck = new Duck();

Link fhe objecf ond


fhe reference

Duck reference

Duck objecf
M
.- . ---
--
----:-
.-.|- -
. :|.:: --
-l
--
.:- l
]-
A

-
-
.
:
|-

-
:
:
-
-
:

-
-
-

A
::- l
- ---

--:l
l
- l
-
--
----:-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 241
Are we calling a method named Duck{}?
Because it sure looks like it.
A consiiucioi Joe looI anu lccl a loi liIc a mcihou, lui ii`s noi
a mcihou. Ii`s goi ihc couc ihai iuns whcn you say new. In oihci
woius, Le oJe Ln .ur wLer ,ou .rnr.ne nr obe.
Thc only way io invoIc a consiiucioi is wiih ihc Icywoiu new
lollowcu ly ihc class namc. Thc ]VM hnus ihai class anu invoIcs
ihc consiiucioi in ihai class. OK, icchnically ihis isn`i ihc orI,
way io invoIc a consiiucioi. Bui ii`s ihc only way io uo ii liom
ou.Je a consiiucioi. You nr call a consiiucioi liom wiihin
anoihci consiiucioi, wiih icsiiiciions, lui wc`ll gci inio all ihai
laici in ihc chaici.)
Duck myDuck = new Duck();
|l |--: |- --'-- :.||-
. --l- -.-- l
-:|`,
-:.-:- - l- .---l-:-:
No.
We're calling the Duck constructor.
But where is the constructor?
f we didn't write it, who did?
You can wiiic a consiiucioi loi youi class wc`ic aloui io uo
ihai), lui il you uon`i, the compiIer writes one [or you:
Hcic`s whai ihc comilci`s uclauli consiiucioi looIs liIc:
public Duck() {

}
w---': l- --l--- l]- | l: ---- . --l-,
]--' --- . --l--- l]- -l---- -|:' .-
l-:|`'
Notice something missing? How is this
different from a method?
public Duck() {
// constructor code goes here
}
|l: -.-- : l- :.-- .: l-
:|.:: -.-- 1
.l': -.-.l--]
A censtracter has the
cede that rans when yea
instantiate an ebject. In
ether werds, the cede that
rans when yea say new en
a class type.
8very class yea create has
a censtracter, even if yea
den't write it yearself.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
242 chapter 9
constructing a new Duck
0ens!rer! z Perk
Thc Icy lcaiuic ol a consiiucioi is ihai ii iuns
ihc ol|cci can lc assigncu io a iclcicncc.
Thai mcans you gci a chancc io sic in anu
uo ihings io gci ihc ol|cci icauy loi usc. In
oihci woius, lcloic anyonc can usc ihc icmoic
coniiol loi an ol|cci, ihc ol|cci has a chancc io
hcl consiiuci iiscll. In oui DucI consiiucioi,
wc`ic noi uoing anyihing usclul, lui ii siill
ucmonsiiaics ihc scqucncc ol cvcnis.
If if Quocks Iike o
consfrucfor...
public class UseADuck {
public static void main (String[] args) {
Duck d = new Duck();
}
}
public class Duck {
public Duck() {
System.out.println(Quack);
}
}
File Edit Window Help Quack
% java UseADuck
Quack
c
--:l--:l-- :--
1
: :.||: l- l
-:
:--:l--:l--
The constructor gives
you a chance to step into
the middle of new.
+,-+ :+ ,-+:.|
A constructor lets you |ump into the middle
of the ob|ect creation stepinto the middle
of new. Can you imagine conditions where
that would be usefulI which of these might
be useful in a Car class constructor, if the Car
is part of a Pacing GameI Check off the ones
that you came up with a scenario for.
lrcrererl a courler lo lrac| |oW rary oojecls ol l||s c|ass lype
|ave oeer rade.
Ass|r rurl|re-spec|l|c slale (dala aooul W|al's |apper|r N0w).
Ass|r va|ues lo l|e oojecl's |rporlarl |rslarce var|ao|es.
0el ard save a relererce lo l|e oojecl l|al's orear|ng l|e reW oojecl.
Add l|e oojecl lo ar ArrayL|sl.
Creale lA3-A oojecls.
________________________________________ (your |dea |ere)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
constructors and gc
you are here 243
|n| !|z||z|n] !hc s!z!c ef z ncw Perk
Mosi colc usc consiiuciois io iniiializc ihc siaic ol an ol|cci.
In oihci woius, io maIc anu assign valucs io ihc ol|cci`s
insiancc vaiiallcs.
public Duck() {
size = 34;
}
Thai`s all wcll anu goou whcn ihc DucI class Je.eIoe. Inows
how lig ihc DucI ol|cci shoulu lc. Bui whai il wc wani ihc
iogiammci who is u.r DucI io ucciuc how lig a aiiiculai
DucI shoulu lc.
Imaginc ihc DucI has a sizc insiancc vaiiallc, anu you wani ihc
iogiammci using youi DucI class io sci ihc sizc ol ihc ncw
DucI. How coulu you uo ii.
Wcll, you coulu auu a sciSizc) sciici mcihou io ihc class. Bui
ihai lcavcs ihc DucI icmoiaiily wiihoui a sizc*, anu loiccs ihc
DucI usci io wiiic wo siaicmcnis-onc io cicaic ihc DucI, anu
onc io call ihc sciSizc) mcihou. Thc couc lclow uscs a sciici
mcihou io sci ihc iniiial sizc ol ihc ncw DucI.
public class Duck {
int size;
public Duck() {
System.out.println(Quack);
}
public void setSize(int newSize) {
size = newSize;
}
}
public class UseADuck {
public static void main (String[] args){
Duck d = new Duck();

d.setSize(42);
}
}
:--:l--:l--
-:l.-:- .-.|-
:-ll-- --l-
1---': . . l- --- 1- l
-: : .|- .l
l: --l - l- :--, -l -l--l . :--'

A- l-- ]--'-- --|]- -- l- l
-:~-:--
l- rN6w
l.l l
-: :--.l-- : . l--~.-l
--:-:: --- l- :.|| l- :--:l--:l-- .- ---
l- :.|| l- :-ll--
(-,- a,- |
oa|| qa--(:|-
Why do you need to write
a constructor if the compiIer
writes one for you!
|f you need code to help
initialize your ob|ect and get
it ready for use, you'll have to
write your own constructor. ou
might, for example, be depen-
dent on input from the user
before you can finish making
the ob|ect ready. There's another
reason you might have to write
a constructor, even if you don't
need any constructor code
yourself. |t has to do with your
superclass constructor, and we'll
talk about that in a few minutes.
How can you teII a con-
structor from a method! Can
you aIso have a method that's
the same name as the cIass!
1ava lets you declare a
method with the same name as
your class. That doesn't make it
a constructor, though. The thing
that separates a method from a
constructor is the return type.
Methods must have a return
type, but constructors connot
have a return type.
Are constructors inher-
ited! If you don't provide a
constructor but your supercIass
does, do you get the supercIass
constructor instead of the
defauIt!
Nope. Constructors are
not inherited. we'll look at that in
|ust a few pages.
*nstance variables do have a default value. 0 or
0.0 for numeric primitives, false for booleans, and
null for references.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
244 chapter 9
0s|n] !hc rens!rer!er !e |n| !|z||zc
|mper!zn! Perk s!z!c'
Il an ol|cci shoulun`i lc uscu uniil onc oi
moic aiis ol iis siaic insiancc vaiiallcs) havc
lccn iniiializcu, uon`i lci anyonc gci aholu ol
a DucI ol|cci uniil you`ic hnishcu iniiializing!
Ii`s usually way ioo iisIy io lci somconc maIc-
anu gci a iclcicncc io-a ncw DucI ol|cci ihai
isn`i quiic icauy loi usc uniil ihai somconc iuins
aiounu anu calls ihc eS..e() mcihou. How will
ihc DucI-usci cvcn Irow ihai hc`s icquiicu io call
ihc sciici mcihou alici maIing ihc ncw DucI.
Thc lcsi lacc io ui iniiializaiion couc is in ihc
consiiucioi. Anu all you nccu io uo is maIc a
consiiucioi wiih aigumcnis.
public class Duck {
int size;
public Duck(int duckSize) {
System.out.println(Quack);
size = duckSize;
System.out.println(size is + size);
}
}
public class UseADuck {
public static void main (String[] args) {
Duck d = new Duck(42);
}
}
File Edit Window Help Honk
% java UseADuck
Quack
size is 42
A


.
-

-
l

.
-
.
-
-
l
-
-

l
-

l

-

l
-
:


:
-
-
:l
-
-
:
l
-
-

c:- l- .-----l .|-- l- :-l


l- :-- -:l.-:- .-.|-
|.:: . .|-- l- l-
:--:l--:l--
1

:
l
-
-

l

-
-
-
':
-
-
|]

-
-
-

:l
.
l
-
-
-
-
l

w
-

-
.

-

l

-

-
-
-

l
-
:


.
-


:-
l

l
: :-
-
-
-
-
-
:l
.
l
-
-
-
-
l

Lef fhe user moke o new Duck


ond sef fhe Duck's si;e oII in
one coII. The coII fo new.
The coII fo fhe Duck
consfrucfor.
*Not to imply that not all Duck state is not unimportant.
initiaIizing object state
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 245
Mzkc | ! czsy !e mzkc z Perk
Bc serc yee hzvc z ne-zr] rens!rer!er
Whai hacns il ihc DucI consiiucioi iaIcs an aigumcni.
ThinI aloui ii. On ihc icvious agc, ihcic`s only ore DucI
consiiucioi-anu ii iaIcs an ini aigumcni loi ihc ..e ol ihc
DucI. Thai mighi noi lc a lig iollcm, lui ii uocs maIc ii
haiuci loi a iogiammci io cicaic a ncw DucI ol|cci, csccially
il ihc iogiammci uocsn`i Irow whai ihc sizc ol a DucI shoulu
lc. Woulun`i ii lc hcllul io havc a uclauli sizc loi a DucI, so
ihai il ihc usci uocsn`i Inow an aioiiaic sizc, hc can siill
maIc a DucI ihai woiIs.
Imagine that you want Duck users to have TWO options
for making a Duck-one where they supply the Duck
size (as the constructor argument) and one where they
don't specify a size and thus get your default Duck size.
You can`i uo ihis clcanly wiih |usi a singlc consiiucioi.
Rcmcmlci, il a mcihou oi consiiucioi-samc iulcs) has
a aiamcici, you u ass an aioiiaic aigumcni whcn
you invoIc ihai mcihou oi consiiucioi. You can`i |usi say, Il
somconc uocsn`i ass anyihing io ihc consiiucioi, ihcn usc
ihc uclauli sizc", lccausc ihcy won`i cvcn lc allc io comilc
wiihoui scnuing an ini aigumcni io ihc consiiucioi call. You
ouIJ uo somcihing clunIly liIc ihis:
Bui ihai mcans ihc iogiammci maIing a ncw DucI ol|cci has
io Irow ihai assing a 0" is ihc ioiocol loi gciiing ihc uclauli
DucI sizc. Piciiy ugly. Whai il ihc oihci iogiammci uocsn`i
Inow ihai. Oi whai il hc ically Joe wani a zcio-sizc DucI.
Assuming a zcio-sizcu DucI is allowcu. Il you uon`i wani
zcio-sizcu DucI ol|ccis, ui valiuaiion couc in ihc consiiucioi
io icvcni ii.) Thc oini is, ii mighi noi always lc ossillc
io uisiinguish lciwccn a gcnuinc I wani zcio loi ihc sizc"
consiiucioi aigumcni anu a I`m scnuing zcio so you`ll givc
mc ihc uclauli sizc, whaicvci ihai is" consiiucioi aigumcni.
public class Duck2 {
int size;
public Duck2() {
// supply default size
size = 27;
}
public Duck2(int duckSize) {
// use duckSize parameter
size = duckSize;
}
}
7o make a Duck when you know the size:
Duck2 d = new Duck2(15);
7o make a Duck when you do ner know
the size:
Duck2 d2 = new Duck2();
You reaIIy want 7WD ways to
make a new Duck:
public class Duck {
int size;
public Duck(int newSize) {
if (newSize == 0) {
size = 27;
} else {
size = newSize;
}
}
}
So this two-options-to-make-a-Duck idea
needs constructors. One that takes
an int and one that doesn't. lI yeu hnve
mere rhnn ene censrrucrer in n clnss,
ir menns yeu hnve everlenJeJ
censrrucrers.
| l- .-.-
-l-- .|-- :
----, - l- ---
l
-: .
-.-|l :--, -l---
:- -:-
l- .-.-
-l-- .|-- --
l- :-- N
6
1
. --] --
:-|-l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
246 chapter 9
You mighi ihinI ihai il you wiiic orI,
a consiiucioi wiih aigumcnis, ihc
comilci will scc ihai you uon`i havc a
no-aig consiiucioi, anu siicI onc in loi
you. Bui ihai`s noi how ii woiIs. Thc
comilci gcis involvcu wiih consiiucioi-
maIing orI, . ,ou Jor` n, nr,L.r n nII
nbou or.uo..
f you write a constructor that
takes arguments, and you still
want a no-arg constructor,
you'll have to build the no-arg
constructor yourselfl
As soon as you ioviuc a consiiucioi,
ANY Iinu ol consiiucioi, ihc comilci
lacIs oll anu says, OK Buuuy, looIs liIc
you`ic in chaigc ol consiiuciois now."
f you have more than one
constructor in a class, the
constructors MU8T have
different argument lists.
Thc aigumcni lisi incluucs ihc oiuci
anu iycs ol ihc aigumcnis. As long as
ihcy`ic uillcicni, you can havc moic
ihan onc consiiucioi. You can uo ihis
wiih mcihous as wcll, lui wc`ll gci io ihai
in anoihci chaici.
overIoaded and defauIt constructors
Pecsn! !hc remp| |cr z| wzys
mzkc z ne-zr] rens!rer!er
fer yee!
OI, Ief's see here... "You
hove fhe righf fo your own
consfrucfor." Mokes sense.
"If you connof offord o consfrucfor,
one wiII be provided for you by fhe
compiIer." 0ood fo know.

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 247
8ll P0lk5

lrslarce var|ao|es ||ve W|l||r l|e oojecl l|ey oe|or lo, or


l|e leap.

ll l|e |rslarce var|ao|e |s a relererce lo ar oojecl, ool|


l|e relererce ard l|e oojecl |l relers lo are or l|e leap.

A corslruclor |s l|e code l|al rurs W|er you say new or


a c|ass lype.

A corslruclor rusl |ave l|e sare rare as l|e c|ass, ard


rusl |ave a relurr lype.

You car use a corslruclor lo |r|l|a||ze l|e slale (|.e. l|e


|rslarce var|ao|es) ol l|e oojecl oe|r corslrucled.

ll you dor'l pul a corslruclor |r your c|ass, l|e corp||er


W||| pul |r a delau|l corslruclor.

T|e delau|l corslruclor |s a|Ways a ro-ar corslruclor.

ll you pul a corslruclorary corslruclor|r your c|ass,


l|e corp||er W||| rol ou||d l|e delau|l corslruclor.

ll you Warl a ro-ar corslruclor, ard you've a|ready pul


|r a corslruclor W|l| arurerls, you'|| |ave lo ou||d l|e
ro-ar corslruclor yourse|l.

A|Ways prov|de a ro-ar corslruclor |l you car, lo ra|e |l


easy lor prorarrers lo ra|e a Wor||r oojecl. 3upp|y
delau|l va|ues.

0ver|oaded corslruclors rears you |ave rore l|ar ore


corslruclor |r your c|ass.

0ver|oaded corslruclors rusl |ave d|llererl arurerl


||sls.

You carrol |ave lWo corslruclors W|l| l|e sare


arurerl ||sls. Ar arurerl ||sl |rc|udes l|e order ard/or
lype ol arurerls.

lrslarce var|ao|es are ass|red a delau|l va|ue, ever


W|er you dor'l exp||c|l|y ass|r ore. T|e delau|l va|ues
are 0/0.0/la|se lor pr|r|l|ves, ard ru|| lor relererces.
|
---

----l
:--:l
--:l
--:
-
-.-:
---

----l
-
.]: l
-
-
.- . ---
-
-:
----

public class Mushroom {
public Mushroom(int size) { }
public Mushroom( ) { }
public Mushroom(boolean isMagic) { }
public Mushroom(boolean isMagic, int size) { }
public Mushroom(int size, boolean isMagic) { }
}
--- ]-- --- l- :--, -l ]--
--'l --- l': -.:
--- ]-- --'l --- .-]l-
--- ]-- --- l': -.: -- --l,
-l --'l --- l- :--
--- ]-- ---
--l-- -- --l l':
-.:, ANl ]-- ---
l- :-- .: --||
Overloaded constructors means you have
more than one constructor in your class.
To compile, each constructor must have a
different argument listl
Thc class lclow is lcgal lccausc all loui consiiuciois havc
uillcicni aigumcni lisis. Il you hau iwo consiiuciois ihai iooI
only an ini, loi cxamlc, ihc class woulun`i comilc. Whai you
namc ihc aiamcici vaiiallc uocsn`i couni. Ii`s ihc vaiiallc
,e ini, Dog, cic.) anu o.Je. ihai maiicis. You nr havc iwo
consiiuciois ihai havc iucniical iycs, os Iong os the order is
di[[erent. A consiiucioi ihai iaIcs a Siiing lollowcu ly an ini, is
ro ihc samc as onc ihai iaIcs an ini lollowcu ly a Siiing.
l-:- l-- .- l-
:.-- .-:, -l -
----l ----, :-
l': 6r
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
248 chapter 9

arIier you said that it's good to have a no-argu-


ment constructor so that if peopIe caII the no-arg con-
structor, we can suppIy defauIt vaIues for the "missing"
arguments. ut aren't there times when it's impossibIe to
come up with defauIts! Are there times when you shouId
not have a no-arg constructor in your cIass!
ou're right. There are times when a no-arg construc-
tor doesn't make sense. ou'll see this in the 1ava AP|some
classes don't have a no-arg constructor. The Color class, for
example, represents a... color. Color ob|ects are used to, for
example, set or change the color of a screen font or GU|
button. when you make a Color instance, that instance is
of a particular color (you know, Death-by-Chocolate 8rown,
8lue-Screen-of-Death 8lue, Scandalous Ped, etc.). |f you
make a Color ob|ect, you must specify the color in some way.
Color c = new Color(3,45,200);
(we're using three ints for PG8 values here. we'll get into
using Color later, in the Swing chapters.) Otherwise, what
would you getI The 1ava AP| programmers have de-
cided that if you call a no-arg Color constructor you'll get a
lovely shade of mauve. 8ut good taste prevailed.
|f you try to make a Color without supplying an argument:
Color c = new Color();
The compiler freaks out because it can't find a matching no-
arg constructor in the Color class.
File Edit Window Help StopBeingStupid
cannot resolve symbol
:constructor Color()
location: class
java.awt.Color
Color c = new Color();
^
1 error
public class TestDuck {
public static void main(String[] args){
int weight = 8;
oat density = 2.3F;
String name = Donald;
long[] feathers = {1,2,3,4,5,6};
boolean canFly = true;
int airspeed = 22;
Duck[] d = new Duck[7];
d[0] = new Duck();
d[1] = new Duck(density, weight);

d[2] = new Duck(name, feathers);
d[3] = new Duck(canFly);
d[4] = new Duck(3.3F, airspeed);

d[5] = new Duck(false);
d[6] = new Duck(airspeed, density);
}
}


class Duck {
int pounds = 6;
oat oatability = 2.1F;
String name = Generic;
long[] feathers = {1,2,3,4,5,6,7};
boolean canFly = true;
int maxSpeed = 25;

public Duck() {
System.out.println(type 1 duck);
}
public Duck(boolean y) {
canFly = y;
System.out.println(type 2 duck);
}
public Duck(String n, long[] f) {
name = n;
feathers = f;
System.out.println(type 3 duck);
}
public Duck(int w, oat f) {
pounds = w;
oatability = f;
System.out.println(type 4 duck);
}
public Duck(oat density, int max) {
oatability = density;
maxSpeed = max;
System.out.println(type 5 duck);
}
}
+,-+ :+ ,-+:.|
Match the new Duck() call with the constructor
that runs when that Duck is instantiated. We did
the easy one to get you started.
overIoaded constructors
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 249
What about supercIasses!
When you make a Dog,
shouId the Canine
constructor run too!
If the supercIass is abstract,
shouId it even have a
constructor!
we'll look at this on the next
few pages, so stop now and
think about the implications of
constructors and superclasses.
hznercv|cw: feer !h|n]s !e
rcmcm|cr z|ee! rens!rer!ers
1
A consfrucfor is fhe code fhof runs when
somebody soys new on o cIoss fype
2
A consfrucfor musf hove fhe some nome
os fhe cIoss, ond refurn fype
3
If you don'f puf o consfrucfor in your cIoss,
fhe compiIer pufs in o defouIf consfrucfor.
The defouIf consfrucfor is oIwoys o no-org
consfrucfor.
4
You con hove more fhon one consfrucfor in your cIoss,
os Iong os fhe orgumenf Iisfs ore differenf. Hoving
more fhon one consfrucfor in o cIoss meons you hove
overIooded consfrucfors.
Duck d = new Duck();

public Duck(int size) { }
public Duck() { }
public Duck() { }
public Duck(int size) { }
public Duck(String name) { }
public Duck(String name, int size) { }
Doing all the Brain Barbells has been shown to produce a 42% increase in
neuron size. And you know what they say, Big neurons...
(-,- a,- |
oa|| qa--(:|-
Do constructors have to be public!
No. Constructors can be public,
private, or Jeloult (which means no access
modifier at all). we'll look more at Jeloult
access in chapter l6 and appendix 8.
How couId a private constructor
ever be usefuI! Nobody couId ever caII it,
so nobody couId ever make a new objectl
8ut that's not exactly right. Marking
something private doesn't mean noooJy
can access it, it |ust means that noooJy
outs|Je the closs can access it. 8et you're
thinking "Catch 22. Only code from the
some class as the class-with-private-con-
structor can make a new ob|ect from that
class, but without first making an ob|ect,
how do you ever get to run code from that
class in the first placeI How do you ever get
to anything in that classI Pot|ence tossho-
et. we'll get there in the next chapter.
WWkm
Qw&W
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
250 chapter 9
Wz| ! z m|ne!c... wc ncvcr P|P !z|k z|ee!
sepcrr|zsscs zn4 |nhcr| !znrc zn4 hew !hz! z| |
f| !s |n w| !h rens!rer!ers.
Hcic`s whcic ii gcis lun. Rcmcmlci liom ihc lasi chaici, ihc aii whcic wc looIcu ai
ihc Snowloaiu ol|cci wiaing aiounu an innci coic icicscniing ihc Ol|cci oiiion
ol ihc Snowloaiu class. Thc Big Poini ihcic was ihai cvciy ol|cci holus noi |usi iis owr
ucclaicu insiancc vaiiallcs, lui also e.e.,L.r .o . ue.Ine which, ai a minimum,
mcans class Ol|cci, sincc e.e., class cxicnus Ol|cci).
So whcn an ol|cci is cicaicu lccausc somclouy saiu , ihcic is no other woy io cicaic
an ol|cci oihci ihan somconc, somcwhcic saying on ihc class iyc), ihc ol|cci
gcis sacc loi nII ihc insiancc vaiiallcs, liom all ihc way u ihc inhciiiancc iicc. ThinI
aloui ii loi a momcni... a suciclass mighi havc sciici mcihous cncasulaiing a iivaic
vaiiallc. Bui ihai vaiiallc has io livc oewLe.e. Whcn an ol|cci is cicaicu, ii`s almosi as
ihough uI.Ie ol|ccis maiciializc-ihc ol|cci lcing ncw`u anu onc ol|cci ci cach
suciclass. Concciually, ihough, ii`s much lciici io ihinI ol ii liIc ihc iciuic lclow,
whcic ihc ol|cci lcing cicaicu has In,e. ol iiscll icicscniing cach suciclass.
1--- : --|] 6N! --:l -- l- -. --- A
----.- --:l B-l l :--l.-: -l l-
----.- .-l: - l:-| .- l- 6-:l .-l: -
l:-| A|| -:l.-:- .-.|-: --- -l :|.::-: .-
l- - ---
----.- .|:- .: -:l.-:-
.-.|-: - l: ---, :- l- -.-
. ----.- --:l -- ---
:.:- -- l- -:l.-:- .-.|-:
- -l :|.::-:
Ob]ect
8nowboard
S
n
o
w
board
o
b
je
c
t
A :-|-
--:l --
l- -.
6-:l .: -:l.-:- .-.|-:
--:.:-|.l- ] .::-:: --l-:
1-:- -:l.-:- .-.|-: .--
:--.l- --- .-] :-:|.:: :
-:l.-l.l- |1-:- .---'l l-
!A| 6-:l .-.|-:, -l --
--'l :.-- -.l l-] .-- :-:-
l-]'-- --:.:-|.l-`
0bject
Foo a,
|rl o,
|rl c,
equa|s()
elC|ass()
|as|Code()
lo3lr|r()
8nowboard
Foo x
Foo y
|rl z
lurr()
s|red()
elA|r()
|oseCorlro|()

space for an object's supercIass parts


Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 251
Ihc re|c ef sepcrr|zss rens!rer!ers
|n zn e|jcr!s ||fc.
AII the constructors in on object`s inheritonce
tree must run when you mohe o new object.
Ici ihai sinI in.
Thai mcans cvciy suciclass has a consiiucioi
lccausc cvciy class has a consiiucioi), anu cach
consiiucioi u ihc hiciaichy iuns ai ihc iimc an
ol|cci ol a sulclass is cicaicu.
Saying is a Big Dcal. Ii siaiis ihc
wholc consiiucioi chain icaciion. Anu ycs,
cvcn alsiiaci classcs havc consiiuciois.
Alihough you can ncvci say ncw on an
alsiiaci class, an alsiiaci class is siill
a suciclass, so iis consiiucioi iuns
whcn somconc maIcs an insiancc ol a
concicic sulclass.
Thc suci consiiuciois iun io luilu
oui ihc suciclass aiis ol ihc ol|cci.
Rcmcmlci, a sulclass mighi inhciii
mcihous ihai uccnu on suciclass siaic
in oihci woius, ihc valuc ol insiancc vaiiallcs
in ihc suciclass). Ioi an ol|cci io lc lully-
loimcu, all ihc suciclass aiis ol iiscll musi lc
lully-loimcu, anu ihai`s why ihc suci consiiucioi
iun. All insiancc vaiiallcs liom cvciy class
in ihc inhciiiancc iicc havc io lc ucclaicu anu
iniiializcu. Evcn il Animal has insiancc vaiiallcs
ihai Hio uocsn`i inhciii il ihc vaiiallcs aic
iivaic, loi cxamlc), ihc Hio siill uccnus on
ihc Animal mcihous ihai ihosc vaiiallcs.
Whcn a consiiucioi iuns, ii immcuiaicly calls iis
suciclass consiiucioi, all ihc way u ihc chain
uniil you gci io ihc class Ol|cci consiiucioi.
On ihc ncxi lcw agcs, you`ll lcain how suciclass
consiiuciois aic callcu, anu how you can call
ihcm youiscll. You`ll also lcain whai io uo il youi
suciclass consiiucioi has aigumcnis!
A new Hippo object aIso IS-A Animal
and IS-A Ob]ect. If you want to make a
Hippo, you must aIso make the Animal
and Ob]ect parts of the Hippo.
This aII happens in a process caIIed
Constructor Chaining.
Hippo
A :-|- +- --:l -- l- -.
Ob]ect

Animal
An|ma|
0bject
h|ppo
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
252 chapter 9
1
Code from onofher
cIoss soys new
Hippo()ond fhe
Hippo{} consfrucfor
goes info o sfock
frome of fhe fop of
fhe sfock.
+-|`
A--.||`
+-|`
2
Hippo{} invokes
fhe supercIoss
consfrucfor which
pushes fhe AnimuI{}
consfrucfor onfo fhe
fop of fhe sfock.
6-:l|`
+-|`
A--.||`
3 4
Object{} compIefes,
ond ifs sfock frome
is popped off fhe
sfock. Execufion goes
bock fo fhe AnimuI{}
consfrucfor, ond
picks up of fhe Iine
foIIowing AnimoI's
coII fo ifs supercIoss
consfrucfor
AnimuI{} invokes
fhe supercIoss
consfrucfor which
pushes fhe Object{}
consfrucfor onfo
fhe fop of fhe sfock,
since Objecf is fhe
supercIoss of AnimoI.
A--.||`
+-|`
Mzk|n] z H|ppe mczns mzk|n] !hc
n|mz| zn4 0|jcr! pzr!s !ee...
public class Animal {
public Animal() {
System.out.println(Making an Animal);
}
}
public class Hippo extends Animal {
public Hippo() {
System.out.println(Making a Hippo);
}
}
public class TestHippo {
public static void main (String[] args) {
System.out.println(Starting...);
Hippo h = new Hippo();
}
}
File Edit Window Help Swear
% java TestHippo
Starting...
Making an Animal
Making a Hippo
File Edit Window Help Swear
% java TestHippo
Starting...
Making a Hippo
Making an Animal
+,-+ :+ ,-+:.|
A
B
what's the real outputI Given the
code on the left, what prints out
when you run TestHippoI A or 8I
(the answer is at the bottom of the page)
object construction
T | e l | r s l o r e , A . T | e l | p p o ( ) c o r s l r u c l o r | s | r v o | e d l | r s l , o u l
| l ' s l | e A r | r a | c o r s l r u c l o r l | a l l | r | s | e s l | r s l .
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
constructors and gc
you are here 253
Hew 4e yee |nvekc z sepcrr|zss rens!rer!er!
And how is it that we've
gotten away without
doing it?
You mighi ihinI ihai somcwhcic in, say, a DucI consiiucioi,
il DucI cxicnus Animal you`u call Animal). Bui ihai`s noi
how ii woiIs:
public class Duck extends Animal {
int size;
public Duck(int newSize) {
Animal();
size = newSize;
}
}
N
6
' 1
: : --l |-.|'
B
A
l
'
Thc only way io call a suci consiiucioi is ly calling super);.
Thai`s iighi-super); calls ihc super constructor.
Whai aic ihc ouus.
public class Duck extends Animal {
int size;
public Duck(int newSize) {
super();
size = newSize;
}
}
]-- -:l :.] :---|`
A call io ue.() in youi consiiucioi uis ihc suciclass
consiiucioi on ihc io ol ihc SiacI. Anu whai uo you
ihinI ihai suciclass consiiucioi uocs. CnII . ue.In
or.uo.. Anu so ii gocs uniil ihc Ol|cci consiiucioi is
on ihc io ol ihc SiacI. Oncc Obe() hnishcs, ii`s ocu
oll ihc SiacI anu ihc ncxi ihing uown ihc SiacI ihc
sulclass consiiucioi ihai callcu Obe()) is now on io.
TLn consiiucioi hnishcs anu so ii gocs uniil ihc oiiginal
consiiucioi is on ihc io ol ihc SiacI, whcic . can now
hnish.
ou probably figured that out.
Dur good friend the compiIer
puts in a caII to suer(} if you
don't.
So the compiler gets involved in
constructor-making in two ways:
The compiler puts one in that looks like:
public ClassName() {
super();
}
The compiler will put a call to super() in
each of your overloaded constructors.`
The compiler-supplied call looks like:
super();
|t always looks like that. The compiler-
inserted call to suet(} is always a no-arg
call. |f the superclass has overloaded
constructors, only the no-arg one is called.
1
2
If you Jenr provide a constructor
If you Je provide a constructor
but you do ner put in the caII to
super()
ur|ess l|e corslruclor ca||s arol|er over|oaded
corslruclor (you'|| see l|al |r a leW paes).
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
object IifecycIe
254 chapter 9
0zn !hc rh||4 cr|s! |cferc
!hc pzrcn!s!
Il you ihinI ol a suciclass as ihc aicni io ihc sulclass chilu,
you can hguic oui which has io cxisi hisi. The supercIoss ports
o[ on object hove to be [uIIy-[ormed )compIeteIy buiIt; be[ore the
subcIoss ports con be constructed. Rcmcmlci,
ihc sulclass ol|cci mighi uccnu on ihings ii
inhciiis liom ihc suciclass, so ii`s imoiiani
ihai ihosc inhciiicu ihings lc hnishcu. No
way aiounu ii. Thc suciclass consiiucioi
musi hnish lcloic iis sulclass consiiucioi.
IooI ai ihc SiacI sciics on agc 24S again,
anu you can scc ihai whilc ihc Hio
consiiucioi is ihc io lc invoIcu ii`s
ihc hisi ihing on ihc SiacI), ii`s ihc onc
io comlcic! Each sulclass consiiucioi
immcuiaicly invoIcs iis own suciclass
consiiucioi, uniil ihc Ol|cci consiiucioi
is on ihc io ol ihc SiacI. Thcn Ol|cci`s
consiiucioi comlcics anu wc louncc
lacI uown ihc SiacI io Animal`s
consiiucioi. Only alici Animal`s consiiucioi comlcics
uo wc hnally comc lacI uown io hnish ihc icsi ol ihc Hio
consiiucioi. Ioi ihai icason:
The call to super{} must be the hrst statement
in each constructorl*
Eewwww... fhof
is SO creepy. There's
woy I couId hove been
born before my porenfs.
Thof's jusf wrong.
*There's an exception to this rule; you'll learn it on page 252.
PossibIe consfrucfors for cIoss 8oop
public Boop() {
super();
}
public Boop(int i) {
super();
size = i;
}
1-:- .-- 6r -:.-:-
l- ---.---- -~ |:l|] :-- l- :.||
l- :---|`, .: l- -:l
:l.l----l
public Boop() {
}
public Boop(int i) {
size = i;
}
public Boop(int i) {
size = i;
super();
}
1-:- .-- 6r -:.-:-
l- :--|-- -|| -l .
:.|| l- :---|` - .: l-
-:l :l.l----l
BAl
'' 1: ---'l :--|-'
/-- :.-'l -|:l|] -l
l- :.|| l- :---|` -|--
.-]l- -|:-

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 255
8epcrr|zss rens!rer!ers w| !h zr]emcn!s
Whai il ihc suciclass consiiucioi has aigumcnis. Can you ass somcihing in io
ihc ue.() call. Ol couisc. Il you coulun`i, you`u ncvci lc allc io cxicnu a class
ihai uiun`i havc a no-aig consiiucioi. Imaginc ihis sccnaiio: all animals havc a
namc. Thcic`s a eNne() mcihou in class Animal ihai iciuins ihc valuc ol ihc
rne insiancc vaiiallc. Thc insiancc vaiiallc is maiIcu iivaic, lui ihc sulclass
in ihis casc, Hio) inhciiis ihc eNne() mcihou. So hcic`s ihc iollcm:
Hio has a eNne() mcihou ihiough inhciiiancc), lui uocs noi havc ihc rne
insiancc vaiiallc. Hio has io uccnu on ihc Animal aii ol himscll io Icc ihc
namc insiancc vaiiallc, anu iciuin ii whcn somconc calls eNne() on a Hio
ol|cci. Bui... how uocs ihc Animal aii gci ihc namc. Thc only iclcicncc Hio
has io ihc Animal aii ol himscll is ihiough ue.(), so ihai`s ihc lacc whcic
Hio scnus ihc Hio`s namc u io ihc Animal aii ol himscll, so ihai ihc
Animal aii can sioic ii in ihc iivaic rne insiancc vaiiallc.

pr|vale 3lr|r rare


Ar|ra|(3lr|r r)
3lr|r elNare()

l|ppo(3lr|r r)
[ol|er l|ppo-spe-
c|l|c rel|ods|
public abstract class Animal {
private String name;
public String getName() {
return name;
}
public Animal(String theName) {
name = theName;
}
}
A -ll-- --l- l.l +- ---l:
1- :--:l--:l-- l.l l.-: l- -.-- .- .::-:
l l- -.-- -:l.-:- .-.|-
A|| .--.|: |-:|--
:-:|.::-:` .- . -.--
public class Hippo extends Animal {
public Hippo(String name) {
super(name);
}
}
public class MakeHippo {
public static void main(String[] args) {
Hippo h = new Hippo(Buffy);
System.out.println(h.getName());
}
}
+- :--:l--:l-- l.-: . -.--
l :--: l- -.-- - l- l.: l-
l- A--.| :--:l--:l--
The AnimoI porf of
me needs fo know my nome,
so I foke o nome in my own
Hippo consfrucfor, fhen poss
fhe nome fo super()
M.- . +-, .::- l-
-.-- B-]' l- l- +-
:--:l--:l-- 1-- :.|| l-
+-': ---l- -lN.--|`
File Edit Window Help Hide
%java MakeHippo
Buffy
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
256 chapter 9
|nvek|n] enc evcr|ez4c4 rens!rer!er
frem zne!hcr
Whai il you havc ovciloaucu consiiuciois ihai, wiih
ihc cxcciion ol hanuling uillcicni aigumcni iycs,
all uo ihc samc ihing. You Inow ihai you uon`i wani
JuI.ne couc siiiing in cach ol ihc consiiuciois ain
io mainiain, cic.), so you`u liIc io ui ihc lulI ol ihc
consiiucioi couc incluuing ihc call io suci)) in only
ore ol ihc ovciloaucu consiiuciois. You wani whichcvci
consiiucioi is hisi invoIcu io call Thc Rcal Consiiucioi
anu lci Thc Rcal Consiiucioi hnish ihc |ol ol
consiiuciion. Ii`s simlc: |usi say L.(). Oi L.(nS..r).
Oi L.(27, :). In oihci woius, |usi imaginc ihai ihc
Icywoiu L. is a iclcicncc io thc currcnt objcct
You can say L.() only wiihin a consiiucioi, anu ii musi
lc ihc hisi siaicmcni in ihc consiiucioi!
Bui ihai`s a iollcm, isn`i ii. Eailici wc saiu ihai
suci) musi lc ihc hisi siaicmcni in ihc consiiucioi.
Wcll, ihai mcans you gci a choicc.
Every constructor can have a call to super{}
or this{}, but never bothl
caIIing overIoaded constructors
class Mini extends Car {
Color color;
public Mini() {
this(Color.Red);
}
public Mini(Color c) {
super(Mini);
color = c;
// more initialization
}
public Mini(int size) {
this(Color.Red);
super(size);

}
}
l
se th:sl I ta :a|| a
:aast:a:ta: I:a
aaathe:
ave:|aaJeJ :aast:a:ta: :a
the sa
e :|ass.
T
he :a|| ta th:sl I
:aa le aseJ aa|y :a a
:aast:a:ta:, aaJ
ast le
the I ::st state
eat :a a
:aast:a:ta:.
A
:aast:a:ta: :aa have a
:a|| ta sae:l I 0
k
th:sl I,
lat aeve: lath!
1- --~.- :--:l--:l--
:-|-: . -.-|l c-|-- .-
:.||: l- ---|-.- -.|
c--:l--:l-- |l- --- l.l
:.||: :---|``
1: : 1- -.| c--:l--:l-- l.l
--: 1- -.| w-- - -l.|-- l-
--:l |-:|-- l- :.|| l- :---|``
File Edit Window Help Drive
javac Mini.java
Mini.java:16: call to super must
be first statement in constructor
super();
^
w--'l ---'' c.-'l .-
:---|` .- l:|` - l- :.--
:--:l--:l--, -:.-:- l-] -.:
--:l - l- -:l :l.l----l'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 257
+,-+ :+ ,-+:.|
public class Boo {
public Boo(int i) { }
public Boo(String s) { }
public Boo(String s, int i) { }
}
class SonOfBoo extends Boo {
public SonOfBoo() {
super(boo);
}
public SonOfBoo(int i) {
super(Fred);
}
public SonOfBoo(String s) {
super(42);
}
public SonOfBoo(int i, String s) {
}
public SonOfBoo(String a, String b, String c) {
super(a,b);
}
public SonOfBoo(int i, int j) {
super(man, j);
}
public SonOfBoo(int i, int x, int y) {
super(i, star);
}
}

Some of the constructors in the SonOf8oo class will not
compile. See if you can recognize which constructors are
not legal. Match the compiler errors with the SonOf8oo
constructors that caused them, by drawing a line from the
compiler error to the "bad constructor.
File Edit Window Help mNotListening
%javac SonOfBoo.java
cannot resolve symbol
symbol:constructor Boo()
File Edit Window Help
%javac SonOfBoo.java
cannot resolve symbol
symbol : constructor Boo
(java.lang.String,java.la
ng.String)
File Edit Window Help Yadayadayada
%javac SonOfBoo.java
cannot resolve symbol
symbol : constructor Boo
(int,java.lang.String)

koses ote teJ, v|olets ote olue.


Yeur nrenrs cem
e Iirsr, w
ny beIere yeu.
The superclass parts of an ob|ect m
ust be fully-
form
ed before the new
subclass ob|ect can
exist. 1ust like there's no w
ay you could have
been born oelote your parents.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
258 chapter 9
hew wc knew hew zn e|jcr! |s |ern,
|e! hew |en] 4ecs zn e|jcr! || vc !
An obe` lilc uccnus cniiicly on ihc lilc ol iclcicnccs
iclciiing io ii. Il ihc iclcicncc is consiucicu alivc", ihc
ol|cci is siill alivc on ihc Hca. Il ihc iclcicncc uics
anu wc`ll looI ai whai ihai mcans in |usi a momcni), ihc
ol|cci will uic.
So iI an objcct's liIc dcpcnds on thc rcIcrcncc
variablc's liIc, how long docs a livc?
Thai uccnus on whcihci ihc vaiiallc is a IonI vaiiallc
oi an .rnre vaiiallc. Thc couc lclow shows ihc lilc ol a
local vaiiallc. In ihc cxamlc, ihc vaiiallc is a iimiiivc,
lui vaiiallc lilciimc is ihc samc whcihci ii`s a iimiiivc
oi iclcicncc vaiiallc.
:|--|`
--.|`
:
public class TestLifeOne {
public void read() {
int s = 42;
sleep();
}
public void sleep() {
s = 7;
}
}
A local variable lives only
within the method that
declared the variable.
variable '' can be used only within the
teoJ(} method. |n other words, rhe vnrinble
is in scee enly wirhin irs ewn merheJ. No
other code in the class (or any other class)
can see ''.
1
2
':' : ::--
l- l- --.
|`
-
-l-
, :- l :.-'l - -:-

.-]-
--- -|:-
An instance variable lives
as long as the ob]ect
does. f the ob]ect is still
alive, so are its instance
variables.
public void read() {
int s = 42;
// `s' can be used only
// within this method.
// When this method ends,
// `s' disappears completely.
}
public class Life {
int size;
public void setSize(int s) {
size = s;
// `s' disappears at the
// end of this method,
// but `size' can be used
// anywhere in the class
}
}
variable '' (this time a method parameter)
is in scope only within the setSize()
method. 8ut instance variable size is
scoped to the life of the ooject as opposed
to the life of the methoJ.
B
A
l
'' N
-
l
|-

.
| l
-

-
:-
':'
-
-
-
'
1
- .-.|- ':' : .|-, -l - ::-- --|] -l- l-
--.|` -
-l- w
-- :|--|` :--
|-l-: .- --.|` :
-- l- - l- l.: .- ----- ..-, --.|` :.-
:l|| :-- ':' w
-- --.|` :--
|-l-: .- : -- -
l- l.:, ':' : -. |-:- - l.| .:-:
:|--|` :.-'l :-- l- ':' .-.|- -:-
l': --l - :|--|`': --- l.: -.--,
:|--|` --:-'l --- .-]l- .--l l
object Iifespan
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 259
public void doStuff() {
boolean b = true;
go(4);
}
public void go(int x) {
int z = x + 24;
crazy();
// imagine more code here
}
public void crazy() {
char c = `a';
}
-l-|`

-|`
-l-|`

-
:-.-]|`
:
-l-|`

-|` -
-|`
-l-|`

-
1
do3tuff[} goes on the
8tack. Var|ab|e 'b' |s
a||ve and |n scope.
go[} p|ops on top of
the 8tack. 'x' and 'z'
are a||ve and |n scope,
and 'b' |s a||ve but not
|n scope.
crezy[} |s pushed onto
the 8tack, w|th 'c' now
a||ve and |n scope. The
other three var|ab|es
are a||ve but out of
scope.
crezy[} comp|etes and
|s popped off the 8tack,
so 'c' |s out of scope
end deed. when go(}
resumes where |t |eft
off, 'x' and 'z' are both
a||ve and back |n scope.
Var|ab|e 'b' |s st||| a||ve
but out of scope (unt||
go(} comp|etes}.
Life
8cope
A local vaiiallc is nI..e as long as iis SiacI
liamc is on ihc SiacI. In oihci woius,
ur.I Le eLoJ oIee.
A local vaiiallc is in oe only wiihin ihc
mcihou in which ihc vaiiallc was ucclaicu.
Whcn iis own mcihou calls anoihci, ihc
vaiiallc is alivc, lui noi in scoc uniil iis
mcihou icsumcs. You con use o voriobIe onIy
when it is in scope.
The difference between life and
scope for IocaI variabIes:
2 3 4
Whilc a local vaiiallc is alivc, iis siaic cisisis.
As long as mcihou uoSiull) is on ihc SiacI, loi
cxamlc, ihc l` vaiiallc Iccs iis valuc. Bui ihc
l` vaiiallc can lc uscu only whilc uoSiull)`s
SiacI liamc is ai ihc io. In oihci woius, you can
usc a local vaiiallc orI, whilc ihai local vaiiallc`s
mcihou is aciually iunning as ooscu io
waiiing loi highci SiacI liamcs io comlcic).
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
object IifecycIe
260 chapter 9
Thc iulcs aic ihc samc loi iimiivcs anu iclcicnccs. A iclcicncc
vaiiallc can lc uscu only whcn ii`s in scoc, which mcans you can`i usc
an ol|cci`s icmoic coniiol unlcss you`vc goi a iclcicncc vaiiallc ihai`s
in scoc. Thc .enI qucsiion is,
How docs voriobIe liIc aIIcct object liIc?
An ol|cci is alivc as long as ihcic aic livc iclcicnccs io ii. Il a iclcicncc
vaiiallc gocs oui ol scoc lui is siill alivc, ihc ol|cci ii .ee. io is siill
alivc on ihc Hca. Anu ihcn you havc io asI... Whai hacns whcn ihc
SiacI liamc holuing ihc iclcicncc gcis ocu oll ihc SiacI ai ihc cnu
ol ihc mcihou."
Il ihai was ihc orI, livc iclcicncc io ihc ol|cci, ihc ol|cci is now
alanuoncu on ihc Hca. Thc iclcicncc vaiiallc uisinicgiaicu wiih
ihc SiacI liamc, so ihc alanuoncu ol|cci is now, o.nII,, ioasi. Thc
iiicI is io Inow ihc oini ai which an ol|cci lccomcs eIigibIe [or gorboge
coIIection.
Oncc an ol|cci is cligillc loi gailagc collcciion GC), you uon`i havc
io woiiy aloui icclaiming ihc mcmoiy ihai ol|cci was using. Il youi
iogiam gcis low on mcmoiy, GC will ucsiioy somc oi all ol ihc cligillc
ol|ccis, io Icc you liom iunning oui ol RAM. You can siill iun oui ol
mcmoiy, lui ro lcloic all cligillc ol|ccis havc lccn haulcu oll io ihc
uum. Youi |ol is io maIc suic ihai you alanuon ol|ccis i.c, maIc
ihcm cligillc loi GC) whcn you`ic uonc wiih ihcm, so ihai ihc gailagc
collccioi has somcihing io icclaim. Il you hang on io ol|ccis, GC can`i
hcl you anu you iun ihc iisI ol youi iogiam uying a ainlul
oui-ol-mcmoiy ucaih.
Whz! z|ee! rcfcrcnrc vzr|z||cs!
aa eoeets ||Ie bas ae
va|ue, ae meaa|ag, ae
pe|at, ua|ess semeoeay
bas a reIereaee te |t.
tI yeu eaat get te |t,
yeu eaat ass |t te ae
aaytb|ag aaa |ts ust a
o|g Iat waste eI o|ts.
sut |I aa eoeet |s
uareaebao|e, tbe
aaroage ce||eeter w|||
gure tbat eut. seeaer
er |ater, tbat eoeets
ge|a aewa.
An ob]ect becomes
eligible for GC when
its last live reference
disappears.
Three ways to get rid of an ob]ect's reference:
1 The reference goes ouf of scope, permonenfIy
2 The reference is ossigned onofher objecf
3 The reference is expIicifIy sef fo nuII
void go() {
Life z = new Life();
}
Life z = new Life();
z = new Life();
Life z = new Life();
z = null;
------:- '-' -: .l
-- - --l-
l- -:l --:l : ..----
--- - : '-----.---' l-
. --- --:l
l- -:l --:l : ..----
--- - : '----.---'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 261
public class StackRef {
public void foof() {
barf();
}
public void barf() {
Duck d = new Duck();
}
}
D
u
c
k ob
j
e
c
f

.-|`
--|`
+
-
.

--|`
|s pushed onto the
8tack, no var|ab|es are
dec|ared.
1
|s pushed onto the
8tack, where |t dec|ares
a reference var|ab|e, and
creates a new object as-
s|gned to that reference.
The object |s created on
the heap, and the refer-
ence |s a||ve and |n scope.
2
--|`
comp|etes and pops
off the 8tack. |ts frame
d|s|ntegrates, so 'd' |s now
dead and gone. Execut|on
returns to , but
can't use 'd' .
3
D
u
c
k ob
j
e
c
f

+
-
.

1
- --- l
-: --: -- l-
+-., .- .: |-- .: .-|`
: -----, l- '' ------:-
: .|- .- - ::--, :- l-
l
-: : :--:--- .|-
c~- 1- '' .-.|-
---l .-.] --- l- .-|`
l.: -.-- -.: |---
- l- :l.:, :- l- l-:
: ..---- 6.-.-~
:-||-:l-- .l
I don'f Iike where
fhis is heoded.
Ob]ect-killer #1
Reference goes
out of scope,
permanently.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
object IifecycIe
262 chapter 9
Ob]ect-killer #2
Assign the reference
to another ob]ect
Dude, oII you
hod fo do wos resef
fhe reference. 0uess
fhey didn'f hove memory
monogemenf bock fhen.
public class ReRef {

Duck d = new Duck();
public void go() {
d = new Duck();
}
}
1- --- l-: --: -- l- +-., ------:-
] '' -:- '' : .- -:l.-:- .-.|-, l-
l-: -|| |- .: |-- .: l- -- --:l
l.l -:l.-l.l- l : .|- c-|-::
D
u
c
k ob
j
e
c
f

+
-
.

1
'' : .::-- . --- l-: --:l, |-.- l-
---.| |-:l` l-: --:l ..---- 1.l
-:l l-: : --- .: -- .: -.

D
u
c
k ob
j
e
c
f

+
-
.

D
u
c
k ob
j
e
c
f

w-- :------ :.||: l-
-|` --l-, l: l-: :
..---- +: --|] ------:-
.: --- -----.--- -- .
----l l-:
P
e
P
e
f ob
j
e
c
f

P
e
P
e
f ob
j
e
c
f

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
constructors and gc
you are here 263
Ob]ect-killer #3
Explicitly set the
reference to null
public class ReRef {

Duck d = new Duck();
public void go() {
d = null;
}
}
1- --- l-: --: -- l- +-., ------:-
] '' -:- '' : .- -:l.-:- .-.|-, l-
l-: -|| |- .: |-- .: l- -- --:l
l.l -:l.-l.l- l : .|- c-|-::
D
u
c
k ob
j
e
c
f

+
-
.

'' : :-l l- --||, -: : -:l |- .- . ----l-


:--l--| l.l :-'l ---.--- l- .-]l- /--'-- --l
--- .||--- l- -:- l- -l ---.l-- -- '' --l| l':
-----.--- |.::-- .- --:l`
D
u
c
k ob
j
e
c
f

+
-
.

1: l-: : ..----
+: --|] ------:- .: ---
:-l l- --||
The meaning of null
when you set a reference to null, you're
deprogramming the remote control.
|n other words, you've got a remote
control, but no Tv at the other end. A null
reference has bits representing 'null' (
don't know or care what those bits are, as
long as the 1vM knows).
|f you have an unprogrammed remote
control, in the real world, the buttons don't
do anything when you press them. 8ut
in 1ava, you can't press the buttons (i.e.
use the dot operator) on a null reference,
because the 1vM knows (this is a runtime
issue, not a compiler error) that you're
expecting a bark but there's no Dog there
to do it!
If you use the dot operator on
a nuII reference, you'II get a
NuIIPointerxception at runtime. ou'll
learn all about Lxceptions in the Pisky
8ehavior chapter.
P
e
P
e
f ob
j
e
c
f

P
e
P
e
f ob
j
e
c
f

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
object IifecycIe
264 chapter 9
Instance Variable
I`u liIc io go hisi, lccausc I icnu io lc moic
imoiiani io a iogiam ihan a local vaiiallc.
I`m ihcic io suoii an ol|cci, usually
ihioughoui ihc ol|cci`s cniiic lilc. Alici all,
whai`s an ol|cci wiihoui ne. Anu whai is
siaic. Valucs Ici in instonce voriobIes.
No, uon`i gci mc wiong, I uo unucisianu youi
iolc in a mcihou, ii`s |usi ihai youi lilc is so
shoii. So icmoiaiy. Thai`s why ihcy call you
guys icmoiaiy vaiiallcs".
My aologics. I unucisianu comlcicly.
I ncvci ically ihoughi aloui ii liIc ihai. Whai
aic you uoing whilc ihc oihci mcihous aic
iunning anu you`ic waiiing loi youi liamc io
lc ihc io ol ihc SiacI again.
Lecal Variable
I aicciaic youi oini ol vicw, anu I cciiainly
aicciaic ihc valuc ol ol|cci siaic anu all,
lui I uon`i wani lolIs io lc mislcu. Iocal
vaiiallcs aic .enII, imoiiani. To usc youi
hiasc, Alici all, whai`s an ol|cci wiihoui
beLn..o.." Anu whai is lchavioi. Algoiiihms
in mcihous. Anu you can lci youi liis ihcic`ll
lc somc IonI .n..nbIe in ihcic io maIc ihosc
algoiiihms woiI.
Wiihin ihc local-vaiiallc communiiy, ihc
hiasc icmoiaiy vaiiallc" is consiucicu
uciogaioiy. Wc iclci local", siacI", auio-
maiic", oi "Scoc-challcngcu".
Anyway, ii`s iiuc ihai wc uon`i havc a long
lilc, anu ii`s noi a aiiiculaily ooJ lilc ciihci.
Iiisi, wc`ic shovcu inio a SiacI liamc wiih
all ihc oihci local vaiiallcs. Anu ihcn, il ihc
mcihou wc`ic aii ol calls anoihci mcihou,
anoihci liamc is ushcu on io ol us. Anu il
Ln mcihou calls nroLe. mcihou... anu so on.
Somciimcs wc havc io waii loicvci loi all ihc
oihci mcihous on io ol ihc SiacI io com-
lcic so ihai oui mcihou can iun again.
Noihing. Noihing ai all. Ii`s liIc lcing in
siasis-ihai ihing ihcy uo io colc in scicncc
hciion movics whcn ihcy havc io iiavcl long
uisianccs. Suscnucu animaiion, ically. Wc
|usi sii ihcic on holu. As long as oui liamc is
siill ihcic, wc`ic salc anu ihc valuc wc holu
is sccuic, lui ii`s a mixcu llcssing whcn oui
1cnih|`s 1alk: An instance variable and
a lecal variable discass life and death
{with remarkable civility}
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 265
Wc saw an cuucaiional viuco aloui ii oncc.
IooIs liIc a iciiy liuial cnuing. I mcan,
whcn ihai mcihou hiis iis cnuing cuily liacc,
ihc liamc is liicially bIowr oll ihc SiacI! Now
Ln` goiia huii.
I livc on ihc Hca, wiih ihc ol|ccis. Wcll, noi
w.L ihc ol|ccis, aciually .r an ol|cci. Thc
ol|cci whosc siaic I sioic. I havc io aumii lilc
can lc iciiy luxuiious on ihc Hca. A loi ol
us lccl guiliy, csccially aiounu ihc holiuays.
OK, hyoihciically, ycs, il I`m an insiancc
vaiiallc ol ihc Collai anu ihc Collai gcis
GC`u, ihcn ihc Collai`s insiancc vaiiallcs
woulu inuccu lc iosscu oui liIc so many izza
loxcs. Bui I was iolu ihai ihis almosi ncvci
hacns.
Thcy lci us J..rI.
liamc gcis io iun again. On ihc onc hanu, wc
gci io lc aciivc again. On ihc oihci hanu, ihc
clocI siaiis iicIing again on oui shoii livcs.
Thc moic iimc oui mcihou scnus iunning,
ihc closci wc gci io ihc cnu ol ihc mcihou.
Wc nII Inow whai hacns ihcn.
Tcll mc aloui ii. In comuici scicncc ihcy usc
ihc icim oeJ as in ihc liamc was ocu
oll ihc SiacI". Thai maIcs ii sounu lun, oi
maylc liIc an cxiicmc soii. Bui, wcll, you
saw ihc looiagc. So why uon`i wc ialI aloui
you. I Inow whai my liiilc SiacI liamc looIs
liIc, lui whcic uo ,ou livc.
Bui you uon`i nIwn, livc as long as ihc ol|cci
who ucclaicu you, iighi. Say ihcic`s a Dog
ol|cci wiih a Collai insiancc vaiiallc. Imaginc
,ou`.e an insiancc vaiiallc ol ihc CoIIn. ol|cci,
maylc a iclcicncc io a BucIlc oi somcihing,
siiiing ihcic all hay insiuc ihc CoIIn. ol|cci
who`s all hay insiuc ihc Do ol|cci. Bui...
whai hacns il ihc Dog wanis a ncw Collai,
oi ruII oui iis Collai insiancc vaiiallc. Thai
maIcs ihc Collai ol|cci cligillc loi GC. So...
il ,ou`.e an insiancc vaiiallc insiuc ihc Collai,
anu ihc wholc CoIIn. is alanuoncu, whai
hacns io ,ou.
Anu you lclicvcu ii. Thai`s whai ihcy say io
Icc us moiivaicu anu iouuciivc. Bui aicn`i
you loigciiing somcihing clsc. Whai il you`ic
an insiancc vaiiallc insiuc an ol|cci, anu ihai
ol|cci is iclcicnccu orI, ly a IonI vaiiallc. Il
I`m ihc only iclcicncc io ihc ol|cci you`ic in,
whcn I go, you`ic coming wiih mc. IiIc ii oi
noi, oui laics may lc connccicu. So I say wc
loigci aloui all ihis anu go gci uiunI whilc
wc siill can. Caic RAM anu all ihai.
1nstance VarIabIe LccaI VarIabIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
266 chapter 9
y[je[ | ([ ]jn, | e] n ([ jg[(, j| z]]]
( ([ e]z,, n ([ ]|( z( jn( j, wa]] eza,
yze(]y n z]]j(jnz] je( ( ]jgj] | ([
(zzg (]]e(/ (j,,a ([z( jn( j (//ez]]
([],) wj]] yea( | z ]ng (j, gjvjng ([
(zzg (]]e( (j ( ] j(, ,(a||.)

] ge (;ge [o||eeo;
public class GC {
public static GC doStuff() {
GC newGC = new GC();
doStuff2(newGC);
return newGC;
}
public static void main(String [] args) {
GC gc1;
GC gc2 = new GC();
GC gc3 = new GC();
GC gc4 = gc3;
gc1 = doStuff();
// call more methods
}
public static void doStuff2(GC copyGC) {
GC localGC = copyGC;
}
}
File Edit Window Help Sleep

I
Z
3
4
b
o
7
8
9
copyGC = null;
gc2 = null;
newGC = gc3;
gc1 = null;
newGC = null;
gc4 = null;
gc3 = gc2;
gc1 = gc4;
gc3 = null;
exercise: Be the Garbage CoIIector
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 267
class Bees {
Honey beeHA,
}
class Raccoon {
Kit k,
Honey rh,
}
class Kit {
Honey kh,
}
class Bear {
Honey hunny,
}
public class Honey {
public static void main{String args| {
Honey honeyPot = new Honey{|,
Honey ha = {honeyPot, honeyPot, honeyPot, honeyPot},
Bees bl = new Bees{|,
bl.beeHA = ha,
Bear ba = new Bear5,
for {int x=0, x < 5, x++| {
bax = new Bear{|,
bax.hunny = honeyPot,
}
Kit k = new Kit{|,
k.kh = honeyPot,
Raccoon r = new Raccoon{|,
r.rh = honeyPot,
r.k = k,
k = null,
} // end of main
}
]a[|i
ubjcc[s
|n this code example, several new ob|ects are created.
our challenge is to find the ob|ect that is 'most popular',
i.e. the one that has the most reference variables referring
to it. Then list how total references there are for
that ob|ect, and what they are! we'll start by pointing out
one of the new ob|ects, and its reference variable.
Good Luck !
Here's u new
Puccoon object|
Here's its reference
vuriubIe 'r',

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
268 chapter 9
]Jc_Jna[c
_s[ci
'We`ve run the simulation four times, and the main module`s temperature consistently
drifts out of nominal towards cold, Sarah said, exasperated. 'We installed the new temp-bots last
week. The readings on the radiator bots, designed to cool the living quarters, seem to be within
spec, so we`ve focused our analysis on the heat retention bots, the bots that help to warm the quar-
ters. Tom sighed, at frst it had seemed that nano-technology was going to really put them ahead
of schedule. Now, with only fve weeks left until launch, some of the orbiter`s key life support
systems were still not passing the simulation gauntlet.
'What ratios are you simulating?, Tom asked.
'Well if I see where you`re going, we already thought of that, Sarah replied. 'Mis-
sion control will not sign off on critical systems if we run them out of spec. We are
required to run the v3 radiator bot`s SimUnits in a 2:1 ratio with the v2 radiator`s
SimUnits, Sarah continued. 'Overall, the ratio of retention bots to radiator bots is
supposed to run 4:3.
'How`s power consumption Sarah?, Tom asked. Sarah paused, 'Well that`s
another thing, power consumption is running higher than anticipated. We`ve got a team
tracking that down too, but because the nanos are wireless it`s been hard to isolate the power
consumption of the radiators from the retention bots. 'Overall power consumption ratios, Sarah
continued, 'are designed to run 3:2 with the radiators pulling more power from the wireless grid.
'OK Sarah, Tom said 'Let`s take a look at some of the simulation initiation code.
We`ve got to fnd this problem, and fnd it quick!
import ava.util.*,
class V2Radiator {
V2Radiator{ArrayList list| {
for{int x=0, x<5, x++| {
list.add{new SimUnit{"V2Radiator"||,
}
}
}
class V3Radiator extends V2Radiator {
V3Radiator{ArrayList lglist| {
super{lglist|,
for{int g=0, g<l0, g++| {
lglist.add{new SimUnit{"V3Radiator"||,
}
}
}
class RetentionBot {
RetentionBot{ArrayList rlist| {
rlist.add{new SimUnit{"Retention"||,
}
}
puzzIe: Five Minute Mystery
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 269
public class TestLifeSupportSim {
public static void main{String args| {
ArrayList aList = new ArrayList{|,
V2Radiator v2 = new V2Radiator{aList|,
V3Radiator v3 = new V3Radiator{aList|,
for{int z=0, z<20, z++| {
RetentionBot ret = new RetentionBot{aList|,
}
}
}
class SimUnit {
String botType,
SimUnit{String type| {
botType = type,
}
int powerUse{| {
if {"Retention".equals{botType|| {
return 2,
} else {
return 4,
}
}
}
Tom gave the code a quick look and a small smile creeped across his lips. I think I`ve
found the problem Sarah, and I bet I know by what percentage your power usage readings are off
too!
What did Tom suspect? How could he guess the power readings errors, and what few
lines of code could you add to help debug this program?
]Jc_Jna[c
_s[ci
cn[Jnacc...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
object IifecycIe
270 chapter 9
public class Honey {
public static void main{String args| {
Honey honeyPot = new Honey{|,
Honey ha = {honeyPot, honeyPot,
honeyPot, honeyPot},
Bees bl = new Bees{|,
bl.beeHA = ha,
Bear ba = new Bear5,
for {int x=0, x < 5, x++| {
bax = new Bear{|,
bax.hunny = honeyPot,
}
Kit k = new Kit{|,
k.kh = honeyPot,
Raccoon r = new Raccoon{|,
r.rh = honeyPot,
r.k = k,
k = null,
} // end of main
}
Honey
Objecf
( ends up nuII )
]a[|i
ubjcc[s
|t probably wasn't too hard to gure out that the Honey ob|ect rst referred to by the honeyPot variable is by
far the most 'popular' ob|ect in this class. 8ut maybe it was a little trickier to see that all of the variables that
point from the code to the Honey ob|ect refer to the snme ebjecr! There are a total of l2 active references to
this ob|ect right before the main( ) method completes. The variable is valid for a while, but k gets nulled
at the end. Since still refers to the Kit ob|ect, (although never explicity declared), refers to the ob|ect!
I
Z
3
4
b
o
7
8
9
copyGC = null;
gc2 = null;
newGC = gc3;
gc1 = null;
newGC = null;
gc4 = null;
gc3 = gc2;
gc1 = gc4;
gc3 = null;
Mo - fhis Iine offempfs fo occess o voriobIe
fhof is ouf of scope.
OI - gcZ wos fhe onIy reference voriobIe
referring fo fhof objecf.
Mo - onofher ouf of scope voriobIe.
OI - gcI hod fhe onIy reference becouse
new0C is ouf of scope.
Mo - new0C is ouf of scope.
Mo - gc3 is sfiII referring fo fhof objecf.
Mo - gc4 is sfiII referring fo fhof objecf.
OI - Peossigning fhe onIy reference fo
fhof objecf.
Mo - gc4 is sfiII referring fo fhof objecf.
(.[.
]e;ejze o|ajoz
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 271
]Jc_Jna[c _s[ci [a[Jn
Tom noticed that the constructor for the V2Radiator class took an
ArrayList. That meant that every time the Radiator constructor was called,
it passed an ArrayList in its super() call to the Radiator constructor. That
meant that an extra fve V2Radiator SimUnits were created. If Tom was right,
total power use would have been 120, not the 100 that Sarah`s expected ratios
predicted.
Since all the Bot classes create SimUnits, writing a constructor for
the SimUnit class, that printed out a line everytime a SimUnit was created,
would have quickly highlighted the problem!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
this is a new chapter 273
10 numbers and statics
Numbers Matter
Do the Math. 8ut there's more to working with numbers than |ust doing primitive
arithmetic. ou might want to get the absolute value of a number, or round a number, or find
the larger of two numbers. ou might want your numbers to print with exactly two decimal
places, or you might want to put commas into your large numbers to make them easier to read.
And what about working with datesI ou might want to print dates in a variety of ways, or even
mon|ulote dates to say things like, "add three weeks to today's date. And what about parsing
a String into a numberI Or turning a number into a StringI ou're in luck. The 1ava AP| is full of
handy number-tweaking methods ready and easy to use. 8ut most of them are , so we'll
start by learning what it means for a variable or method to be static, including constants in
1avastatic l|nol variables.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
274 chapter 10
Math methods
p([], jn ([ pz([ e]z,,
]n'( a, zny jn,(zne
vzjz] vz]a,. jn] eza,
([ ([], z ',(z(je',
ya ]n'( n] ( [zv zn
jn,(zne | pz([. j]] ya
n] j, ([ pz([ e]z,,.
MIH mc!he4s: zs r|esc zs yee||
cvcr ]c! !e z ]|e|z| mc!he4
Excci ihcic`s no glolal nr,L.r in ]ava. Bui ihinI aloui
ihis: whai il you havc a mcihou whosc lchavioi uocsn`i
uccnu on an insiancc vaiiallc valuc. TaIc ihc iounu)
mcihou in ihc Maih class, loi cxamlc. Ii uocs ihc samc
ihing cvciy iimc-iounus a uoaiing oini numlciihc
aigumcni io ihc mcihou) io ihc ncaicsi inicgci. Evciy
iimc. Il you hau 10,000 insianccs ol class Maih, anu ian
ihc iounu42.2) mcihou, you`u gci an inicgci valuc ol
42. Evciy iimc. In oihci woius, ihc mcihou acis on ihc
aigumcni, lui is ncvci allccicu ly an insiancc vaiiallc
siaic. Thc only valuc ihai changcs ihc way ihc iounu)
mcihou iuns is ihc aigumcni asscu io ihc mcihou!
Docsn`i ii sccm liIc a wasic ol cilccily goou hca sacc
io maIc an insiancc ol class Maih simly io iun ihc
iounu) mcihou. Anu whai aloui oLe. Maih mcihous
liIc min), which iaIcs iwo numciical iimiiivcs anu
iciuins ihc smallci ol ihc iwo. Oi max). Oi als), which
iciuins ihc alsoluic valuc ol a numlci.
These methods never use instonce voriobIe voIues. In laci ihc
Maih class uocsn`i Ln.e any insiancc vaiiallcs. So ihcic`s
noihing io lc gaincu ly maIing an insiancc ol class
Maih. So gucss whai. You uon`i havc io. As a maiici ol
laci, you can`i.
1: ----- :--: l.l l- M.l
:--:l--:l-- : -.-- -.l-' 1.l --.-: ]-- :.- N!/! :.] '---' -- l- M.l :|.:: l- -.- . --- M.l --:l
File Edit Window Help wasToldThereWouldBeNoMath
%javac TestMath
TestMath.java:3: Math() has private
access in java.lang.Math
Math mathObject = new Math();
^
1 error
Math mathObject = new Math();
f you try to make an instance of
class Math:
You'll get this error:
int x = Math.round(42.2);
int y = Math.min(56,12);
int z = Math.abs(-343);
1-:- --l-: ---- -:-
-:l.-:- .-.|-:, :- l--
-.-- --:-'l --- l-
--- .--l . :-:: --:l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 275
Ihc 4|ffcrcnrc |c! wccn rc]e|zr
|nen-s!z!|rI zn4 s!z!|r mc!he4s
]ava is ol|cci-oiicnicu, lui oncc in a whilc you havc a sccial casc,
iyically a uiiliiy mcihou liIc ihc Maih mcihous), whcic ihcic is
no nccu io havc an insiancc ol ihc class. Thc Icywoiu static lcis
a mcihou iun without ony instonce o[ the cIoss. A siaiic mcihou mcans
lchavioi noi uccnucni on an insiancc vaiiallc, so no insiancc/ol|cci
is icquiicu. ]usi ihc class."
PoIitik
CoIdpIoy
Song

s2.play();
s3.play();
c
.
||-

|.
]
|
`

-
-

l

:

-
-

-
-
-
-
:
-

-
||
:
.
-
:
-

|
-
|l

'

l
-

|.
]

c.||- |.]|` -- l:
------:- -|| :.-:-
M] w.]' l- |.]
My Wuy
Sex PisfoIs
Song

Son
g

o
b
j
e
c
f

public class Song {
String title;
public Song(String t) {
title = t;
}
public void play() {
SoundPlayer player = new SoundPlayer();
player.playSound(title);
}
public static int min(int a, int b){
//returns the lesser of a and b
}

r|r()
rax()
aos()
...
l|l|e
p|ay()
regular {non-static} method static method
1- :-----l .|-- - l- 'll|-'
-:l.-:- .-.|- : l- :-- l.l
|.]: --- ]-- :.|| |.]|`
N- -:l.-:- .-.|-:
1- --l- -.--
--:-'l :.-- -l
-:l.-:- .-.|- :l.l-
Math.min(42,36);
N
6 6B
)!
c
1
''
A
:-|-l-|] N
6 6B
)!
c
1

.-]---- - l: :l--- '
c:- l- c|.:: -.--, -.l--
l.- . ------:- .-.|-
-.--
l
-
-

-
:
l
.
-
:
-
:

-


:
|.
:
:

-
-

|-:l.-:- .-.|- .|-- .-:l:


l- -.-- - l- |.]|`
--l-
Son
g

o
b
j
e
c
f

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
static methods
276 chapter 10
Math.min(88,86);
Call a static method using a
class name

r|r()
rax()
aos()
...
Call a non-static method using a
reference variable name

Song t2 = new Song();
t2.play();
Whz! | ! mczns !e hzvc z
r|zss w| !h s!z!|r mc!he4s.
Olicn alihough noi always), a class wiih siaiic
mcihous is noi mcani io lc insianiiaicu. In Chaici
S wc ialIcu aloui alsiiaci classcs, anu how maiIing
a class wiih ihc abstract mouihci maIcs ii
imossillc loi anyonc io say ncw` on ihai class iyc.
In oihci woius, it`s impossibIe to instontiote on obstroct
cIoss.
Bui you can icsiiici oihci couc liom insianiiaiing
a ror-alsiiaci class ly maiIing ihc consiiucioi
private. Rcmcmlci, a eLoJ maiIcu iivaic mcans
ihai only couc liom wiihin ihc class can invoIc
ihc mcihou. A or.uo. maiIcu iivaic mcans
csscniially ihc samc ihing-only couc liom wiihin
ihc class can invoIc ihc consiiucioi. Nolouy can
say ncw` liom ou.Je ihc class. Thai`s how ii woiIs
wiih ihc Maih class, loi cxamlc. Thc consiiucioi
is iivaic, you cannoi maIc a ncw insiancc ol Maih.
Thc comilci Inows ihai youi couc uocsn`i havc
acccss io ihai iivaic consiiucioi.
This uocs ro mcan ihai a class wiih onc oi moic
siaiic mcihous shoulu ncvci lc insianiiaicu. In laci,
cvciy class you ui a main) mcihou in is a class wiih
a siaiic mcihou in ii!
Tyically, you maIc a main) mcihou so ihai you
can launch oi icsi anoihci class, ncaily always ly
insianiiaiing a class in main, anu ihcn invoIing a
mcihou on ihai ncw insiancc.
So you`ic licc io comlinc siaiic anu non-siaiic
mcihous in a class, alihough cvcn a singlc non-siaiic
mcihou mcans ihcic musi lc oe way io maIc an
insiancc ol ihc class. Thc only ways io gci a ncw
ol|cci aic ihiough ncw` oi ucsciializaiion oi
somcihing callcu ihc ]ava Rcucciion API ihai wc
uon`i go inio). No oihci way. Bui cxacily wLo says ncw
can lc an inicicsiing qucsiion, anu onc wc`ll looI ai
a liiilc laici in ihis chaici.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 277
8!z!|r mc!he4s rzn! esc nen-s!z!|r
||ns!znrcI vzr|z||cs|
Siaiic mcihous iun wiihoui Inowing aloui any aiiiculai
insiancc ol ihc siaiic mcihou`s class. Anu as you saw on
ihc icvious agcs, ihcic mighi noi cvcn be any insianccs
ol ihai class. Sincc a siaiic mcihou is callcu using ihc In
.ianuom)) as ooscu io an .rnre .ee.ere .lay)),
a siaiic mcihou can`i iclci io any insiancc vaiiallcs ol ihc
class. Thc siaiic mcihou uocsn`i Inow wL.L insiancc`s vaiiallc
valuc io usc.
]| ya (y ( a, zn
jn,(zne vzjz] |
jn,j] z ,(z(je ([],
([ ej] ([jn[,,
] ]n'( [nw w[je[
je(', jn,(zne vzjz]
ya' (z][jng za([
]| ya [zv (n ]ae[
je(, n ([ [z, z
,(z(je ([] ],n'(
[nw za( zny | ([.
public class Duck {
private int size;
public static void main (String[] args) {
System.out.println(Size of duck is + size);
}
public void setSize(int s) {
size = s;
}
public int getSize() {
return size;
}
}

f you try to compile this code:
I'm sure fhey're
foIking obouf MY
si;e voriobIe.
Mo, I'm preffy sure
fhey're foIking obouf
MY si;e voriobIe.
w
: l
-:
w
-:- :--
You'll get this error:
File Edit Window Help Quack
% javac Duck.java
Duck.java:6: non-static variable
size cannot be referenced from a
static context
System.out.println(Size
of duck is + size);
^
| l---': . l-: --
l- -. :-------, --
--'l --- .--l l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
static methods
278 chapter 10
8!z!|r mc!he4s rzn! esc nen-s!z!|r
mc!he4s, c| !hcr|
Whai uo non-siaiic mcihous uo. They usuoIIy use instonce
voriobIe stote to o[[ect the behovior o[ the method. A gciNamc)
mcihou iciuins ihc valuc ol ihc namc vaiiallc. Whosc namc.
Thc ol|cci uscu io invoIc ihc gciNamc) mcihou.
public class Duck {
private int size;
public static void main (String[] args) {
System.out.println(Size is + getSize());
}
public void setSize(int s) {
size = s;
}
public int getSize() {
return size;
}
}

This won't compile:
c.||- -l--|` -:l -:l---:
l- --l.|---l--|` -:-: l- :-- -:l.-:- .-.|-
File Edit Window Help Jack-in
% javac Duck.java
Duck.java:6: non-static method
getSize() cannot be referenced
from a static context
System.out.println(Size
of duck is + getSize());
^
B.: l- l- :.-- --|--
--:- :--
(-,- a,- |
oa|| qa--(:|-

What if you try to caII a non-static
method from a static method, but the
non-static method doesn't use any in-
stance variabIes. WiII the compiIer aIIow
that!

No. The compiler knows that
whether you do or do not use instance
variables in a non-static method, you con.
And think about the implications... if you
were allowed to compile a scenario like
that, then what happens if in the future
you want to change the implementation
of that non-static method so that one day
it Joes use an instance variableI Or worse,
what happens if a subclass ovett|Jes the
method and uses an instance variable in
the overriding versionI

I couId swear I've seen code that
caIIs a static method using a reference
variabIe instead of the cIass name.
ou con do that, but as your mother
always told you, "1ust because it's legal
doesn't mean it's good. Although it wotls
to call a static method using any instance
of the class, it makes for misleading (less-
readable) code. ou con say,
Duck d = new Duck();
String[] s = {};
d.main(s);
This code is legal, but the compiler |ust
resolves it back to the real class anyway
("OK, J is of type Duck, and main() is static,
so |'ll call the static main() in class Duck).
|n other words, using J to invoke main()
doesn't imply that main() will have any
special knowledge of the ob|ect that J is
referencing. |t's |ust an alternate woy to
invoke a static method, but the method is
still static!
DateFormat.getDateTimeInstance();
DateFormat.getTimeInstance();
NumberFormat.getPercentInstance();
M
.-
l
l:
koses ote teJ,
onJ lnown to oloom lote
5rnrics cnnr see
insrnnce vnrinble srnre
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 279
!.: l-: --:l .: l: ---
:-- .-.|-, -l l---': --|]
--- :-] - l- -:c---l
.-.|--l- --- - l- :|.::
8!z!|r vzr|z||c:
vz|ec |s !hc szmc fer II
|ns!znrcs ef !hc r|zss
Imaginc you wanicu io couni how many DucI
insianccs aic lcing cicaicu whilc youi iogiam is
iunning. How woulu you uo ii. Maylc an insiancc
vaiiallc ihai you incicmcni in ihc consiiucioi.
class Duck {
int duckCount = 0;
public Duck() {
duckCount++;
}
}
No, ihai woulun`i woiI lccausc uucICouni is an
insiancc vaiiallc, anu siaiis ai 0 loi cach DucI. You
coulu iiy calling a mcihou in somc oihci class, lui
ihai`s Iluugcy. You nccu a class ihai`s goi only a singlc
coy ol ihc vaiiallc, anu all insianccs shaic ihai onc
coy.
Thai`s whai a siaiic vaiiallc givcs you: a valuc shaicu
ly all insianccs ol a class. In oihci woius, onc valuc
ci , insicau ol onc valuc ci .
l: ---| .|-.]: :-l -:c---l l- | -.: l--
. l-: -.: -.-
public class Duck {
private int size;
private static int duckCount = 0;

public Duck() {
duckCount++;
}
public void setSize(int s) {
size = s;
}
public int getSize() {
return size;
}
}
N-- l -|| --
-:-----l- -.: l--
l- l-: :--:l--:l-- ---:,
-:.-:- -:c---l : :l.l:
.- ---'l - --:-l l- o
1
- :l.l: -:c
---l
.-.|- : -l.|-- 6
N
|
/

-
-- l- :|.:: : -:l
|-.-, N
6
1
-.: l-
- .
---
-:l.-:- : -
.-
A
l
-: --:l --:-'l -- l: --
- :-]
- -:c
---l
B
-:.-:- -:c
---l : :l.l:, l
-: --:l:
.|| :.-- . :-|- :-] - l /
-- :.- l-
- . :l.l: .-.|- .: . .-.|- l.l |-:
- . c
|
A
-:l-. - - .- --:l
D
u
c
k
ob
j
e
c
f

size: 1Z
duckCounf: 4
D
u
c
k
ob
j
e
c
f

size: ZZ
duckCounf: 4
D
u
c
k
ob
j
e
c
f

size:
duckCounf: 4
D
u
c
k
ob
j
e
c
f

size: Z0
duckCounf: 4

s|ze
slal|c duc|Courl
el3|ze()
sel3|ze()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
280 chapter 10
Larlier in this chapter, we saw that a private
constructor means that the class can't be instantiated
from code running outside the class. |n other words,
only code from within the class can make a new
instance of a class with a private constructor. (There's
a kind of chicken-and-egg problem here. )
what if you want to write a class in such a way that
only ONL instance of it can be created, and anyone
who wants to use an instance of the class will always
use that one, single instanceI
Stati: va:ial|es a:e sha:eJ.
A|| iastaa:es aI the sae
:|ass sha:e a siag|e :ay aI
the stati: va:ial|es.
insfonce voriobIes: I per
sfofic voriobIes: I per

8f8l 88f00ll
-:l.-:- ---
-:l.-:- l--
:l.l: .-.|-
:-c--.-
static variabIes
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 281
|n| !|z||z|n] z s!z!|r vzr|z||c
Siaiic vaiiallcs aic iniiializcu whcn a In . IonJeJ. A class is
loaucu lccausc ihc ]VM ucciucs ii`s iimc io loau ii. Tyically,
ihc ]VM loaus a class lccausc somclouy`s iiying io maIc a
ncw insiancc ol ihc class, loi ihc hisi iimc, oi usc a siaiic
mcihou oi vaiiallc ol ihc class. As a iogiammci, you also
havc ihc oiion ol iclling ihc ]VM io loau a class, lui you`ic
noi liIcly io nccu io uo ihai. In ncaily all cascs, you`ic lciici
oll lciiing ihc ]VM ucciuc whcn io IonJ ihc class.
Anu ihcic aic iwo guaianiccs aloui siaiic iniiializaiion:
Siaiic vaiiallcs in a class aic iniiializcu lcloic any obe ol ihai
class can lc cicaicu.
Siaiic vaiiallcs in a class aic iniiializcu lcloic any n. eLoJ
ol ihc class iuns.
class Player {
static int playerCount = 0;
private String name;
public Player(String n) {
name = n;
playerCount++;
}
}
public class PlayerTestDrive {
public static void main(String[] args) {
System.out.println(Player.playerCount);
Player one = new Player(Tiger Woods);
System.out.println(Player.playerCount);
}
}
Siaiic vaiiallcs aic iniiializcu whcn ihc class is loaucu. Il you
uon`i cxliciily iniiializc a siaiic vaiiallc ly assigning ii a
valuc ai ihc iimc you ucclaic ii), ii gcis a uclauli valuc, so ini
vaiiallcs aic iniiializcu io zcio, which mcans wc uiun`i nccu
io cxliciily say layciCouni 0". Dcclaiing, lui noi iniiial-
izing, a siaiic vaiiallc mcans ihc siaiic vaiiallc will gci ihc uc-
lauli valuc loi ihai vaiiallc iyc, in cxacily ihc samc way ihai
insiancc vaiiallcs aic givcn uclauli valucs whcn ucclaicu.
All static variables
in a class are
initialized before
any ob]ect of
that class can be
created.
1- |.]--c---l : -l.|-- --- l- :|.:: : |-.-
w- -|:l|] -l.|-- l l- o, -l -- --'l ---
l- :-:- o : l- -.-|l .|-- -- -l: l.l: .-~
.|-: -l -.-|l .|--: -:l |- -:l.-:- .-.|-:
l-.-|l .|--: -- -:|.-- -l ---l.|--
:l.l: .- -:l.-:- .-.|-: .-- l- :.--
--l- -l---: ||--, :--l, -l:` o
--l- |-.l- --l: ||-.l, --|-` oo
--|-.- .|:-
--:l ------:-: --||
File Edit Window Help What?
% java PlayerTestDrive
0
1
---- .-] -:l.-:-: .-- -.-
.l-- .- --:l : :--.l-
A::-:: . :l.l: .-.|- -:l |- . :l.l:
--l---l l- :|.:: -.--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
282 chapter 10
s!z!|r f|nz| vzr|z||cs zrc rens!zn!s
A vaiiallc maiIcu nalmcans ihai-oncc iniiializcu-ii can
ncvci changc. In oihci woius, ihc valuc ol ihc siaiic hnal vaiiallc
will siay ihc samc as long as ihc class is loaucu. IooI u Maih.PI
in ihc API, anu you`ll hnu:
public static nal double PI = 3.141592653589793;
Thc vaiiallc is maiIcu public so ihai any couc can acccss ii.
Thc vaiiallc is maiIcu static so ihai you uon`i nccu an
insiancc ol class Maih which, icmcmlci, you`ic noi allowcu io
cicaic).
Thc vaiiallc is maiIcu nal lccausc PI uocsn`i changc as lai as
]ava is conccincu).
Thcic is no oihci way io ucsignaic a vaiiallc as a consiani, lui
ihcic is a naming convcniion ihai hcls you io iccognizc onc.
Constont voriobIe nomes shouId be in oII cops:
nitialize a hnal static variable:
At the time you decIure it:
1
public class Foo {
public static nal int FOO_X = 25;
}
In u stutic initiuIizer:
2
public class Bar {
public static nal double BAR_SIGN;
static {
BAR_SIGN = (double) Math.random();
}
}
OR
A static initiaIizer is a bIock
of code that runs when a
cIass is Ioaded, before any
other code can use the
cIass, so it's a great pIace
to initiaIize a static finaI
variabIe.
class Foo {
nal static int x;
static {
x = 42;
}
}
l: :-- ---: .: :--- .: l- :|.::
: |-.-, ---- .-] :l.l: --l-
: :.||- .- --- ---- .-] :l.l:
.-.|- :.- - -:-
--l:- l- -.-- :----l-- ~~ :l.l:
-.| .-.|-: .-- :--:l.-l:, :- l-
-.-- :--| - .|| ---:.:-, -l .-
----::--- :-.-.l- l- ---:
File Edit Window Help Jack-in
% javac Bar.java
Bar.java:1: variable BAR_SIGN
might not have been initialized
1 error
public class Bar {
public static nal double BAR_SIGN;
}
If you don't give u vuIue to u hnuI vuriubIe
in one of those two pIuces:
The compiIer wiII cutch it:
static finaI constants
-- -l.|-.l--'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
numbers and statics
you are here 283
A I iaa| va:ial|e eaas yaa
:aa't :haage its va|ae.
A I iaa| ethaJ eaas yaa
:aa't ave::iJe the ethaJ.
A I iaa| :|ass eaas yaa
:aa't exteaJ the :|ass li.e.
yaa :aa't a|e a sal:|assI.
non-static hnal variables
f|nz| |sn! jes! fer s!z!|r
vzr|z||cs...
You can usc ihc Icywoiu nal io mouily non-
siaiic vaiiallcs ioo, incluuing insiancc vaiiallcs,
local vaiiallcs, anu cvcn mcihou aiamcicis. In
cach casc, ii mcans ihc samc ihing: ihc valuc can`i
lc changcu. Bui you can also usc hnal io sio
somconc liom ovciiiuing a mcihou oi maIing a
sulclass.
class Foof {
nal int size = 3;
nal int whufe;
Foof() {
whufe = 42;
}

void doStuff(nal int x) {
// you can't change x
}

void doMore() {
nal int z = 7;
// you can't change z
}
}

hnal method
class Poof {
nal void calcWhufe() {
// important things
// that must never be overridden
}
}
hnal class
nal class MyMostPerfectClass {
// cannot be extended
}
If's oII so... so fnoI.
I meon, if I'd known
I wouIdn'f be obIe fo
chonge fhings...
--- ]-- :.-'l :.-- :--
--- ]-- :.-'l :.-- ---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
284 chapter 10
(-,- a,- |
oa|| qa--(:|-

A static method can't access a


non-static variabIe. ut can a non-static
method access a static variabIe!

Of course. A non-static method in a
class can always call a static method in the
class or access a static variable of the class.

Why wouId I want to make a cIass


naI! Doesn't that defeat the whoIe
purpose of DD!

es and no. A typical reason for
making a class final is for security. ou
can't, for example, make a subclass of the
String class. |magine the havoc if someone
extended the String class and substituted
their own String subclass ob|ects,
polymorphically, where String ob|ects
are expected. |f you need to count on a
particular implementation of the methods
in a class, make the class final.

Isn't it redundant to have to mark


the methods naI if the cIass is naI!

|f the class is final, you don't need to
mark the methods final. Think about itif
a class is final it can never be subclassed,
so none of the methods can ever be
overridden.
On the other hand, if you want to allow
others to extend your class, and you want
them to be able to override some, but not
all, of the methods, then don't mark the
class final but go in and selectively mark
specific methods as final. A final method
means that a subclass can't override that
particular method.
8ll P0lk5
A stetic method s|ou|d oe ca||ed us|r l|e c|ass
rare ral|er l|ar ar oojecl relererce var|ao|e:
Math.random() vs. myFoo.go()
A slal|c rel|od car oe |rvo|ed W|l|oul ary |rslarces
ol l|e rel|od's c|ass or l|e |eap.
A slal|c rel|od |s ood lor a ul|||ly rel|od l|al does
rol (ard W||| rever) deperd or a parl|cu|ar |rslarce
var|ao|e va|ue.
A slal|c rel|od |s rol assoc|aled W|l| a parl|cu|ar
|rslarceor|y l|e c|assso |l carrol access ary
|rslarce var|ao|e va|ues ol |ls c|ass. ll Wou|dr'l |roW
un|on |rslarce's va|ues lo use.
A slal|c rel|od carrol access a ror-slal|c rel|od,
s|rce ror-slal|c rel|ods are usua||y assoc|aled W|l|
|rslarce var|ao|e slale.
ll you |ave a c|ass W|l| or|y slal|c rel|ods, ard you
do rol Warl l|e c|ass lo oe |rslarl|aled, you car rar|
l|e corslruclor pr|vale.
A stetic verieble |s a var|ao|e s|ared oy a|| reroers
ol a |ver c|ass. T|ere |s or|y ore copy ol a slal|c
var|ao|e |r a c|ass, ral|er l|ar ore copy per eac|
|rd|v|dua| |rslarce lor |rslarce var|ao|es.
A slal|c rel|od car access a slal|c var|ao|e.
To ra|e a corslarl |r Java, rar| a var|ao|e as ool|
slal|c ard l|ra|.
A l|ra| slal|c var|ao|e rusl oe ass|red a va|ue e|l|er
al l|e l|re |l |s dec|ared, or |r a slal|c |r|l|a||zer.
static {
DOG_CODE = 420;
}
T|e rar|r corverl|or lor corslarls (l|ra| slal|c
var|ao|es) |s lo ra|e l|e rare a|| uppercase.
A l|ra| var|ao|e va|ue carrol oe c|ared orce |l |as
oeer ass|red.
Ass|r|r a va|ue lo a l|ra| |nsranoe var|ao|e rusl oe
e|l|er al l|e l|re |l |s dec|ared, or |r l|e corslruclor.
A l|ra| rel|od carrol oe overr|dder.
A l|ra| c|ass carrol oe exlerded (suoc|assed).
static and finaI
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 285
+,-+ :+ ,-+:.|
What's LegaI?
Given everything you've |ust
learned about static and nal,
which of these would compileI
1
public class Foo {
static int x;
public void go() {
System.out.println(x);
}
}
public class Foo2 {
int x;
public static void go() {
System.out.println(x);
}
}
public class Foo3 {
nal int x;
public void go() {
System.out.println(x);
}
}
public class Foo4 {
static nal int x = 12;
public void go() {
System.out.println(x);
}
}
public class Foo5 {
static nal int x = 12;
public void go(nal int x) {
System.out.println(x);
}
}
public class Foo6 {
int x = 12;
public static void go(nal int x) {
System.out.println(x);
}
}
2
3
4
5
6
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
286 chapter 10
Mz!h mc!he4s
Now ihai wc Inow how siaiic
mcihous woiI, lci`s looI
ai somc siaiic mcihous in
class Maih. This isn`i all ol
ihcm, |usi ihc highlighis.
ChccI youi API loi ihc icsi
incluuing sqii), ian), ccil),
uooi), anu asin).
Math.random{}
Pefurns o doubIe befween 0.0 fhrough (buf
nof incIuding) I.0.
double r1 = Math.random();
int r2 = (int) (Math.random() * 5);
Math.abs{}
Pefurns o doubIe fhof is fhe obsoIufe voIue of
fhe orgumenf. The mefhod is overIooded, so
if you poss if on inf if refurns on inf. Poss if o
doubIe if refurns o doubIe.
int x = Math.abs(-240); // returns 240
double d = Math.abs(240.45); // returns 240.45
Math.round{}
Pefurns on inf or o Iong (depending on
whefher fhe orgumenf is o oof or o doubIe)
rounded fo fhe neoresf infeger voIue.
int x = Math.round(-24.8f); // returns -25
int y = Math.round(24.45f); // returns 24
------, |-.l- --l |l--.|: .-- .::---
l- - --|-: --|-:: ]-- . l- ''
Math.min{}
Pefurns o voIue fhof is fhe minimum of fhe
fwo orgumenfs. The mefhod is overIooded fo
foke infs, Iongs, oofs, or doubIes.
int x = Math.min(24,240); // returns 24
double y = Math.min(90876.5, 90876.49); // returns 90876.49
Math.max{}
Pefurns o voIue fhof is fhe moximum of fhe
fwo orgumenfs. The mefhod is overIooded fo
foke infs, Iongs, oofs, or doubIes.
int x = Math.max(24,240); // returns 240
double y = Math.max(90876.5, 90876.49); // returns 90876.5
Math methods
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 287
ale:t
:iitive
Wrzpp|n] z pr|m| !| vc
Somciimcs you wani io iicai a iimiiivc liIc
an ol|cci. Ioi cxamlc, in all vcisions ol ]ava
iioi io .0, you cannoi ui a iimiiivc uiiccily
inio a collcciion liIc AiiayIisi oi HashMa:
hhea yaa aeeJ ta t:eat
a :iitive |i|e aa ale:t,
v:a it. !I yaa':e asiag aay
ve:siaa aI Java leIa:e s.0,
yaa'|| Ja this vhea yaa
aeeJ ta sta:e a :iitive
va|ae iasiJe a :a||e:tiaa |i|e
A::ayIist a: ashKa.
int x = 32;
ArrayList list = new ArrayList();
list.add(x);
1: ---'l --- --|-:: ]--'-- -:- ).. -o --
--.l--'' 1---': -- .|-l` --l- - A--.]|:l
l.l l.-: .- -l' |A--.]|:l --|] .: .|` --l-:
l.l l.- --:l ------:-:, --l --l-:`
wrapping a value
int i = 288;
Integer iWrap = new Integer(i);
Boolean
Character
Byte
8hort
nteger
Long
Float
Double
Thcic`s a wiaci class loi cvciy iimiiivc iyc,
anu sincc ihc wiaci classcs aic in ihc |ava.
lang acIagc, you uon`i nccu io imoii ihcm.
You can iccognizc wiaci classcs lccausc
cach onc is namcu alici ihc iimiiivc iyc ii
wias, lui wiih ihc hisi lciici caiializcu io
lollow ihc class naming convcniion.
Oh ycah, loi icasons alsoluicly nolouy on ihc
lanci is cciiain ol, ihc API ucsigncis ucciucu
noi io ma ihc namcs liom iimiiivc
iyc io class iyc. You`ll scc whai wc mcan:
unwrapping a value
int unWrapped = iWrap.intValue();
6- l- --l- l- l-
--.-- :--:l--:l-- 1.l': l
A|| l- --.--: ---
|- l: B--|-.- .: .
--|-.-/.|--|`, c.-.:l--
.: . :.-/.|--|`, -l:
w.l: --l' 1- -.--: .---'l
-.- -.:l|] l- l- --l-
l]-: 1- :|.:: -.--: .-- -||]
:-||- --l
I
n
f
e
ger

o
b
j
e
c
f

inf
-l --l-
|-l--- --:l
Note: the picture at the top is a chocolate in a foil wrapper. Get
it? Wrapper? Some people think it looks like a baked potato, but
that works too.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
static methods
288 chapter 10
Bcferc 1zvz 5.0, Y00 hz4 !e 4e !hc werk...
Shc`s iighi. In all vcisions ol ]ava iioi io .0, iimiiivcs wcic iimiiivcs
anu ol|cci iclcicnccs wcic ol|cci iclcicnccs, anu ihcy wcic NEVER
iicaicu inicichangcally. Ii was always u io you, ihc iogiammci, io uo
ihc wiaing anu unwiaing. Thcic was no way io ass a iimiiivc io a
mcihou cxcciing an ol|cci iclcicncc, anu no way io assign ihc icsuli ol a
mcihou iciuining an ol|cci iclcicncc uiiccily io a iimiiivc vaiiallc-cvcn
whcn ihc iciuincu iclcicncc is io an Inicgci anu ihc iimiiivc vaiiallc is
an ini. Thcic was simly no iclaiionshi lciwccn an Inicgci anu an ini,
oihci ihan ihc laci ihai Inicgci has an insiancc vaiiallc ol iyc ini io holu
ihc iimiiivc ihc Inicgci wias). All ihc woiI was u io you.
This is sfupid. You meon I con'f
jusf moke on ArroyLisf of infs777 I
hove fo wrop every singIe frickin' one in o new
Infeger objecf, fhen unwrop if when I fry
fo occess fhof voIue in fhe ArroyLisf7
Thof's o wosfe of fime ond on error
woifing fo hoppen...
An ArrayList of primitive ints
public void doNumsOldWay() {
ArrayList listOfNumbers = new ArrayList();

listOfNumbers.add(new Integer(3));
Integer one = (Integer) listOfNumbers.get(0);
int intOne = one.intValue();
}
Without autoboxing {Java versions before 5.0}
M.- .- A--.]|:l |------, ---- -o ]-- :--| --l
:-:] l- 1/|!, :- .|| A--.]|:l: ---- |:l: - 6-:l:`
/-- :.-'l . l- --l- '?' l- l- |:l,
:- ]-- .- l- --. l - .- |-l--- -:l
|l :---: --l .: l]-
6-:l, -l ]-- :.- :.:l
l- 6-:l l- .- |-l---
|-.||] ]-- :.- -l l- --l- --l - l- |-l---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 289
public void doNumsNewWay() {
ArrayList<Integer> listOfNumbers = new ArrayList<Integer>();
listOfNumbers.add(3);
int num = listOfNumbers.get(0);
}
With autoboxing {Java versions 5.0 or greater}
M.- .- A--.]|:l - l]- |-l---
)-:l . l'
A|l-- l--- : N61 . --l- - A--.]|:l
-- .|-l`, l- :--|-- --: .|| l- --.-
|--` -- ]-- |- -l-- ---:, l--- --.||] |
.- |-l--- --:l :l--- - l- A--.]|:l, -l
]-- -l l- --l--' l.l l- A--.]|:l l.-:
-l: |/-- :.- . -l -l: .- |-l---: l- .-
A--.]|:l|-l---`
A- l- :--|-- .-l--.l:.||] ----.: |----:` l- |-l--- --:l :- ]-- :.- .::- l- -l .|-- --:l|] l- . --l- -l--l .- l- :.|| l- -l/.|--|` --l- -- l- |-l--- --:l
e!e|er|n]: ||err|n] !hc ||nc
|c! wccn pr|m| !| vc zn4 e|jcr!
Thc auioloxing lcaiuic auucu io ]ava .0 uocs
ihc convcision liom iimiiivc io wiaci ol|cci
nuon.nII,
Ici`s scc whai hacns whcn wc wani io maIc an
AiiayIisi io holu inis.
An ArrayList of primitive ints

Why not decIare an ArrayList<int> if you want to


hoId ints!

8ecause... you cont. Pemember, the rule for generic
types is that you can specify only class or interface types, not
t|m|t|ves. So ArrayList<int> will not compile. 8ut as you can
see from the code above, it doesn't really matter, since the
compiler lets you put ints into the ArrayList<|nteger>. |n fact,
there's really no way to tevent you from putting primitives
into an ArrayList where the type of the list is the type of that
primitive's wrapper, if you're using a 1ava 5.0-compliant com-
piler, since autoboxing will happen automatically. So, you can
put boolean primitives in an ArrayList<8oolean> and chars
into an ArrayList<Character>.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
static methods
290 chapter 10
void takeNumber(Integer i) { }
inf
3
I
n
f
e
g
er o
b
j
e
c
f

3
int giveNumber() {
return x;
}
inf
3
I
n
f
e
g
er o
b
j
e
c
f

3
if (bool) {
System.out.println(true);
}
booIeon
true
b
o
o
Ie
on o
b
j
e
c
f

true
e!e|er|n] werks z|mes! cvcrywhcrc
Auioloxing lcis you uo moic ihan |usi ihc olvious wiaing anu
unwiaing io usc iimiiivcs in a collcciion... ii also lcis you usc
ciihci a iimiiivc oi iis wiaci iyc viiiually anywhcic onc oi ihc
oihci is cxccicu. ThinI aloui ihai!
Fun with autoboxing
Method arguments
If o mefhod fokes o wropper fype, you
con poss o reference fo o wropper or
o primifive of fhe mofching fype. And
of course fhe reverse is frue-if o
mefhod fokes o primifive, you con
poss in eifher o compofibIe primifive
or o reference fo o wropper of fhof
primifive fype.
Return values
If o mefhod decIores o primifive
refurn fype, you con refurn eifher o
compofibIe primifive or o reference
fo fhe wropper of fhof primifive fype.
And if o mefhod decIores o wropper
refurn fype, you con refurn eifher o
reference fo fhe wropper fype or o
primifive of fhe mofching fype.
Boolean expressions
Any pIoce o booIeon voIue is expecfed,
you con use eifher on expression fhof
evoIuofes fo o booIeon (4 Z), or o
primifive booIeon, or o reference fo o
8ooIeon wropper.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 291
i++;
inf
3
I
n
f
e
g
er o
b
j
e
c
f

3
Double d = x;
inf
3
I
n
f
e
g
er o
b
j
e
c
f

3
Operations on numbers
This is probobIy fhe sfrongesf one-yes, you
con now use o wropper fype os on operond
in operofions where fhe primifive fype is
expecfed. Thof meons you con oppIy, soy,
fhe incremenf operofor ogoinsf o reference
fo on Infeger objecfl
8uf don'f worry-fhis is jusf o compiIer frick.
The Ionguoge wosn'f modifed fo moke fhe
operofors work on objecfs, fhe compiIer
simpIy converfs fhe objecf fo ifs primifive
fype before fhe operofion. If sure Iooks
weird, fhough.
Infeger i ~ new Infeger(4Z),
i++,
And fhof meons you con oIso do fhings Iike:
Infeger j ~ new Infeger(b),
Infeger k ~ j + 3,
Assignments
You con ossign eifher o wropper or primifive
fo o voriobIe decIored os o mofching wropper
or primifive. For exompIe, o primifive inf
voriobIe con be ossigned fo on Infeger
reference voriobIe, ond vice-verso-o
reference fo on Infeger objecf con be
ossigned fo o voriobIe decIored os on inf
primifive.
+,-+ :+ ,-+:.|
public class TestBox {
Integer i;
int j;
public static void main (String[] args) {
TestBox t = new TestBox();
t.go();
}

public void go() {
j=i;
System.out.println(j);
System.out.println(i);
}
}
w||| l||s code corp||e? w||| |l rur? ll |l rurs,
W|al W||| |l do?
Ta|e your l|re ard l||r| aooul l||s ore, |l
or|rs up ar |rp||cal|or ol aulooox|r l|al
We d|dr'l la|| aooul.
You'|| |ave lo o lo your corp||er lo l|rd
l|e arsWers. (Yes, We're lorc|r you lo
exper|rerl, lor your oWr ood ol course.)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
292 chapter 10
Be! wz| !| Ihcrcs merc| Wrzppcrs
hzvc s!z!|r e!||| !y mc!he4s !ee|
Bcsiucs aciing liIc a noimal class, ihc wiacis havc a
lunch ol ically usclul siaiic mcihous. Wc`vc uscu onc in
ihis looI lcloic-Inicgci.aiscIni).
Thc aisc mcihous iaIc a Siiing anu givc you lacI a
iimiiivc valuc.
String s = 2;
int x = Integer.parseInt(s);
double d = Double.parseDouble(420.24);
boolean b = new Boolean(true).booleanValue();
Converting a 8tring to a
primitive value is easy:
N- --|-- l- .-:-
i' -l- i
c~- 1: :--|-: -:l --, -l
.l ---l-- l |--: - A-]l-
l.l :.-'l - .-:- .: . -----
-|| :.-:- . N----|---.l!:-l--
File Edit Window Help Clue
% java Wrappers
Exception in thread main
java.lang.NumberFormatException: two
at java.lang.Integer.parseInt(Integer.java:409)
at java.lang.Integer.parseInt(Integer.java:458)
at Wrappers.main(Wrappers.java:9)
String t = two;
int y = Integer.parseInt(t);
But if you try to do this:
You'll get a runtime exception:
/--' l- l--- ---| - .
B--|-.-.-:-B--|-.-|` ---|-'l ]-- B-l l---
:-'l |--l--.l-|] l---': . B--|-.- :--:l--:l--
l.l l.-: |.- .-:-:` . l--, .- l-- ]--
-:l -l l- --l- .|-- ] ----.- l
Every method or
constructor that parses
a 8tring can throw a
NumberFormatException.
t's a runtime exception,
so you don't have to
handle or declare it.
But you might want to.
wrapper methods
(We'll talk about Exceptions in the
next chapter.)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
numbers and statics
you are here 293
n4 new |n rcvcrsc... !ern|n] z
pr|m| !| vc nem|cr |n!e z 8!r|n]
Thcic aic scvcial ways io iuin a numlci inio a Siiing.
Thc casicsi is io simly concaicnaic ihc numlci io an
cxisiing Siiing.
double d = 42.5;
String doubleString = + d;
double d = 42.5;
String doubleString = Double.toString(d);
------ l- '+' ---.l-- : ---|-.-
- ).. |l- --|] ---|-.- ---.l--` .: .
l-- :--:.l--.l-- A-]l- .- l- .
l-- -:---: l---
A--l-- -.] l- - l -:- . :l.l:
--l- - :|.:: l--|-
Yeoh,
buf how do I moke if
Iook Iike money7 Wifh o doIIor
sign ond fwo decimoI pIoces
Iike $bo.87 or whof if I wonf
commos Iike 4b,o87,890 or
whof if I wonf if in...
Where's my prinff
Iike I hove in C7 Is
number formoffing porf of
fhe I/O cIosses7
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
294 chapter 10
hem|cr fermz!!|n]
In ]ava, loimaiiing numlcis anu uaics uocsn`i havc io lc coulcu wiih I/O. ThinI
aloui ii. Onc ol ihc mosi iyical ways io uislay numlcis io a usci is ihiough a
GUI. You ui Siiings inio a sciolling icxi aica, oi maylc a iallc. Il loimaiiing was
luili only inio iini siaicmcnis, you`u ncvci lc allc io loimai a numlci inio a nicc
Siiing io uislay in a GUI. Bcloic ]ava .0, mosi loimaiiing was hanulcu ihiough
classcs in ihc |ava.icxi acIagc ihai wc won`i cvcn looI ai in ihis vcision ol ihc
looI, now ihai ihings havc changcu.
In ]ava .0, ihc ]ava icam auucu moic owcilul anu ucxillc loimaiiing ihiough a
Ioimaiici class in |ava.uiil. Bui you uon`i nccu io cicaic anu call mcihous on ihc
Ioimaiici class youiscll, lccausc ]ava .0 auucu convcnicncc mcihous io somc ol
ihc I/O classcs incluuing iinil)) anu ihc Siiing class. So ii`s a simlc maiici ol
calling a siaiic Siiing.loimai) mcihou anu assing ii ihc ihing you wani loimaiicu
along wiih loimaiiing insiiuciions.
Ol couisc, you uo havc io Inow how io suly ihc loimaiiing insiiuciions, anu
ihai iaIcs a liiilc clloii unlcss you`ic lamiliai wiih ihc print[); lunciion in C/C++.
Ioiiunaicly, cvcn il you Jor` Inow iinil) you can simly lollow iccics loi ihc
mosi lasic ihings ihai wc`ic showing in ihis chaici). Bui you w.II wani io lcain
how io loimai il you wani io mix anu maich io gci nr,L.r you wani.
Wc`ll siaii hcic wiih a lasic cxamlc, ihcn looI ai how ii woiIs. Noic: wc`ll icvisii
loimaiiing again in ihc I/O chaici.)
public class TestFormats {
public static void main (String[] args) {

String s = String.format(%, d, 1000000000);
System.out.println(s);
}
}
Formatting a number to use commas
1- ----- l- ---.l |--
-.-l l l- .- :---.:`
N-- -- -l :---.: -:--l- -l- l- -----
1,000,000,000
number formatting
1- ---.ll- -:l--:l--: -- -- l- ---.l l-
:-:-- .-----l |-: - l: :.:- : .- -l .|--`
------, l--- .-- --|] l-- .-----l: l- l: --l-
----l- -:l :---. : |N|l! l- l-- |l--.|, :-
l :-'l :-.-.l- .-----l: l- l- ---.l --l-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 295
Iermz!!|n] 4crens!rer!c4...
format(%, d, 1000000000);
Ai ihc mosi lasic lcvcl, loimaiiing consisis ol iwo main aiis
ihcic is moic, lui wc`ll siaii wiih ihis io Icc ii clcanci):
Formatting instructions
1
The argument to be formatted.
2
1 2
Use these instructions... on this argument.
You use spec|a| lorral spec|l|ers l|al descr|oe |oW
l|e arurerl s|ou|d oe lorralled.
A|l|ou| l|ere car oe rore l|ar ore arurerl, We'||
slarl W|l| jusl ore. T|e arurerl lype car'l oe jusl
anyrn|ng... |l |as lo oe sorel||r l|al car oe lorralled
us|r l|e lorral spec|l|ers |r l|e lorrall|r |rslrucl|ors.
For exarp|e, |l your lorrall|r |rslrucl|ors spec|ly a
l|oar|ng o|nr numoer, you car'l pass |r a 0o or ever a
3lr|r l|al |oo|s |||e a l|oal|r po|rl ruroer.
What do these instructions actually say?
TaIc ihc scconu aigumcni io ihis mcihou, anu
loimai ii as a ccimal inicgci anu inscii ."
How do they say that?
On ihc ncxi agc wc`ll looI in moic uciail ai whai ihc syniax %,
u" aciually mcans, lui loi siaiicis, any iimc you scc ihc ciccni
sign %) in a loimai Siiing which is always ihc hisi aigumcni
io a loimai) mcihou), ihinI ol ii as icicscniing a vaiiallc,
anu ihc vaiiallc is ihc oihci aigumcni io ihc mcihou. Thc icsi
ol ihc chaiacicis alici ihc ciccni sign ucsciilc ihc loimaiiing
insiiuciions loi ihc aigumcni.
l
- l: l- l:
N-l- ]-- .|--.] --- --l|`
--- :/c++, ]-- :.- --.|] -:l
:- l- --l -- .-: 6l---:-,
--. :.---||]'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
296 chapter 10
the format() method
Ihc pcrrcn! |7I szys, |nscr! zr]emcn! hcrc
|zn4 fermz! | ! es|n] !hcsc |ns!rer!|ensI
Thc hisi aigumcni io a loimai) mcihou is callcu ihc loimai Siiing, anu ii
can aciually incluuc chaiacicis ihai you |usi wani iinicu as-is, wiihoui cxiia
loimaiiing. Whcn you scc ihc % sign, ihough, ihinI ol ihc ciccni sign as a
vaiiallc ihai icicscnis ihc oihci aigumcni io ihc mcihou.
format(I have %.2f bugs to x., 476578.09876);
6-l-l
A-----l l- -
---.ll-
|---.l :-:--: -- l-
:-:-- .-----l l- l-
--l- |l- -----`
c.-.:l--: l- -:|-- -
l- -.| l-- --l----
--- ---.l|`
I have 476578.10 bugs to x.
M--- :.-.:l--: l-
-:|-- - l- l-- .l--
l- :-:-- .-----l :
---.ll- .- -:--l-
Thc %" sign iclls ihc loimaiici io inscii ihc oihci mcihou aigumcni ihc
scconu aigumcni io loimai), ihc numlci) hcic, AND loimai ii using ihc
.2l" chaiacicis alici ihc ciccni sign. Thcn ihc icsi ol ihc loimai Siiing,
lugs io hx", is auucu io ihc hnal ouiui.
N-l:- -- |-:l :--- - l- -----:
.l-- l- -:-.| --l c.- ]-- --::
-.l l- i' --.-:
Adding a comma
format(I have %,.2f bugs to hx., 476578.09876);
I have 476,578.10 bugs to x.
B] :.-- l- ---.l -:l--:l--:
--- *i' l- *,i', -- -l .
:---. - l- ---.ll- -----
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 297
Ihc fermz! 8!r|n] escs | !s
ewn || !!|c |zn]ez]c syn!zr
You olviously can`i ui |usi alici ihc %"
sign. Thc syniax loi whai gocs alici ihc ciccni
sign lollows vciy sccihc iulcs, anu ucsciilcs
how io loimai ihc aigumcni ihai gcis insciicu ai
ihai oini in ihc icsuli loimaiicu) Siiing.
You`vc alicauy sccn iwo cxamlcs:
mcans inscii commas anu loimai ihc
numlci as a uccimal inicgci."
anu
mcans loimai ihc numlci as a uoaiing
oini wiih a iccision ol iwo uccimal laccs."
anu
mcans inscii commas anu loimai ihc
numlci as a uoaiing oini wiih a iccision ol
iwo uccimal laccs."
Thc ical qucsiion is ically, How uo I Inow whai
io ui alici ihc ciccni sign io gci ii io uo whai
I wani." Anu ihai incluucs Inowing ihc symlols
liIc u" loi uccimal anu l" loi uoaiing oini)
as wcll as ihc oiuci in which ihc insiiuciions
musi lc laccu lollowing ihc ciccni sign. Ioi
cxamlc, il you ui ihc comma alici ihc u" liIc
ihis: %u," insicau ol %,u" ii won`i woiI!
Oi will ii. Whai uo you ihinI ihis will uo:
8uf how does if even IMOW
where fhe insfrucfions end ond fhe
resf of fhe chorocfers begin7 How come
if doesn'f prinf ouf fhe "f" in "7.Zf"7 Or
fhe "Z"7 How does if know fhof fhe .Zf
wos porf of fhe insfrucfions ond MOT
porf of fhe Sfring7
String.format(I have %.2f, bugs to x., 476578.09876);
Wc`ll answci ihai on ihc ncxi agc.)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
298 chapter 10
Ihc fermz! spcr|f|cr
Evciyihing alici ihc ciccni sign u io anu incluuing ihc iyc inuicaioi liIc
u" oi l") aic aii ol ihc loimaiiing insiiuciions. Alici ihc iyc inuicaioi, ihc
loimaiici assumcs ihc ncxi sci ol chaiacicis aic mcani io lc aii ol ihc ouiui
Siiing, uniil oi unlcss ii hiis anoihci ciccni %) sign. Hmmmm... is ihai cvcn
ossillc. Can you havc moic ihan onc loimaiicu aigumcni vaiiallc. Pui ihai
ihoughi on holu loi iighi now, wc`ll comc lacI io ii in a lcw minuics. Ioi now,
lci`s looI ai ihc syniax loi ihc loimai sccihcis-ihc ihings ihai go alici ihc
ciccni %) sign anu ucsciilc how ihc aigumcni shoulu lc loimaiicu.
A format speciher can have up to hve different parts {not
including the %}. Everything in brackets [ j below is optional, so
only the percent {%} and the type are required. But the order is
also mandatory, so any parts you DO use must go in this order.
%[argument number][Hags][width][.precision]type
w-'|| -l l- l: |.l--
l |-l: ]-- :.] w+|c+
.-----l l---': ----
l.- --- |l--'l ----]
.--l l -:l ]-l`
1-:- .-- --
:-:.| ---.ll-
-l--: |- -:--l-
:---.:, -- -ll-
--.l- -----: -
.---l-:-:, -- l-
-.- l- -----:
|-l -:l-
1: ---: l-
M|N|McM -----
- :.-.:l--: l.l
-|| - -:- 1.l':
----- --l
161A| | l- -----
: |---- l.- l-
-l, l'|| :l|| - -:-
- -||, -l l': |-::
l.- l- -l, l'|| -
.- -l -----:
/-- .|--.] ---
l: ---l ---:
l- --::-- |-
-l-- ---:, l
:-l: l- -----
- -:-.| |.:-:
l--'l ---l l-
-:|-- l- ' -
l---
1]- : -.-.l--]
|:-- l- --l .-`
.- -|| -:-.||] -
' -- . -:-.|
-l--- -- ' --
. |-.l- --l
-----
%[argument number][Hags][width][.precision]type
format(%,6.1f, 42.000);
1---': -- .-----l -----'
:-:- - l: ---.l l--,
-l .|| l- -l-- -:-: .-- l---
format specifier
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 299
Ihc en|y rce|rc4 spcr|f|cr |s fer IY|I
Alihough iyc is ihc only icquiicu sccihci, icmcmlci ihai il you ui
in anyihing clsc, iyc musi always comc lasi! Thcic aic moic ihan a uozcn
uillcicni iyc mouihcis noi incluuing uaics anu iimcs, ihcy havc ihcii own
sci), lui mosi ol ihc iimc you`ll iolally usc %u uccimal) oi %l uoaiing
oini). Anu iyically you`ll comlinc %l wiih a iccision inuicaioi io sci ihc
numlci ol uccimal laccs you wani in youi ouiui.
format(%d, 42);
The TYPE is mandatory, everything else is optional.
42
%d decimal
format(%.3f, 42.000000);
42.000
%f hoating point
format(%x, 42);
2a
%x hexadecimal
format(%c, 42);
*
%c character
Thc aigumcni musi lc comaiillc wiih an ini, so ihai mcans
only lyic, shoii, ini, anu chai oi ihcii wiaci iycs).
Thc aigumcni musi lc ol a uoaiing oini iyc, so ihai
mcans only a uoai oi uoullc iimiiivc oi wiaci) as wcll
as somcihing callcu BigDccimal which wc uon`i looI ai in
ihis looI).
A +ii- ---| --l ---' |l ---| - l- :.-- .: l-]- l- --:l|] .::- . --|- l- .- -l .-.|-
+--- -- :---- l- '
-l . --::-- -:.l--
?' :- -- --- - -l
l--- -----:
Thc aigumcni musi lc a lyic, shoii, ini, long incluuing
loih iimiiivc anu wiaci iycs), anu BigInicgci.
)aa ast :a:|aJe a
tye :a yaa: Ia:at
:ast:a:t:aas, aaJ :I yaa
se::Iy th:ags les:Jes
tye, the tye ast
a|vays :ae |ast.
Kast aI the t:e,
yaa'|| :alal|y Ia:at
aale:s as:ag e:the:
J" Ia: Je::a| a: I"
Ia: I |aat:ag a:at.
Thc aigumcni musi lc a lyic, shoii, chai, oi ini incluuing
loih iimiiivc anu wiaci iycs).
1- ----- +i ----:--l:
l- :.- '
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
300 chapter 10
Whz! hzppcns |f | hzvc merc !hzn enc zr]emcn!!
Imaginc you wani a Siiing ihai looIs liIc ihis:
Thc ianI is 20,+56,65+ oui ol 100,567,S90.2+."
Bui ihc numlcis aic coming liom vaiiallcs. Whai uo you uo. You simly auu wo
aigumcnis alici ihc loimai Siiing hisi aigumcni), so ihai mcans youi call io loimai)
will havc ihicc aigumcnis insicau ol iwo. Anu insiuc ihai hisi aigumcni ihc loimai
Siiing), you`ll havc iwo uillcicni loimai sccihcis iwo ihings ihai siaii wiih %"). Thc
hisi loimai sccihci will inscii ihc scconu aigumcni io ihc mcihou, anu ihc scconu
loimai sccihci will inscii ihc ihiiu aigumcni io ihc mcihou. In oihci woius, ihc
vaiiallc insciiions in ihc loimai Siiing usc ihc oiuci in which ihc oihci aigumcnis aic
asscu inio ihc loimai) mcihou.
int one = 20456654;
double two = 100567890.248907;
String s = String.format(The rank is %,d out of %,.2f, one, two);
w-- ]-- .- ---- l.- --- .-----l, l-]'-- -:--l- -:- l- ---- - -: ]-- .:: l-- l- l- ---.l|` --l-
As you`ll scc whcn wc gci io uaic loimaiiing, you mighi aciually wani io aly uillcicni
loimaiiing sccihcis io ihc samc aigumcni. Thai`s iolally haiu io imaginc uniil you
scc how Jne loimaiiing as ooscu io ihc rube. loimaiing wc`vc lccn uoing) woiIs.
]usi Inow ihai in a minuic, you`ll scc how io lc moic sccihc aloui which loimai
sccihcis aic alicu io which aigumcnis.
The rank is 20,456,654 out of 100,567,890.25
w- .- :---.: l- -l .-.|-:,
.- --:l-:l- l- |-.l- --l
----- |l- :-:-- .-.|-` l- l--
-:-.| |.:-:

Um, there's something RALLY strange going on here. 1ust how many arguments I
pass! I mean, how many overIoaded format() methods are IN the String cIass! So, what happens
if I want to pass, say, ten different arguments to be formatted for a singIe output String!

Good catch. es, there |s something strange (or at least new and different) going on, and
no there are not a bunch of overloaded format() methods to take a different number of possible
arguments. |n order to support this new formatting (printf-like) AP| in 1ava, the language needed
another new featurevot|oole otument l|sts (called votots for short). we'll talk about varargs
only in the appendix because outside of formatting, you probably won't use them much in a well-
designed system.
format arguments
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 301
8e merh fer nem|crs, whz! z|ee! 4z!cs!
Imaginc you wani a Siiing ihai looIs liIc ihis: Sunuay, Nov 2S 2004"
Noihing sccial ihcic, you say. Wcll, imaginc ihai all you havc io siaii wiih is a vaiiallc
ol iyc Daic-A ]ava class ihai can icicscni a iimcsiam, anu now you wani io iaIc ihai
ol|cci as ooscu io a numlci) anu scnu ii ihiough ihc loimaiici.
Thc main uillcicncc lciwccn numlci anu uaic loimaiiing is ihai uaic loimais usc a
iwo-chaiacici iyc ihai siaiis wiih i" as ooscu io ihc singlc chaiacici l" oi u", loi
cxamlc). Thc cxamlcs lclow shoulu givc you a goou iuca ol how ii woiIs:
String.format(%tc, new Date());
Sun Nov 28 14:52:41 MST 2004
The complete date and time %tc
String.format(%tr, new Date());
03:01:47 PM
Just the time %tr
Date today = new Date();
String.format(%tA %tB %td,today,today,today);

Sunday, November 28
Day of the week, month and day %tA %tB %td
Date today = new Date();
String.format(%tA, %<tB %<td,today);

8ame as above, but without duplicating the arguments %tA %tB %td
Thcic isn`i a singlc loimai sccihci ihai will uo cxacily whai wc
wani, so wc havc io comlinc ihicc ol ihcm loi uay ol ihc wccI
%iA), monih %iB), anu uay ol ihc monih %iu).
B-l l.l --.-: -- .- l- .:: l- l.l- --:l - l--- l--:, --- -- -.: .-l - l-
---.l l.l -- -.-l |- -l--
---:, l- *lA -|| - -: -:l
l- .] - l- ---, -l l-- -- .- l- - l ..- l- -l -:l l- ---l .- ..- -- l-
.]- l- ---l
1- :---. : --l .-l - l- ---.ll- l':
-:l l- :.-.:l-- -- -.-l --l- .l-- l-
-:l -:--l- ---.ll- .-----l
1- .-|-~-.:-l ' : -:l .--l--
|. - l- :-:-- l.l l-||: l-
---.ll-- l- -:- l- ----: .-----l
..-' - l :.-: ]-- --- ---.l- l-
.-----l:, .- -:l-. ]-- ---.l l-
:.-- .-----l l--- ----l -.]:
/-- :.- l- - l: .: - - |- :.||- l---
----l -ll-- --l-: -- l- l.l- --:l, l-
-l l--- ----l -:-: - .l. --- l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
302 chapter 10
Werk|n] w| !h Pz!cs
You nccu io uo moic wiih uaics ihan |usi gci
oJn,` uaic. You nccu youi iogiams io au|usi
uaics, hnu clascu iimcs, iioiiiizc schcuulcs,
hccI, maIc schcuulcs. You nccu inuusiiial
siicngih uaic maniulaiion caaliliiics.
You coulu maIc youi own uaic iouiincs ol
couisc... anu uon`i loigci aloui lca ycais!)
Anu, ouch, ihosc occasional, csIy lca-
eorJ. Wow, ihis coulu gci comlicaicu. Thc
goou ncws is ihai ihc ]ava API is iich wiih
classcs ihai can hcl you maniulaic uaics.
Somciimcs ii lccls a liiilc oo iich...
Lef's see... how mony work
doys wiII fhere be if fhe
projecf sforfs on Feb Z7fh ond
ends on Augusf bfh7
manipuIating dates
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
numbers and statics
you are here 303
Mev|n] |zrkwzr4 zn4 ferwzr4 |n !|mc
Ici`s say youi comany`s woiI schcuulc is Monuay ihiough Iiiuay.
You`vc lccn assigncu ihc iasI ol hguiing oui ihc lasi woiI uay in
cach calcnuai monih ihis ycai...
Ia: a t:e-sta aI aav",
ase Pate. 5at Ia: eve:yth:ag
e|se, ase Ca|eaJa:.
t seems that ]ava.util.Date is actually... out of date
Eailici wc uscu |ava.uiil.Daic io hnu iouay`s uaic, so ii sccms
logical ihai ihis class woulu lc a goou lacc io siaii looIing loi
somc hanuy uaic maniulaiion caaliliiics, lui whcn you chccI
oui ihc API you`ll hnu ihai mosi ol Daic`s mcihous havc lccn
uciccaicu!
Thc Daic class is siill gicai loi gciiing a iimc siam"-an ol|cci
ihai icicscnis ihc cuiicni uaic anu iimc, so usc ii whcn you wani
io say, givc mc NOW".
Thc goou ncws is ihai ihc API iccommcnus java.util.Calcndar
insicau, so lci`s iaIc a looI:
Use ]ava.util.Calendar for your date manipulation
Thc ucsigncis ol ihc Calcnuai API wanicu io ihinI glolally,
liicially. Thc lasic iuca is ihai whcn you wani io woiI wiih uaics,
you asI loi a Calcnuai ihiough a siaiic mcihou ol ihc Calcnuai
class ihai you`ll scc on ihc ncxi agc), anu ihc ]VM hanus you lacI
an insiancc ol a concicic sulclass ol Calcnuai. Calcnuai is aciually
an alsiiaci class, so you`ic always woiIing wiih a concicic sulclass.)
Moic inicicsiing, ihough, is ihai ihc I.rJ ol calcnuai you gci
lacI will lc n.o..ne o. ,ou. IonIe. Much ol ihc woilu uscs ihc
Gicgoiian calcnuai, lui il you`ic in an aica ihai uocsn`i usc a
Gicgoiian calcnuai you can gci ]ava liliaiics io hanulc oihci
calcnuais such as Buuuhisi, oi Islamic oi ]aancsc.
Thc sianuaiu ]ava API shis wiih java.util.GrcgorianCalcndar, so
ihai`s whai wc`ll lc using hcic. Ioi ihc mosi aii, ihough, you
uon`i cvcn havc io ihinI aloui ihc Iinu ol Calcnuai sulclass you`ic
using, anu insicau locus only on ihc mcihous ol ihc Calcnuai class.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
304 chapter 10
0c!!|n] zn e|jcr! !hz! cr!cn4s 0z|cn4zr
How in ihc woilu uo you gci an insiancc" ol an alsiiaci class.
Wcll you uon`i ol couisc, ihis won`i woiI:
This WON'T work:
Calendar cal = new Calendar();
nstead, use the static getnstance{} method:
Calendar cal = Calendar.getInstance();
Woif o minufe.
If you con'f moke on
insfonce of fhe CoIendor
cIoss, whof exocfIy ore you
ossigning fo fhof CoIendor
reference7
You can't get an instance of Calendar,
but you can can get an instance of a
concrete Calendar subclass.
Olviously you can`i gci an insiancc ol Calcnuai, lccausc
Calcnuai is alsiiaci. Bui you`ic siill licc io call siaiic mcihous
on Calcnuai, sincc mcihous aic callcu on ihc ,
iaihci ihan on a aiiiculai insiancc. So you call ihc siaiic
gciInsiancc) on Calcnuai anu ii givcs you lacI... an insiancc
ol a concicic sulclass. Somcihing ihai cxicnus Calcnuai
which mcans ii can lc olymoihically assigncu io Calcnuai)
anu which-ly coniiaci-can icsonu io ihc mcihous ol class
Calcnuai.
In mosi ol ihc woilu, anu ly uclauli loi mosi vcisions ol ]ava,
you`ll lc gciiing lacI a java.util.GrcgorianCalcndar insiancc.
1- :--|-- ---'l .||-- l: '
1: :]-l. :--| |-- .-|.- .l l:
--l ~ --'-- --- . :l.l: --l-
getting a CaIendar
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 305
Werk|n] w| !h 0z|cn4zr e|jcr!s
Thcic aic scvcial Icy conccis you`ll nccu io unucisianu in
oiuci io woiI wiih Calcnuai ol|ccis:
Ficlds hold stote - A Calcnuai ol|cci has many hclus ihai aic uscu io
icicscni asccis ol iis uliimaic siaic, iis uaic anu iimc. Ioi insiancc, you
can gci anu sci a Calcnuai`s ,en. oi orL.
Datcs and Timcs can bc incremented - Thc Calcnuai class has mcihous ihai
allow you io auu anu suliiaci valucs liom vaiious hclus, loi cxamlc auu
onc io ihc monih", oi suliiaci ihicc ycais".
Datcs and Timcs can bc rcprcscntcd in miIIiseconds - Thc Calcnuai class
lcis you convcii youi uaics inio anu oui ol a milliscconu icicscniaiion.
Sccihcally, ihc numlci ol milliscconus ihai havc occuicu sincc ]anuaiy
1si, 1970.) This allows you io ciloim iccisc calculaiions such as clascu
iimc lciwccn iwo iimcs" oi auu 6S houis anu 2S minuics anu 12 scconus
io ihis iimc".
An example of working with a Calendar ob]ect:
Calendar c = Calendar.getInstance();
c.set(2004,0,7,15,40);
long day1 = c.getTimeInMillis();
day1 += 1000 * 60 * 60;
c.setTimeInMillis(day1);
System.out.println(new hour + c.get(c.HOUR_OF_DAY));
c.add(c.DATE, 35);
System.out.println(add 35 days + c.getTime());
c.roll(c.DATE, 35);
System.out.println(roll 35 days + c.getTime());
c.set(c.DATE, 1);
System.out.println(set to 1 + c.getTime());
File Edit Window Help Time-Flies
new hour 16
add 35 days Wed Feb 11 16:40:41 MST 2004
roll 35 days Tue Feb 17 16:40:41 MST 2004
set to 1 Sun Feb 01 16:40:41 MST 2004
c----l l: l- . -|'
.----l - -||:-:--:
-l l-- l- ).- 7, ioo+
.l |-+
o
|N-l:- l- ---l : ----~.:-`
A ?- .]: l- l- .l-, -:
:--| --- -: -l- |---.-]
-||' ?- .]: --l- l: .l- 1:
--||:' l- .l- .-. ?- .]:, -l
l6! N61 :.-- l- ---l'
w-'-- --l -:-----l- ---, -:l
-- . :-l' - l- .l-
A .- ---': ---l - -||:, l-- -.l- l- l--
|N-l:- l- +=', l': |- .]| = .]| + `
1: --l-l :----: -- -||:,
., --||, .- :-l ---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
306 chapter 10
H|]h||]h!s ef !hc 0z|cn4zr ||
Wc |usi woiIcu ihiough using a lcw ol ihc hclus anu
mcihous in ihc Calcnuai class. This is a lig API, so
wc`ic showing only a lcw ol ihc mosi common hclus
anu mcihous ihai you`ll usc. Oncc you gci a lcw ol
ihcsc ii shoulu lc iciiy casy io lcnu ihc icsi ol ihc
ihis API io youi will.
key CaIendar Methods
add(int eId, int amount)

get(int eId)
getInstance()
get7imeInMiIIis()
roII(int eId, booIean up)
set(int eId, int vaIue)
set(year, month, day, hour, minute) (aII ints)
set7imeInMiIIis(Iong miIIis)
// more...
Adds or subtracts time from the calendar's field.
Peturns the value of the given calendar field.
Peturns this Calendar's time in millis, as a long.
Adds or subtracts time without changing larger fields.
Sets the value of a given Calendar field.
A common variety of set to set a complete time.
Sets a Calendar's time based on a long milli-time.
Peturns a Calendar, you can specify a locale.
key CaIendar FieIds
DA7 / DAY_DF_MDN7H

HDUR / HDUR _DF_DAY

MILLISCDND
MINU7
MDN7H
YAR
ZDN_DFFS7
// more...
Get / set the day of month
Get / set the l2 hour or 24 hour value.
Get / set the minute.
Get / set the month.
Get / set the year.
Get / set raw offset of GMT in millis.
Get / set the milliseconds.
CaIendar API
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 307
Ivcn merc 8!z!|rs|... s!z!|r |mper!s
Ncw io ]ava .0... a ical mixcu llcssing. Somc colc lovc
ihis iuca, somc colc haic ii. Siaiic imoiis cxisi only io savc
you somc iying. Il you haic io iyc, you mighi |usi liIc ihis
lcaiuic. Thc uownsiuc io siaiic imoiis is ihai - il you`ic noi
caiclul - using ihcm can maIc youi couc a loi haiuci io icau.
Thc lasic iuca is ihai whcncvci you`ic using a siaiic class, a
siaiic vaiiallc, oi an cnum moic on ihosc laici), you can
imoii ihcm, anu savc youiscll somc iying.
8ome old-fashioned code:
import java.lang.Math;
class NoStatic {
public static void main(String [] args) {
System.out.println(sqrt + Math.sqrt(2.0));
System.out.println(tan + Math.tan(60));
}
}
8ame code, with static imports:
import static java.lang.System.out;
import static java.lang.Math.*;
class WithStatic {
public static void main(String [] args) {
out.println(sqrt + sqrt(2.0));
out.println(tan + tan(60));
}
}
ll you're or|y o|r lo use a slal|c reroer
a leW l|res, We l||r| you s|ou|d avo|d
slal|c |rporls, lo |e|p |eep l|e code rore
readao|e.
ll you're o|r lo use a slal|c reroer a |ol,
(|||e do|r |ols ol Val| ca|cu|al|ors), l|er
|l's prooao|y 0K lo use l|e slal|c |rporl.
Nol|ce l|al you car use W||dcards (.), |r
your slal|c |rporl dec|aral|or.
A o| |ssue W|l| slal|c |rporls |s l|al |l's
rol loo |ard lo creale rar|r corl||cls For
exarp|e, |l you |ave lWo d|llererl c|asses
W|l| ar 'add() rel|od, |oW W||| you ard
l|e corp||er |roW W||c| ore lo use?
6uveuIs & 6eIthus
1
- :]-l
.
l
- -:- -
--

-:|.-- :l
.l
: -
--l
:
l.l: ---l: - .:l--
lse Ca:eIa||y
stat:: :a:ts :aa
a|e yaa: :aJe
:aaIas:ag ta :eaJ
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
308 chapter 10
Instance Variable
I uon`i cvcn Inow why wc`ic uoing ihis.
Evciyonc Inows siaiic vaiiallcs aic |usi uscu
loi consianis. Anu how many ol ihosc aic
ihcic. I ihinI ihc wholc API musi havc, whai,
loui. Anu ii`s noi liIc anylouy cvci uscs
ihcm.
Iull ol ii. Ycah, you can say ihai again. OK,
so ihcic aic a lcw in ihc Swing liliaiy, lui
cvciylouy Inows Swing is |usi a sccial casc.
OI, lui lcsiucs a lcw GUI ihings, givc mc an
cxamlc ol |usi onc siaiic vaiiallc ihai anyonc
woulu aciually usc. In ihc ical woilu.
Wcll, ihai`s anoihci sccial casc. Anu nolouy
uscs ihai cxcci loi uclugging anyway.
8tatic Variable
You ically shoulu chccI youi lacis. Whcn
was ihc lasi iimc you looIcu ai ihc API. Ii`s
liicIin` loaucu wiih siaiics! Ii cvcn has cniiic
classcs ucuicaicu io holuing consiani valucs.
Thcic`s a class callcu SwingConsianis, loi
cxamlc, ihai`s |usi lull ol ihcm.
Ii mighi lc a sccial casc, lui ii`s a ically
imoiiani onc! Anu whai aloui ihc Coloi
class. Whai a ain il you hau io icmcmlci ihc
RGB valucs io maIc ihc sianuaiu colois. Bui
ihc coloi class alicauy has consianis uchncu
loi lluc, uilc, whiic, icu, cic. Vciy hanuy.
How`s Sysicm.oui loi siaiicis. Thc oui in
Sysicm.oui is a siaiic vaiiallc ol ihc Sysicm
class. You cisonally uon`i maIc a ncw
insiancc ol ihc Sysicm, you |usi asI ihc Sysicm
class loi iis oui vaiiallc.
Oh, liIc uclugging isn`i imoiiani.
Anu hcic`s somcihing ihai iolally ncvci
ciosscu youi naiiow minu-lci`s lacc ii, siaiic
vaiiallcs aic moic clhcicni. Onc ci class
insicau ol onc ci insiancc. Thc mcmoiy
savings mighi lc hugc!
1cnih|`s 1alk: An instance variable
takes cheap shets at a static variable
static vs. instance
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 309
Um, aicn`i you loigciiing somcihing.
Siaiic vaiiallcs aic aloui as un-OO as ii gcis!!
Gcc why noi |usi go iaIc a giani lacIwaius
sic anu uo somc ioccuuial iogiamming
whilc wc`ic ai ii.
You`ic liIc a glolal vaiiallc, anu any
iogiammci woiih his PDA Inows ihai`s
usually a Bau Thing.
Ycah you livc in a class, lui ihcy uon`i call
ii CIn-Oiicnicu iogiamming. Thai`s |usi
siuiu. You`ic a iclic. Somcihing io hcl ihc
olu-iimcis maIc ihc lca io |ava.
Wcll, OK, cvciy oncc in a whilc suic, ii maIcs
scnsc io usc a siaiic, lui lci mc icll you, alusc
ol siaiic vaiiallcs anu mcihous) is ihc maiI
ol an immaiuic OO iogiammci. A ucsignci
shoulu lc ihinIing aloui obe siaic, noi In
siaic.
Siaiic mcihous aic ihc woisi ihings ol all,
lccausc ii usually mcans ihc iogiammci is
ihinIing ioccuuially insicau ol aloui ol|ccis
uoing ihings lascu on ihcii uniquc ol|cci
siaic.
Riiiiiighi. Whaicvci you nccu io icll youiscll...
Whai.
Whai uo you mcan ur-OO.
I am NOT a glolal vaiiallc. Thcic`s no such
ihing. I livc in a class! Thai`s iciiy OO you
Inow, a CIASS. I`m noi |usi siiiing oui ihcic
in sacc somcwhcic, I`m a naiuial aii ol ihc
siaic ol an ol|cci, ihc only uillcicncc is ihai
I`m shaicu ly all insianccs ol a class. Vciy
clhcicni.
Aliighi |usi sio iighi ihcic. THAT is
uchniicly noi iiuc. Somc siaiic vaiiallcs aic
alsoluicly ciucial io a sysicm. Anu cvcn ihc
oncs ihai aicn`i ciucial suic aic hanuy.
Why uo you say ihai. Anu whai`s wiong wiih
siaiic mcihous.
Suic, I Inow ihai ol|ccis shoulu lc ihc locus
ol an OO ucsign, lui |usi lccausc ihcic aic
somc cluclcss iogiammcis oui ihcic... uon`i
ihiow ihc laly oui wiih ihc lyiccouc. Thcic`s
a iimc anu lacc loi siaiics, anu whcn you
nccu onc, noihing clsc lcais ii.
1nstance VarIabIe StatIc VarIabIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
310 chapter 10

] ge eomgj|e;
[[ ]zvz |j] n ([j, zg ,n(, z
e]( gz. (a j j, ( ]zy
ej] zn] ](jn w[([ ([j,
|j] wj]] ej]. ]| j( wn'( ej],
[w wa]] ya |jy j(, zn]
j| j( ], ej], w[z(
wa]] j(, a(a(/
class StaticSuper{
static {
System.out.println{"super static block"|,
}

StaticSuper{
System.out.println{
"super constructor"|,
}
}
public class StaticTests extends StaticSuper {
static int rand,
static {
rand = {int| {Math.random{| * 6|,
System.out.println{"static block " + rand|,
}
StaticTests{| {
System.out.println{"constructor"|,
}
public static void main{String args| {
System.out.println{"in main"|,
StaticTests st = new StaticTests{|,
}
}
File Edit Window Help Cling
%java StaticTests
static block 4
in main
super static block
super constructor
constructor
PossibIe Dutput
File Edit Window Help Electricity
%java StaticTests
super static block
static block 3
in main
super constructor
constructor
PossibIe Dutput
|f it compiles, which of these is
the outputI
be the compiIer
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 311
This chapter explored the wonderful, static, world
of 1ava. our |ob is to decide whether each of the
following statements is true or false.
1. To usc ihc Maih class, ihc hisi sic is io maIc an insiancc ol ii.
2. You can maiI a consiiucioi wiih ihc Icywoiu.
S. Siaiic mcihous uon`i havc acccss io insiancc vaiiallc siaic ol ihc ihis` ol|cci.
4. Ii is goou iaciicc io call a siaiic mcihou using a iclcicncc vaiiallc.
. Siaiic vaiiallcs coulu lc uscu io couni ihc insianccs ol a class.
6. Consiiuciois aic callcu lcloic siaiic vaiiallcs aic iniiializcu.
7. MAX_SIZE woulu lc a goou namc loi a siaiic hnal vaiiallc.
S. A siaiic iniiializci llocI iuns lcloic a class`s consiiucioi iuns.
9. Il a class is maiIcu hnal, all ol iis mcihous musi lc maiIcu hnal.
10. A hnal mcihou can only lc ovciiiuucn il iis class is cxicnucu.
11. Thcic is no wiaci class loi loolcan iimiiivcs.
12. A wiaci is uscu whcn you wani io iicai a iimiiivc liIc an ol|cci.
1S. Thc aiscXxx mcihous always iciuin a Siiing.
14. Ioimaiiing classcs which aic uccoulcu liom I/O), aic in ihc |ava.loimai
acIagc.
fs-s cs |s.ss

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
312 chapter 10
This one might actually be useful! |n addition to what you've learned in the last few
pages about manipulating dates, you'll need a little more information... Pirst, full
moons happen every 29.52 days or so. Second, there was a full moon on 1an. 7th,
2004. our |ob is to reconstruct the code snippets to make a working 1ava program
that produces the output listed below (plus more full moon dates). (ou might not
need all of the magnets, and add all the curly braces you need.) Oh, by the way, your
output will be different if you don't live in the mountain time zone.
File Edit Window Help Howl
% java FullMoons
full moon on Fri Feb 06 04:09:35 MST 2004
full moon on Sat Mar 06 16:38:23 MST 2004
full moon on Mon Apr 05 06:07:11 MDT 2004
Iaaa: CaJe Kagaets
static import java.lang.System.out;
import java.util.*;
println
import static java.lang.System.out;
(full moon on %tc, c));
(c.format
(full moon on %t, c));
(String.format
Calendar c = Calendar.getInstance();
public static void main(String [] args) {
import ava.io.*,
out.println
class FullMoons {
c.setTimeInMillis(day1);
static int DAY_IM = 1000 * 60 * 60 * 24;
static int DAY_IM = 60 * 60 * 24;
for (int x = 0; x < 60; x++) {
long day1 = c.getTimeInMillis();
c.set(2004,1,7,15,40);
c.set(2004,0,7,15,40);
day1 += (DAY_IM * 29.52);
Calendar c = new Calendar();
code magnets
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
numbers and statics
you are here 313
]e;ejze o|ajoz
StaticSuper{ } {
System.out.println{
"super constructor"|,
}
File Edit Window Help Cling
%java StaticTests
super static block
static block 3
in main
super constructor
constructor
PossibIe Dutput
] ge eomgj|e;
SfoficSuper is o consfrucfor, ond musf
hove ( ) in ifs signofure. Mofice fhof os
fhe oufpuf beIow demonsfrofes, fhe sfofic
bIocks for bofh cIosses run before eifher
of fhe consfrucfors run.
1. To usc ihc Maih class, ihc hisi sic is io
maIc an insiancc ol ii.
2. You can maiI a consiiucioi wiih ihc Icy-
woiu siaiic`.
S. Siaiic mcihous uon`i havc acccss io an
ol|cci`s insiancc vaiiallcs.
4. Ii is goou iaciicc io call a siaiic mcihou
using a iclcicncc vaiiallc.
. Siaiic vaiiallcs coulu lc uscu io couni ihc
insianccs ol a class.
6. Consiiuciois aic callcu lcloic siaiic vaii-
allcs aic iniiializcu.
7. MAX_SIZE woulu lc a goou namc loi a
siaiic hnal vaiiallc.
S. A siaiic iniiializci llocI iuns lcloic a class`s
consiiucioi iuns.
9. Il a class is maiIcu hnal, all ol iis mcihous
musi lc maiIcu hnal.
10. A hnal mcihou can only lc ovciiiuucn il
iis class is cxicnucu.
11. Thcic is no wiaci class loi loolcan
iimiiivcs.
12. A wiaci is uscu whcn you wani io iicai a
iimiiivc liIc an ol|cci.
1S. Thc aiscXxx mcihous always iciuin a
Siiing.
14. Ioimaiiing classcs which aic uccoulcu
liom I/O), aic in ihc |ava.loimai acIagc.
FuIse
FuIse
True
FuIse
True
FuIse
True
True
FuIse
FuIse
FuIse
True
FuIse
FuIse
True or FoIse
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
314 chapter 10
]e;ejze o|ajoz
import java.util.*;
import static java.lang.System.out;
class FullMoons {
static int DAY_IM = 1000 * 60 * 60 * 24;
public static void main(String [] args) {
Calendar c = Calendar.getInstance();
c.set(2004,0,7,15,40);
long day1 = c.getTimeInMillis();
for (int x = 0; x < 60; x++) {
day1 += (DAY_IM * 29.52)
c.setTimeInMillis(day1);
out.println(String.format(full moon on %tc, c));
}
}
}

File Edit Window Help Howl
% java FullMoons
full moon on Fri Feb 06 04:09:35 MST 2004
full moon on Sat Mar 06 16:38:23 MST 2004
full moon on Mon Apr 05 06:07:11 MDT 2004
Noics on ihc Iunai Couc Magnci:
You mighi uiscovci ihai a lcw ol ihc
uaics iouuccu ly ihis iogiam aic
oll ly a uay. This asiionomical siull
is a liiilc iiicIy, anu il wc mauc ii
cilcci, ii woulu lc ioo comlcx io
maIc an cxcicisc hcic.
Hini: onc iollcm you mighi iiy io
solvc is lascu on uillcicnccs in iimc
zoncs. Can you soi ihc issuc.
code magnets soIution
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
11 exception handIing
this is a new chapter 315
Stuff happens. The fiIe isn't there. The server is down. No matter how
good a programmer you are, you can't control everything. Things can go wrong. vety wrong.
when you write a risky method, you need code to handle the bad things that might happen.
8ut how do you lnow when a method is riskyI And where do you put the code to honJle the
exceriennl situationI So far in this book, we haven't teolly taken any risks. we've certainly had
things go wrong at runtime, but the problems were mostly flaws in our own code. 8ugs. And
those we should fix at development time. No, the problem-handling code we're talking about
here is for code that you cont guaranatee will work at runtime. Code that expects the file to be
in the right directory, the server to be running, or the Thread to stay asleep. And we have to do
this now. 8ecause in th|s chapter, we're going to build something that uses the risky 1avaSound
AP|. we're going to build a M|D| Music Player.
Risky Behavior
Sure if's risky,
buf I con if if
somefhing goes wrong.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
31
chapter 11
buiIding the MIDI Music PIayer
Ic!s mzkc z Mes|r Mzrh|nc
Ovci ihc ncxi ihicc chaicis, wc`ll luilu a lcw uillcicni sounu
alicaiions, incluuing a BcaiBox Dium Machinc. In laci,
lcloic ihc looI is uonc, wc`ll havc a mulii-layci vcision so
you can scnu youi uium loos io anoihci layci, Iinu ol liIc
a chai ioom. You`ic going io wiiic ihc wholc ihing, alihough
you can choosc io usc Rcauy-laIc couc loi ihc GUI aiis.
OK, so noi cvciy IT ucaiimcni is looIing loi a ncw BcaiBox
scivci, lui wc`ic uoing ihis io Ien.r moic aloui Jn.n. Builuing
a BcaiBox is |usi a way io havc lun wL.Ie wc`ic lcaining ]ava.
Ihc f|n|shc4 Bcz!Ber |eeks semc!h|n] ||kc !h|s:
]--- --::.-, l.l -l:
:--l l- l- -l-- |.]--:,
.|-- -l ]--- :-----l
-.l .ll---, --- ]--
l --|l'
Andy: groove #2
6hr|s: groove2 rev|sed
N|ge|: dance beat
dance beat
-:--- --::.-: --- -l-- |.]--: c|: --- l- |-. l- .ll--- l.l
--: -l l, .- l-- :|:
'l.-l' l- |.] l
Pui chccImaiIs in ihc loxcs loi cach ol ihc 16 lcais`. Ioi cxamlc, on lcai
1 ol 16) ihc Bass uium anu ihc Maiacas will lay, on lcai 2 noihing, anu
on lcai S ihc Maiacas anu Closcu Hi-Hai... you gci ihc iuca. Whcn you hii
Siaii`, ii lays youi aiicin in a loo uniil you hii Sio`. Ai any iimc, you
can caiuic" onc ol youi own aiicins ly scnuing ii io ihc BcaiBox scivci
which mcans any oihci laycis can lisicn io ii). You can also loau any ol ihc
incoming aiicins ly clicIing on ihc mcssagc ihai gocs wiih ii.
/-- -.- . -.l- |-- |. ||~-.l --- .ll---`
] -ll- :-:-.-: - l- --:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
317
Wc|| s!zr! w| !h !hc |zs|rs
M
|l
| |- .: ----
.l--
.--l -- . :-- :--| -
|.]-, -l l --:-'l .- .-]
.:l-.| :--- .l. |l': - -
|- :--l -
-:: -:l--:l--:
-- . |.]--~.--
M|l| |-
M
|l
|~
:..
|- |-:l
---
--l
Olviously wc`vc goi a lcw ihings io lcain lcloic ihc wholc
iogiam is hnishcu, incluuing how io luilu a Swing GUI, how
io orre io anoihci machinc via nciwoiIing, anu a liiilc I/O
so wc can erJ somcihing io ihc oihci machinc.
Oh ycah, anu ihc ]avaSounu API. TLn` whcic wc`ll siaii in ihis
chaici. Ioi now, you can loigci ihc GUI, loigci ihc nciwoiIing
anu ihc I/O, anu locus only on gciiing somc MIDI-gcnciaicu
sounu io comc oui ol youi comuici. Anu uon`i woiiy il you
uon`i Inow a ihing aloui MIDI, oi a ihing aloui icauing oi
maIing music. Evciyihing you nccu io lcain is covcicu hcic.
You can almosi smcll ihc iccoiu ucal.
Ihc 1zvz8een4 ||
]avaSounu is a collcciion ol classcs anu inicilaccs auucu io
]ava siaiiing wiih vcision 1.S. Thcsc aicn`i sccial auu-ons,
ihcy`ic aii ol ihc sianuaiu ]2SE class liliaiy. ]avaSounu is slii
inio iwo aiis: MIDI anu Samlcu. Wc usc only MIDI in ihis
looI. MIDI sianus loi Musical Insiiumcni Digiial Inicilacc,
anu is a sianuaiu ioiocol loi gciiing uillcicni Iinus ol
clcciionic sounu cquimcni io communicaic. Bui loi
oui BcaiBox a, you can ihinI ol MIDI as n I.rJ o
Lee u. ihai you lccu inio somc ucvicc you can ihinI
ol liIc a high-icch layci iano`. In oihci woius, MIDI
uaia uocsn`i aciually incluuc any ourJ, lui ii uocs
incluuc ihc .r.u.or ihai a MIDI-icauing insiiumcni
can lay lacI. Oi loi anoihci analogy, you can ihinI ol
a MIDI hlc liIc an HTMI uocumcni, anu ihc insiiumcni
ihai icnucis ihc MIDI hlc i.c. In, ii) is liIc ihc Wcl
liowsci.
MIDI uaia says wLn io uo lay miuulc C, anu hcic`s how haiu
io hii ii, anu hcic`s how long io holu ii, cic.) lui ii uocsn`i say
anyihing ai all aloui ihc aciual ourJ you hcai. MIDI uocsn`i
Inow how io maIc a uuic, iano, oi ]immy Hcnuiix guiiai
sounu. Ioi ihc aciual sounu, wc nccu an insiiumcni a MIDI
ucvicc) ihai can icau anu lay a MIDI hlc. Bui ihc ucvicc is
usually moic liIc an er..e bnrJ o. o.Le.n ol insiiumcnis. Anu
ihai insiiumcni mighi lc a hysical ucvicc, liIc ihc clcciionic
Icyloaiu synihcsizcis ihc iocI musicians lay, oi ii coulu
cvcn lc an insiiumcni luili cniiicly in soliwaic, living in youi
comuici.
Ioi oui BcaiBox, wc usc only ihc luili-in, soliwaic-only
insiiumcni ihai you gci wiih ]ava. Ii`s callcu a ,rLe..e. somc
lolIs iclci io ii as a own.e ,rL) lccausc ii .ene sounu.
Sounu ihai you Len..

-.--
M|l| -:- ---: -- l-
'--.' . M|l| |- .- |.] .:
l- :--- 1- -:- -l
- . :]-l-:--- -]-.- --
:--- -l-- - - -:l-----l
c:-.||], . M|l| -:l-----l
:.- |.] . |61 - ----l
:---: |.--, ---:, -|-,
-l:`, .- .|| .l l- :.-- l--
- . M|l| |- :-'l |- :--l
--:: -- -:l --- --::.- -
l- .- ~~ l :.- -| l-
.-l: -- A|| l- --::.-:
|.]- . .-l:-|.- :--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
I|rs! wc ncc4 z 8cecnrcr
Bcloic wc can gci any sounu io lay, wc nccu a Scqucncci ol|cci. Thc
scqucncci is ihc ol|cci ihai iaIcs all ihc MIDI uaia anu scnus ii io ihc iighi
insiiumcnis. Ii`s ihc ihing ihai ihc music. A scqucncci can uo a loi ol
uillcicni ihings, lui in ihis looI, wc`ic using ii siiicily as a laylacI ucvicc. IiIc
a CD-layci on youi sicico, lui wiih a lcw auucu lcaiuics. Thc Scqucncci class
is in ihc |avax.sounu.miui acIagc aii ol ihc sianuaiu ]ava liliaiy as ol vcision
1.S). So lci`s siaii ly maIing suic wc can maIc oi gci) a Scqucncci ol|cci.
but it Iooked so simpIe
import javax.sound.midi.*;
public class MusicTest1 {

public void play() {
Sequencer sequencer = MidiSystem.getSequencer();

System.out.println(We got a sequencer);
} // close play
public static void main(String[] args) {
MusicTest1 mt = new MusicTest1();
mt.play();
} // close main
} // close class
---l l- ..:---- .:.-
w- --- . ----:-- --:l |l': l-
-.- .-l - l- M|l| -:-/-:l-----l
--'-- -:- |l': l- l- l.l, --||,
:----:-: .|| l- M|l| ----.l-- -l-
. ':--' B-l -- --'l -.- . -.-
--- --- ---:-|-: ~~ -- .- l- .: l-
M]:l-- l- - -: ---
File Edit Window Help SayWhat?
% javac MusicTest1.java
MusicTest1.java:13: unreported exception javax.sound.midi.
MidiUnavailableException; must be caught or declared to be
thrown
Sequencer sequencer = MidiSystem.getSequencer();
^
1 errors
1: :-- ---'l :--|-' 1- :--|-- :.]: l---': .-
'------l- -:-l--' l.l --:l - :.-l -- -:|.--
8emc!h|n]s wren]|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
319
1 Let's say you want
to call a method in a
class that you didn't
write.
2 That method does
something risky,
something that might
not work at runtime.
3 You need to know
that the method
you're calling is
risky.
Whz! hzppcns whcn z mc!he4 yee wzn! !e rz||
|pre|z||y |n z r|zss yee 4|4n! wr| !cI |s r|sky!
4 You then write code
that can handle the
failure if it does
happen. You need to be
prepared, ]ust in case.
you
cIoss you
didn'f wrife
wrife
f
h
o
f
uses mefh
o
d
s

i
n
void moo() {
if (serverDown) {
explode();
}
}
you
your code
class Cow {
void moo() {
if (serverDown){
explode();
}
}
}
cIoss you
didn'f wrife
class Cow {
void moo() {
if (serverDown){
explode();
}
}
}
cIoss you
didn'f wrife
class Cow {
void moo() {
if (serverDown){
explode();
}
}
}
I wonder if
fhof mefhod
couId bIow up...
My moo()
mefhod wiII
expIode if fhe
server is down.
you
w
rife so
f
e
I
y
Mow fhof I
know, I con foke
precoufions.
your code
class Bar {
void go() {
moo();
}
int stuff() {
x.beep();
}
}
class Bar {
void go() {
try{
moo();
}catch(MX m){
cry();
}
}
}
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
1- A|| -:: l-|| ]--
l.l -l----:--|`
:.- l--- .- -:-l--
Mc-..|.|-!:-l--
A --l- .: l- -:|.--
l- -:-l--: l -l
l---
1: .-l l-||: ]-- w+!N ]-- -l -l l.l
-:-l-- ~~ - l: :.:-, -:.-:- - --:---:-
--:l-:l--: |-: :--| -:l --.-: l- :----:--
: .|--.] -- -:-`
]ava`s cxcciion-hanuling mcchanism is a clcan, wcll-lighicu way io hanulc cxcciional
siiuaiions" ihai o u ai iuniimc, ii lcis you ui all youi ciioi-hanuling couc in onc
casy-io-icau lacc. Ii`s lascu on you Irow.r ihai ihc mcihou you`ic calling is iisIy
i.c. ihai ihc mcihou .L gcnciaic an cxcciion), so ihai you can wiiic couc io ucal
wiih ihai ossililiiy. Il you Irow you mighi gci an cxcciion whcn you call a aiiiculai
mcihou, you can lc .en.eJ loi-ossilly cvcn .eo.e. liom-ihc iollcm ihai causcu
ihc cxcciion.
So, how Jo you Inow il a mcihou ihiows an cxcciion. You hnu a throws clausc in ihc
iisIy mcihou`s ucclaiaiion.
The getSequencer() method takes a risk. t can fail at runtime.
8o it must declare' the risk you take when you call it.
when things might go wrong
Mc!he4s |n 1zvz esc ex6ef|o0t !e !c|| !hc rz|||n] re4c,
8emc!h|n] Bz4 Hzppcnc4. | fz||c4.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
321
Ihc remp||cr ncc4s !e knew
!hz! Y00 knew yeerc rz|||n]
z r|sky mc!he4.
Il you wia ihc iisIy couc in somcihing callcu a
, ihc comilci will iclax.
A iiy/caich llocI iclls ihc comilci ihai you
an cxcciional ihing coulu hacn in ihc
mcihou you`ic calling, anu ihai you`ic icaicu
io hanulc ii. Thai comilci uocsn`i caic you
hanulc ii, ii caics only ihai you say you`ic iaIing
caic ol ii.
import javax.sound.midi.*;
public class MusicTest1 {
public void play() {
try {
Sequencer sequencer = MidiSystem. getSequencer();
System.out.println(Successfully got a sequencer);
} catch(MidiUnavailableException ex) {
System.out.println(Bummer);
}
} // close play
public static void main(String[] args) {
MusicTest1 mt = new MusicTest1();
mt.play();
} // close main
} // close class
-l l- -:] l-
- . 'l-]' |-:
-
.- . ':.l:' |-:
-- -
.l l-

-
l- -
:-l--.| :l-.l--
.--: ~
~
- -l-- -
--
:, .
M

c
-..|.|-!

:-l-- : l---
-
] l- :.|| l- -l
----:--|`
;
~.
.
..

/.
.
~/., ~ ./ ..
~. , ./ .
~ ~
~
,.~. ,/, .
~//
;
~. ,/,.

. .~, . ~

~/ ./ .
,

, . .~
., ~. ./ . . .~
.

~., ..
. ~ .~/
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
322
chapter 11
I'm gonno
fhis risky fhing
ond I'm gonno
myseIf if I foII.
Don't try this at home.
try {
// do risky thing
} catch(Exception ex) {
// try to recover
}
n crrcp!|en |s zn e|jcr!...
ef !ypc Irrcp!|en.
Which is loiiunaic, lccausc ii woulu lc much haiuci
io icmcmlci il cxcciions wcic ol iyc Bioccoli.
Rcmcmlci liom youi olymoihism chaicis ihai
an ol|cci ol iyc Excciion nr lc an insiancc ol any
ubIn ol Excciion.
Bccausc an E:e.or is an ol|cci, whai you nL is an
ol|cci. In ihc lollowing couc, ihc catch aigumcni
is ucclaicu as iyc Excciion, anu ihc aiamcici
iclcicncc vaiiallc is e:.
l': -:l |- -:|.--
. --l- .-----l
1
: :-- --|] ---: .-
!
:-l-- : l---
-
|nterruptedExcept|on
Throwab|e
Except|on
|0Except|on
getHessage(}
pr|nt8tackTrace(}
|.-l - l- !:-l--
:|.:: --.-:] 1-] .||
-l-- :|.:: 1---.|-
.- ---l l-- -]
--l-:
exceptions are objects
Whai you wiiic in a caich llocI uccnus on ihc
cxcciion ihai was ihiown. Ioi cxamlc, il a scivci
is uown you mighi usc ihc caich llocI io iiy anoihci
scivci. Il ihc hlc isn`i ihcic, you mighi asI ihc usci
loi hcl hnuing ii.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
exception handIing
323
|f | !s yeer re4c !hz! rz!rhcs !hc crrcp!|en,
!hcn whesc re4c !hrews | !!
You`ll scnu much moic ol youi ]ava couing iimc LnrJI.r
cxcciions ihan you`ll scnu .en.r anu L.ow.r ihcm youiscll.
Ioi now, |usi Inow ihai whcn youi couc nII a iisIy mcihou-a
mcihou ihai ucclaics an cxcciion-ii`s ihc iisIy mcihou ihai
L.ow ihc cxcciion lacI io ,ou, ihc callci.
In icaliiy, ii mighi lc you who wioic loih classcs. Ii ically
uocsn`i maiici who wiiics ihc couc... whai maiicis is Inowing
which mcihou L.ow ihc cxcciion anu which mcihou nLe ii.
Whcn somclouy wiiics couc ihai coulu ihiow an cxcciion, ihcy
musi JeIn.e ihc cxcciion.
|- |-,| ,.,,
.a,. ,a, a|,-,
|-,| ,,,-. [|
-.-,.| .- a,,a,-
,,,| |a.| , ,-
.a,,-,.
;- |-,| ,a,
,,,- a- , |-.,a,-
,a, ., |._, ,,,
,- -.-,.|.
public void takeRisk() throws BadException {
if (abandonAllHope) {
throw new BadException();
}
}
:--.
l
- .
---
!

:-
l
-
-
-

-:l
.
-
l

--
-
l

l: -
-l- M
c
1
l-|| l- ---| |]
-:|.--` l.l l l---: . B
.!
:-l--
public void crossFingers() {
try {
anObject.takeRisk();
} catch (BadException ex) {
System.out.println(Aaargh!);
ex.printStackTrace();
}

| ]-- :.-'l --:--- --- l- -:-l--, .l |!A1 -l . :l.: l-.:- -:- l- --ll.:1-.:-|` --l- l.l .|| -:-l--: ---l
cIoss wifh o
risky mefhod
f
h
r
o
w
s on excep
fio
n

b
o
c
k
class Cow {
void moo() {
if (serverDown){
explode();
}
}
}
your code
class Bar {
void go() {
moo();
}
int stuff() {
x.beep();
}
}
coIIs risky mefhod
1
2
Risky, exception-throwing code:
Your code that calls the risky method:
1
2
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
324
chapter 11
(-,- a,- |
oa|| qa--(:|-
Wait just a minutel How come this is the FIRS7 time
we've had to try/catch an xception! What about the
exceptions I've aIready gotten Iike NuIIPointerxception
and the exception for DivideyZero. I even got a
NumberFormatxception from the Integer.parseInt()
method. How come we didn't have to catch those!
The compiler cares about all subclasses of Lxception,
unless they are a special type, PuntimeLxception. Any
exception class that extends PuntimeLxception gets a
free pass. PuntimeLxceptions can be thrown anywhere,
with or without throws declarations or try/catch blocks.
The compiler doesn't bother checking whether a method
declares that it throws a PuntimeLxception, or whether the
caller acknowledges that they might get that exception at
runtime.
I'II bite. WHY doesn't the compiIer care about those
runtime exceptions! Aren't they just as IikeIy to bring the
whoIe show to a stop!
Most PuntimeLxceptions come from a problem in
your code logic, rather than a condition that fails at runtime
in ways that you cannot predict or prevent. ou connot
guarantee the file is there. ou connot guarantee the server
is up. 8ut you con make sure your code doesn't index off the
end of an array (that's what the .length attribute is for).
ou wANT PuntimeLxceptions to happen at development
and testing time. ou don't want to code in a try/catch, for
example, and have the overhead that goes with it, to catch
something that shouldn't happen in the first place.
A try/catch is for handling exceptional situations, not flaws
in your code. Use your catch blocks to try to recover from
situations you can't guarantee will succeed. Or at the very
least, print out a message to the user and a stack trace, so
somebody can figure out what happened.
The compiler checks for everything
except RuntimeExceptions.
The compiler guarantees:
--l--!:-l--: .-- N61 :-:- ] l-
:--|-- 1-]'-- ---- .: | :---:- ---`
--:-:- -:-l--:' /-- :.- l---, :.l:,
.- -:|.-- --l--!:-l--:, -l ]-- --'l
.- l-, .- l- :--|-- ---'l :-:
|nterruptedExcept|on
Except|on
|0Except|on Runt|meExcept|on
Nu||Po|nterExcept|on 6|ass6astExcept|on
!:-l--: l.l .-- N61 :-:|.::-: -
--l--!:-l-- .-- :-:- -- ]
l- :--|-- 1-]'-- :.||- :-:-
-:-l--:'
|f you thtow an exception in your code you must declare it using
the thtows keyword in your method declaration.
|f you coll a method that throws an exception (in other words,
a method that Jeclotes it throws an exception), you must
oclnowleJe that you're aware of the exception possibility.
One way to satisfy the compiler is to wrap the call in a try/catch.
( There's a second way we'll look at a little later in this chapter.)
checked and unchecked exceptions
1
2
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
325
8ll P0lk5
A rel|od car l|roW ar excepl|or W|er sorel||r la||s al rurl|re.
Ar excepl|or |s a|Ways ar oojecl ol lype Excepl|or. (w||c|, as you
rereroer lror l|e po|yrorp||sr c|aplers rears l|e oojecl |s lror a
c|ass l|al |as Excepl|or soreW|ere up |ls |r|er|larce lree.)
T|e corp||er does N0T pay allerl|or lo excepl|ors l|al are ol
lype Runt|meExcept|on. A Rurl|reExcepl|or does rol |ave lo oe
dec|ared or Wrapped |r a lry/calc| (a|l|ou| you're lree lo do e|l|er or
ool| ol l|ose l||rs)
A|| Excepl|ors l|e corp||er cares aooul are ca||ed 'c|ec|ed
excepl|ors' W||c| rea||y rears oom||er-c|ec|ed excepl|ors. 0r|y
Rurl|reExcepl|ors are exc|uded lror corp||er c|ec||r. A|| ol|er
excepl|ors rusl oe ac|roW|eded |r your code, accord|r lo l|e
ru|es.
A rel|od l|roWs ar excepl|or W|l| l|e |eyWord throw, lo||oWed oy
a reW excepl|or oojecl:
throw new NoCaffeineException();
Vel|ods l|al m|gnr l|roW a c|ec|ed excepl|or arrource |l W|l|
a throws Exception dec|aral|or.
ll your code ca||s a c|ec|ed-excepl|or-l|roW|r rel|od, |l rusl
reassure l|e corp||er l|al precaul|ors |ave oeer la|er.
ll you're prepared lo |ard|e l|e excepl|or, Wrap l|e ca|| |r a lry/calc|,
ard pul your excepl|or |ard||r/recovery code |r l|e calc| o|oc|.
ll you're rol prepared lo |ard|e l|e excepl|or, you car sl||| ra|e l|e
corp||er |appy oy oll|c|a||y 'duc||r' l|e excepl|or. we'|| la|| aooul
duc||r a ||ll|e |aler |r l||s c|apler.
Which of these do you think
might throw an exception that
the compiIer wouId care about!
We're onIy Iooking for the
things that you can't controI in
your code. We did the rst one.
(8ecause it was the easiest.)
__ connect to a remote server
__ access an array beyond its length
__ display a window on the screen
__ retrieve data from a database
__ see if a text le is where you it is
__ create a new le
__ read a character from the command-line
+,-+ :+ ,-+:.|
7hings you want to do
__________________________________
__________________________________
__________________________________
__________________________________
__________________________________
__________________________________
__________________________________
What might go wrong
l- :---- : ---
ezca||re |(
ll you're lry|r lo |earr sorel||r reW,
ra|e l|al l|e |asr l||r you lry lo |earr
oelore o|r lo s|eep. 3o, orce you pul l||s
ooo| doWr (assur|r you car lear yourse|l
aWay lror |l) dor'l read aryl||r e|se rore
c|a||er|r l|ar l|e oac| ol a C|eer|os
oox. Your ora|r reeds l|re lo process W|al
you've read ard |earred. T|al cou|d la|e
a leW nours. ll you lry lo s|ove sorel||r
reW |r r||l or lop ol your Java, sore ol l|e
Java r||l rol 'sl|c|.'
0l course, l||s doesr'l ru|e oul |earr|r
a p|ys|ca| s||||. wor||r or your |alesl
8a||roor K|c|8ox|r roul|re
prooao|y Wor'l allecl your
Java |earr|r.
For l|e oesl resu|ls, read l||s
ooo| (or al |easl |oo| al
l|e p|clures) r||l oelore
o|r lo s|eep.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
try {
Foo f = x.doRiskyThing();
int b = f.getNum();

} catch (Exception ex) {
System.out.println(failed);
}
System.out.println(We made it!);
exceptions and fIow controI
|-:l l- l-] |-: ---:,
l-- l- :-- -|-- l-
:.l: ---:
File Edit Window Help RiskAll
%java Tester
We made it!
Whcn you call a iisIy mcihou, onc ol iwo ihings can ha-
cn. Thc iisIy mcihou ciihci succccus, anu ihc iiy llocI
comlcics, oi ihc iisIy mcihou ihiows an cxcciion lacI io
youi calling mcihou.
I|ew ren!re| |n !ry/rz!rh ||erks
f the try succeeds
{doRiskyThing{} does not
throw an exception}
1
try {
Foo f = x.doRiskyThing();
int b = f.getNum();

} catch (Exception ex) {
System.out.println(failed);
}
System.out.println(We made it!);
1
- l-] |-: ---:, -l l-
:.|| l- -:]1
-|` l---:
.- -:-l--, :- l- --:l -
l- l-] |-: --:-'l ---
1
- :.l: |-: ---:, l--
l- --l- :--l---: --
File Edit Window Help RiskAll
%java Tester
failed
We made it!
f the try fails
{because doRiskyThing{}
does throw an exception}
1
- --:l - l- l
-] |-: --~
-- ---:, -
: : . 6
-- 1
-
-:.-:- l- --:l - l- l-]
---: -- l- :-::-:: -
l- :.|| l- -
:]1
-|`
2
1
2
3
1- :-- - l-
:.l: |-: ----
---:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
327
Il you iiy io cooI somcihing, you siaii ly iuining on
ihc ovcn.
Il ihc ihing you iiy is a comlcic Iailurc
you hove to turn o[[ the oven.
Il ihc ihing you iiy succccds,
you hove to turn o[[ the oven.
You hove to turn o[[ the oven no motter whot:
Are you sure
you wonf fo fry
fhis7
Mo moffer whof, do MOT Ief
me forgef fo furn off fhe
ovenl Losf fime I forched hoIf
fhe neighborhood.
I|nz||y: fer !hc !h|n]s yee wzn!
!e 4e ne mz!!cr whz!.
A hnally block is where you put
code that must run regardless
of an exception.
try {
turnOvenOn();
x.bake();
turnOvenOff();
} catch (BakingException ex) {
ex.printStackTrace();
turnOvenOff();
}
Wiihoui hnally, you havc io ui ihc
iuinOvcnOll) in ihc iiy anu ihc caich
lccausc you hove to turn o[[ the oven no motter
whot. A hnally llocI lcis you ui all youi
imoiiani clcanu couc in lacc insicau ol
uulicaiing ii liIc ihis:
try {
turnOvenOn();
x.bake();
} catch (BakingException ex) {
ex.printStackTrace();
} nally {
turnOvenOff();
}
f the try block fails {an exception}, fIow
controI immediateIy moves to the catch bIock.
When the catch bIock compIetes, the finaIIy
bIock runs. When the finaIIy bIock compIetes,
the rest of the method continues on.
f the try block succeeds {no exception},
fIow controI skips over the catch bIock and
moves to the finaIIy bIock. When the finaIIy
bIock compIetes, the rest of the method
continues on.
f the try or catch block has a return
statement, hnally will still runl FIow
jumps to the finaIIy, then back to the return.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
Look at the code to the Ieft. What do you think the
output of this program wouId be! What do you think
it wouId be if the third Iine of the program were
changed to: String test = "yes", !
Assume Scaryxception extends xception.
+,-+ :+ ,-+:.|
public class TestExceptions {
public static void main{String args| {
String test = "no",
try {
System.out.println{"start try"|,
doRisky{test|,
System.out.println{"end try"|,
} catch { ScaryException se| {
System.out.println{"scary exception"|,
} nally {
System.out.println{"nally"|,
}
System.out.println{"end of main"|,
}
static void doRisky{String test| throws ScaryException {
System.out.println{"start risky"|,
if {"yes".equals{test|| {
throw new ScaryException{|,
}
System.out.println{"end risky"|,
return,
}
}
Dutput when test = "no"
Dutput when test = "yes"
w h e n t e s t " n o : s t a r t t r y - s t a r t r i s k y - e n d r i s k y - e n d t r y - n a l l y - e n d o f m a i n
w h e n t e s t " y e s : s t a r t t r y - s t a r t r i s k y - s c a r y e x c e p t i o n - n a l l y - e n d o f m a i n
I|ow 0onIro|
fIow controI exercise
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
329
public class Foo {
public void go() {
Laundry laundry = new Laundry();
try {
laundry.doLaundry();
} catch(PantsException pex) {
// recovery code
} catch(LingerieException lex) {
// recovery code
}
}
}
A mcihou can ihiow muliilc cxcciions il ii uain wcll nccus io. Bui
a mcihou`s ucclaiaiion musi ucclaic ihc chccIcu cxcciions ii can
ihiow alihough il iwo oi moic cxcciions havc a common suciclass, ihc
mcihou can ucclaic |usi ihc suciclass.)
P|4 wc mcn!|en !hz! z mc!he4 rzn
!hrew merc !hzn enc crrcp!|en!
Thc comilci will maIc suic ihai you`vc hanulcu ihc chccIcu cxcc-
iions ihiown ly ihc mcihou you`ic calling. SiacI ihc llocIs unuci
ihc , onc alici ihc oihci. Somciimcs ihc oiuci in which you siacI ihc
caich llocIs maiicis, lui wc`ll gci io ihai a liiilc laici.
0z!rh|n] me| !|p|c crrcp!|ens
public class Laundry {
public void doLaundry() throws PantsException, LingerieException {
// code that could throw either exception
}
}
1
: --l- -:|.--: l--, :---l '--,
1
w
6 -:-l--:
-|.---]|` l---: .
|.-l:!:-l--, l |.-: - l-
|.-l:!:-l-- :.l: |-:
-|.---]|` l---: .
|----!:-l--, l |.-: - l-
|----!:-l-- :.l: |-:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
330
chapter 11
Excciions aic ol|ccis, icmcmlci. Thcic`s noihing all ihai
sccial aloui onc, cxcci ihai ii is n L.r Ln nr be .
So liIc all goou ol|ccis, Excciions can lc iclciicu io
olymoihically. A IingciicExcciion obe, loi cxamlc,
coulu lc assigncu io a CloihingExcciion .ee.ere. A
PanisExcciion coulu lc assigncu io an Excciion iclcicncc.
You gci ihc iuca. Thc lcnchi loi cxcciions is ihai a mcihou
uocsn`i havc io cxliciily ucclaic cvciy ossillc cxcciion ii
mighi ihiow, ii can ucclaic a suciclass ol ihc cxcciions.
Samc ihing wiih caich llocIs-you uon`i havc io wiiic a caich
loi cach ossillc cxcciion as long as ihc caich oi caichcs)
you havc can hanulc any cxcciion ihiown.
Irrcp!|ens zrc pe|ymerph|r
You can DECLARE exceptions using
a supertype of the exceptions you
throw.
A|| -:-l--: .-
!:-l-- .: .
:---:|.::
Except|on
|0Except|on
1
public void doLaundry() throws ClothingException {

l-:|.-- . c|-l-!:-l-- |-l: ]-- l---
.-] :-:|.:: - c|-l-!:-l-- 1.l --.-:
-|.---]|` :.- l--- . |.-l:!:-l--,
|----!:-l--, 1---l!:-l--, .-
l--::-l!:-l-- -l--l -|:l|] -:|.-- l--
--.||]
You can CATCH exceptions using a
supertype of the exception thrown.
2
try {
laundry.doLaundry();
} catch(ClothingException cex) {
// recovery code
}

try {
laundry.doLaundry();
} catch(ShirtException sex) {
// recovery code
}

:.- :.l: --|]
1---l!:-l-- .-
l
--::-l!:-l--
:.- :.l: .-]
c|-l-!:-l--
:-:|.::
6|oth|ngExcept|on
PantsExcept|on L|nger|eExcept|on 8h|rtExcept|on
Tee8h|rtExcept|on
0ress8h|rtExcept|on
poIymorphic exceptions
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
331
You ouIJ wiiic youi cxcciion-hanuling couc so ihai
you sccily only ore caich llocI, using ihc suciiyc
Excciion in ihc caich clausc, so ihai you`ll lc allc io
caich nr, cxcciion ihai mighi lc ihiown.
Just because you CAN catch everything
with one big super polymorphic catch,
doesn't always mean you 8HOULD.
try {
laundry.doLaundry();
} catch(Exception ex) {
// recovery code...
}

-:---] --- w+A1 1: :.l: |-: -||
:.l: AN/ .- .|| -:-l--:, :- ]-- ---'l
.-l--.l:.||] --- -.l ---l ----
Ioi cxamlc, il youi couc ucals wiih oi iccovcis
liom) a TccShiiiExcciion uillcicnily ihan ii hanulcs a
IingciicExcciion, wiiic a caich llocI loi cach. Bui il you
iicai all oihci iycs ol CloihingExcciion in ihc samc way,
ihcn auu a CloihingExcciion caich io hanulc ihc icsi.
Write a different catch block for each
exception that you need to handle
uniquely.
try {
laundry.doLaundry();
} catch(TeeShirtException tex) {
// recovery from TeeShirtException
} catch(LingerieException lex) {
// recovery from LingerieException
} catch(ClothingException cex) {
// recovery from all others
}
1
---l!
:-l--: .-
|
----!
:-l--: --- ----l
--:---] :--, :- ]-- :--| -:-
----l :.l: |-::
A|| -l-- c|-l-!:-l--:
.-- :.-l ---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
332
chapter 11
Thc highci u ihc inhciiiancc iicc, ihc liggci ihc
caich lasIci`. As you movc uown ihc inhciiiancc
iicc, iowaiu moic anu moic sccializcu Excciion
classcs, ihc caich lasIci` is smallci. Ii`s |usi lain olu
olymoihism.
A ShiiiExcciion caich is lig cnough io iaIc
a TccShiiiExcciion oi a DicssShiiiExcciion
anu any luiuic sulclass ol anyihing ihai cxicnus
ShiiiExcciion). A CloihingExcciion is cvcn liggci
i.c. ihcic aic moic ihings ihai can lc iclcicnccu
using a CloihingExcciion iyc). Ii can iaIc an
cxcciion ol iyc CloihingExcciionuuh), anu
any CloihingExcciion sulclasscs: PanisExcciion,
UniloimExcciion, IingciicExcciion, anu
ShiiiExcciion. Thc moihci ol all caich aigumcnis
is iyc Exccption, ii will caich cxcciion,
incluuing iuniimc unchccIcu) cxcciions, so you
iolally won`i usc ii ouisiuc ol icsiing.
Me| !|p|c rz!rh ||erks mes! |c er4crc4
frem smz||cs! !e ||]]cs!
Un|formExcept|on
6|oth|ngExcept|on
PantsExcept|on L|nger|eExcept|on 8h|rtExcept|on
Tee8h|rtExcept|on 0ress8h|rtExcept|on
catch(TeeShirtException tex)
catch(ShirtException sex)
catch(ClothingException cex)
1
---l!
:-l--: .--
:.-l ---, -l -- -l--
-:-l--: -
|| l
1
---l!
:-l--: -
||
---- -l ---, -l .||
-l-- -l!
:-l--
:-:|.::-: .-- :.-l ---
A
|| c
|-l-!
:-l--:
.-- :.-l ---, .|l--
1
---l!
:-l-- .-
-l!
:-l-- -
|| ----
-l l: .-
order of muItipIe catch bIocks
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
exception handIing
333
try {
laundry.doLaundry();
} catch(ClothingException cex) {
// recovery from ClothingException
} catch(LingerieException lex) {
// recovery from LingerieException
} catch(ShirtException sex) {
// recovery from ShirtException
}


Si;e moffers when
you hove muIfipIe cofch
bIocks. The one wifh fhe biggesf
boskef hos fo be on fhe boffom.
Ofherwise, fhe ones wifh
smoIIer boskefs ore useIess.
Yee rzn! pe! ||]]cr |zskc!s
z|evc smz||cr |zskc!s.
Wcll, you lui ii won`i comilc. Caich
llocIs aic noi liIc ovciloaucu mcihous
whcic ihc lcsi maich is icIcu. Wiih caich
llocIs, ihc ]VM simly siaiis ai ihc hisi onc
anu woiIs iis way uown uniil ii hnus a caich
ihai`s lioau cnough in oihci woius, high
cnough on ihc inhciiiancc iicc) io hanulc
ihc cxcciion. Il youi hisi caich llocI is
catch(Exception ex), ihc comilci
Inows ihcic`s no oini in auuing any
oihcis-ihcy`ll ncvci lc icachcu.
S:l|:ags :aa le :a aay a:Je:, le:aase they
:aa't :at:h aae aaathe:'s ex:et:aas.
ou could put ShirtLxception above
LingerieLxception and nobody would mind.
8ecause even though ShirtLxception is a bigger
(broader) type because it can catch other classes
(its own subclasses), ShirtLxception can't catch a
LingerieLxception so there's no problem.
l
-
-
'l

-
l

:'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
334
chapter 11
poIymorphic puzzIe
|ffEx
FooEx
arEx
try {
x.doRisky();
} catch(AlphaEx a) {
// recovery from AlphaEx
} catch(BetaEx b) {
// recovery from BetaEx
} catch(GammaEx c) {
// recovery from GammaEx
} catch(DeltaEx d) {
// recovery from DeltaEx
}
azEx
o|nkEx
Assume the try/catch block here is legally coded. our task is to draw
two different class diagrams that can accurately ren ect the Lxception
classes. |n other words, what class inheritance structures would make the
try/catch blocks in the sample code legalI
our task is to create two different try / catch structures (similar to
the one above left), to accurately represent the class diagram shown on
the left. Assume ALL of these exceptions might be thrown by the method
with the try block.
+,-+ :+ ,-+:.|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
335
Whcn yee 4en! wzn! !e hzn4|c
zn crrcp!|en...
f you don't want to handle an
exception, you can duck it by
declaring it.
Whcn you call a iisIy mcihou, ihc comilci
nccus you io acInowlcugc ii. Mosi ol ihc iimc,
ihai mcans wiaing ihc iisIy call in a iiy/
caich. Bui you havc anoihci alicinaiivc, simly
JuI ii anu lci ihc mcihou ihai callcu ,ou caich
ihc cxcciion.
Ii`s casy-all you havc io uo is JeIn.e ihai
,ou ihiow ihc cxcciions. Evcn ihough,
icchnically, ,ou aicn`i ihc onc uoing ihc
ihiowing, ii uocsn`i maiici. You`ic siill ihc onc
lciiing ihc cxcciion whiz iighi on ly.
Bui il you uucI an cxcciion, ihcn you uon`i
havc a iiy/caich, so whai hacns whcn ihc
iisIy mcihou uoIaunuiy)) Joe ihiow ihc
cxcciion.
Whcn a mcihou ihiows an cxcciion, ihai
mcihou is ocu oll ihc siacI immcuiaicly,
anu ihc cxcciion is ihiown io ihc ncxi
mcihou uown ihc siacI-ihc nIIe.. Bui il ihc
nIIe. is a JuIe., ihcn ihcic`s no caich loi ii so
ihc nIIe. os oll ihc siacI immcuiaicly, anu
ihc cxcciion is ihiown io ihc ncxi mcihou
anu so on... whcic uocs ii cnu. You`ll scc a
liiilc laici.
ju
s
t d
u
c
k
|t
Whof fhe...7
There is MO woy I'm
cofching fhof fhing. I'm geffin'
ouf of fhe woy-- somebody
behind me con hondIe if.
public void foo() throws ReallyBadException {
// call risky method a try/catch
laundry.doLaundry();
}
/
-- --'l !A
|
|
/
l--- l, -l
:-:- ]-- --'l .- . l-]/:.l:
-- l- -:] --l- ]-- :.||,
/
6c
.-- --- l- -:] --l-'
B
-:.-:- ---, ----- :.||: /
6c

.: l- -.| -l l- -:-l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
handIe or decIare
Perk|n] ||y 4cr|zr|n]I en|y
4c|zys !hc |ncv| !z||c
8ooner or later, somebody has to
deal with it. But what if main{}
ducks the exception?
public class Washer {
Laundry laundry = new Laundry();
public void foo() throws ClothingException {
laundry.doLaundry();
}
public static void main (String[] args) throws ClothingException {
Washer a = new Washer();
a.foo();
}
}
B
-
l

-
-l

:
-:
l

- -
:-
l
-
-
|
]

-:|.
-- l
` :-
l

---': --

]
l
-

.
-
|- l
' 1

: :-
-

|-: -:l

--
moin
moin
foo
doLoundry
moin
foo

moin() coIIs foo()


foo() coIIs doLoundry()
doLoundry() is
running ond fhrows o
CIofhingExcepfion

doLoundry() pops off fhe


sfock immediofeIy ond
fhe excepfion is fhrown
bock fo foo().
8uf foo() doesn'f hove o
fry/cofch, so...
doLoundry() fhrows o
CIofhingExcepfion
foo() ducks fhe
excepfion

moin() ducks fhe
excepfion
foo() pops off fhe
sfock immediofeIy ond
fhe excepfion is fhrown
bock fo... who7 Whof7
There's nobody Ieff
buf fhe JVM, ond if's
fhinking, "Don'f expecf
ME fo gef you ouf of
fhis."

The JVM
shufs down
We're using the tee-shirt to represent a Clothing
Exception. We know, we know... you would
have preferred the blue jeans.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
337
8o now we've seen both ways to satisfy the compiler
when you call a risky {exception-throwing} method.
Handle or Declare. t's the law.
HANDLE 1
try {
laundry.doLaundry();
} catch(ClothingException cex) {
// recovery code
}

Wrop fhe risky coII in o fry/cofch
1: . -ll-- - . ---- :.l: l- .-|- .|| -:-l--: l.l -|.---]| `
-l l--- 6- -|:- l- :--|-- -||
:l|| :--|.- l.l ]--'-- --l :.l:- .|| - l- -:-l--:
DECLARE {duck it} 2
void foo() throws ClothingException {
laundry.doLaundry();
}
DecIore fhof YOUP mefhod fhrows fhe some excepfions
os fhe risky mefhod you're coIIing.
8uf now fhis meons fhof whoever coIIs fhe foo() mefhod
hos fo foIIow fhe HondIe or DecIore Iow. If foo() ducks
fhe excepfion (by decIoring if), ond moin() coIIs foo(), fhen
moin() hos fo deoI wifh fhe excepfion.
public class Washer {
Laundry laundry = new Laundry();
public void foo() throws ClothingException {
laundry.doLaundry();
}
public static void main (String[] args) {
Washer a = new Washer();
a.foo();
}
} B-:.-:- l- --|` --l- -:: l-
c|-l-!:-l-- l---- ] -|.---]|`,
-.-|` .: l- --. .--|` - . l-]/:.l:,
-- -.-|` .: l- -:|.-- l.l l, l--,
l---: c|-l-!:-l--'
N
-- -
.-|` ---'l :--
|-, .- --
-l .- ------l- -:-l--' -----
A
: .- .: l- :--
|--': :--:----,
l- --|` -
-l- l---: .-
-:-l--
16cB|!''
1- -|.---]|` --l- l---: .
c|-l-!:-l--, -l ] -:|.-- l-
-:-l--, l- --|` --l- -l: l-
-: l- -:-l-- N- l-]/:.l:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
fixing the Sequencer code
public void play() {
try {
Sequencer sequencer = MidiSystem.getSequencer();
System.out.println(Successfully got a sequencer);
} catch(MidiUnavailableException ex) {
System.out.println(Bummer);
}
} // close play

Now ihai you`vc comlcicly loigoiicn, wc siaiicu ihis chaici
wiih a hisi looI ai somc ]avaSounu couc. Wc cicaicu a Sc-
qucncci ol|cci lui ii woulun`i comilc lccausc ihc mcihou
Miui.gciScqucncci) ucclaics a chccIcu cxcciion MiuiUnavail-
allcExcciion). Bui wc can hx ihai now ly wiaing ihc call in a
iiy/caich.
0c!!|n] |zrk !e eer mes|r re4c...
N- --|-- :.||- -l----:--|`,
--- l.l --'- --.- l - . l-]/
:.l: |-:
1
- :.l
: .-.-
-l
-- .: l
- -
l
- '-l
' -
:-l
-- |
-
- :.

':.l
:||
|-N
-l
|
---
!

:-l
--
`, l
-
:-
- -
--|
--l
:--
|-, -:.-:- -|]~
-
--:.||] . M

c
-.|.|-!

:-l
--
-
--'l

l
-l
- . |
|-N
-l
|
---
!

:-l
--

--
--
-- l
': --l
---- l
- .- .
:.l
: |-: ]-- .- l
- :.l
: l
-
l
- -- l
---
-'
You cannot have a catch or hnally
without a try
Irrcp!|en Ke|cs
void go() {
Foo f = new Foo();
f.foof();
catch(FooException ex) { }
}
N61
|
!6A|
'
w
---': l- l-]
You cannot put code between the
try and the catch
try {
x.doStuff();
}
int y = 43;
} catch(Exception ex) { }
N61
|!6A|
' /-- :.-'l -l
:-- -l---- l- l-] .-
l- :.l:
A try MU8T be followed by either a
catch or a hnally
try {
x.doStuff();
} hnally {
// cleanup
}
|
!
6
A
|
-:.-:- ]--
.- . -.||], ---
l-- l---': -- :.l:
B
-l ]-- :.---l .- .
l-] ] l:-|
1
2
3
A try with only a hnally {no catch}
must still declare the exception.
void go() throws FooException {
try {
x.doStuff();
} hnally { }
}
4
A l-] -l--l . :.l:
--:-'l :.l:] l-
.-|- -- -:|.-- |.-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
339
CaJe kit:hea
There is MO woy
I'm Ieffing 8effy win fhe
code-off fhis yeor, so I'm
gonno moke if myseIf from
scrofch.
8uf why don'f
you jusf use
Peody-boke code7
)aa Jaa't have ta Ja it
yaa:se|I, lat it's a |at
a:e Iaa iI yaa Ja.
The :est aI this :hate:
is atiaaa| yaa :aa ase
keaJy-la|e :aJe Ia: a||
the asi: as.
5at iI yaa vaat ta |ea:a
a:e alaat JavaSaaaJ,
ta:a the age.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
Rcmcmlci ncai ihc lcginning ol ihc chaici, wc looIcu ai how MIDI uaia holus
ihc insiiuciions loi wLn shoulu lc laycu anu Low ii shoulu lc laycu) anu wc
also saiu ihai MIDI uaia uocsn`i aciually .ene nr, ourJ Ln ,ou Len.. Ioi sounu
io comc oui ol ihc scaIcis, ihc MIDI uaia has io lc scni ihiough somc Iinu ol
MIDI ucvicc ihai iaIcs ihc MIDI insiiuciions anu icnucis ihcm in sounu, ciihci
ly iiiggciing a haiuwaic insiiumcni oi a viiiual` insiiumcni soliwaic synihc-
sizci). In ihis looI, wc`ic using only soliwaic ucviccs, so hcic`s how ii woiIs in
]avaSounu:
Mzk|n] zr!ez| seen4
You need FOUR things:
8equencer
pIoys hos o
Midi
Event
Midi
Event
Midi
Event
8equence
Track
Midi
Event hoIds
The Sequencer is the thing
that actually causes a song
to be played. Think of it like
a music CD pIayer.
The Sequence is the
song, the musical piece
that the Sequencer will
play. Por this book, think
of the Sequence as a
music CD, but the whoIe
CD pIays just one song.
Por this book, we only
need one Track, so |ust
imagine a a music CD
with only one song. A
single Track. This Track
is where all the song
data (M|D| information)
lives.
1
The thing thut
pIuys the music
2
The music to be
pIuyed,,,u song,
3
The purt of the
Sequence thut
hoIds the uctuuI
informution
4
The uctuuI music
informution:
notes to pIuy
how Iong etc,
A M|D| event is a message
that the Sequencer can
understand. A M|D| event
might say (if it spoke
Lnglish), "At this moment
in time, play middle C, play
it this fast and this hard,
and hold it for this long. "
A M|D| event might
also say something like,
"Change the current
instrument to Plute.
|
-- l: --, l- - l- ----:- .: .
:-|-~
:-- c
l
|.: --|] --- 1
-.:` 1
-
----
.l-- .--l --
l- |.] l- :--
|-: -- l- 1
-.:, .- l- 1
-.: : .-l
- l- ----:-
JavaSound MIDI cIasses
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
341
And you need FVE steps:

Moke o new Sequence


3 0ef o new Truck from fhe Sequence
4 FiII fhe Trock wifh MidiEvents ond
give fhe Sequence fo fhe Sequencer
1 0ef o Sequencer ond open if
Sequencer player = MidiSystem.getSequencer();
player.open();
Sequence seq = new Sequence(timing,4);
Track t = seq.createTrack();
t.add(myMidiEvent1);
player.setSequence(seq);
Uh, hofe fo breok if
fo you, buf fhof's onIy
FOUP sfeps.
Ahhhh. We
forgof fo push fhe
PLAY buffon. You hove fo
sforf() fhe Sequencerl
player.start();
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
import javax.sound.midi.*;
public class MiniMiniMusicApp {

public static void main(String[] args) {
MiniMiniMusicApp mini = new MiniMiniMusicApp();
mini.play();
} // close main
public void play() {
try {
Sequencer player = MidiSystem.getSequencer();
player.open();

Sequence seq = new Sequence(Sequence.PPQ, 4);

Track track = seq.createTrack();

ShortMessage a = new ShortMessage();
a.setMessage(144, 1, 44, 100);
MidiEvent noteOn = new MidiEvent(a, 1);
track.add(noteOn);
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, 44, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);

player.setSequence(seq);

player.start();
} catch (Exception ex) {
ex.printStackTrace();
}
} // close play
} // close class
-l .
----:-- .-
--- l
|:- -
- :.- -:- l .
----:--

--:-'l :--
- .|--.
] ---`
l--'l ----] .--l l- .-----l: l- l-
----:- :--:l--:l-- )-:l :-] l-:- |l-
- '-- .: -.]~.- .-----l: `
A: l- ----:- -- . 1-.: ------, l- 1-.: |-: - l- ----:-, .- l- M|l| .l. |-: - l- 1-.:
|-l :--- M!--l: -l- l- 1-.: 1: .-l
: --:l|] -.]~.- :-- 1- --|] l- ]--'||
.- l- :.-- .--l .-- l- .-----l: l- l-
:-lM-::.-|` --l-, .- l- .-----l: l-
l- M!--l :--:l--:l-- w-'|| |-- .l l-:-
.-----l: -- l- --l .-
l.-l|` l- ----:-- ||- -:- ||A/`
l--'l ---l l- ---l l- - .:.-
Yeer vcry f|rs! seen4 p|zycr zpp
1
2
3
4
Tyc ii in anu iun ii. You`ll hcai ihc sounu ol somconc laying a
singlc noic on a iano! OK, maylc noi somc, lui somc.)
6- l- ----:- l- l- ----:-- ||-
-ll- l- cl - l- cl |.]--`
a sound appIication
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
exception handIing
343
ShortMessage a = new ShortMessage();
A MiuiEvcni is an insiiuciion loi aii ol a song. A sciics ol MiuiEvcnis is
Iinu ol liIc shcci music, oi a layci iano ioll. Mosi ol ihc MiuiEvcnis wc
caic aloui ucsciilc o thing to do anu ihc moment in time to do it. Thc momcni
in iimc aii maiicis, sincc iiming is cvciyihing in music. This noic lollows
ihis noic anu so on. Anu lccausc MiuiEvcnis aic so uciailcu, you havc io say
ai whai momcni io n. laying ihc noic a NOTE ON cvcni) anu ai whai
momcni io o laying ihc noics NOTE OII cvcni). So you can imaginc
ihai hiing ihc sio laying noic G" NOTE OII mcssagc) beo.e ihc siaii
laying Noic G" NOTE ON) mcssagc woulun`i woiI.
Thc MIDI insiiuciion aciually gocs inio a Mcssagc ol|cci, ihc MiuiEvcni is
a comlinaiion ol ihc Mcssagc lus ihc momcni in iimc whcn ihai mcssagc
shoulu hic`. In oihci woius, ihc Mcssagc mighi say, Siaii laying Miuulc
C" whilc ihc MiuiEvcni woulu say, Tiiggci ihis mcssagc ai lcai 4".
So wc always nccu a Mcssagc anu a MiuiEvcni.
Thc Mcssagc says wLn io uo, anu ihc MiuiEvcni says wLer io uo ii.
Mzk|n] z M|4|Ivcn! |sen] 4z!zI
1 Moke o Messuge

Puf fhe Instruction in fhe Messoge


a.setMessage(144, 1, 44, 100);
3 Moke o new MidiEvent using fhe Messoge
MidiEvent noteOn = new MidiEvent(a, 1);
4 Add fhe MidiEvenf fo fhe Truck
track.add(noteOn);
1: --::.- :.]:, :l.-l |.]- --l- ++'
|--'|| |-- .l l- -l-- -----: -- l-
--l .-`
1- -:l--:l--: .-- - l- --::.-, -l l- M~ !--l .: l- -----l - l-- --- l- -:l--:l--
:--| - l---- 1: M!--l :.]: l- l---
--::.- '.' .l l- -:l -.l |-.l |`
4 MidivenI sags
whaI Io do and
when Io do iI.
verg insIrucIion
musI inc|ude Ihe
Iiming !or IhaI
insIrucIion.
In oIher words, aI
which beaI IhaI
Ihing shou|d happen.
A 1-.: -|: .|| l- M!--l --:l: 1- ----:- --.---:
l-- .::--- l- --- -.: ---l : :--:- l- .--, .- l--
l- ----:-- |.]: l-- .: - l.l ---- /-- :.- .- |-l: -
---l: .--- .l l- -.:l :.-- -----l - l-- |-- -.-|-,
]-- -l -.-l l-- --l-: |.]- :--|l.----:|], -- --- ----l
-:l-----l: |.]- ----l :---: .l l- :.-- l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
A MIDI mcssagc holus ihc aii ol ihc cvcni ihai says wLn io uo. Thc aciual insiiuciion
you wani ihc scqucncci io cxccuic. Thc hisi aigumcni ol an insiiuciion is always ihc iyc
ol ihc mcssagc.Thc valucs you ass io ihc oihci ihicc aigumcnis uccnu on ihc iyc ol
mcssagc. Ioi cxamlc, a mcssagc ol iyc 144 mcans NOTE ON". Bui in oiuci io caiiy
oui a NOTE ON, ihc scqucncci nccus io Inow a lcw ihings. Imaginc ihc scqucncci saying,
OK, I`ll lay a noic, lui wL.L LnrreI. In oihci woius, uo you wani mc io lay a Dium
noic oi a Piano noic. Anu wL.L roe. Miuulc-C. D Shai. Anu whilc wc`ic ai ii, ai wL.L
.eIo., shoulu I lay ihc noic.
To maIc a MIDI mcssagc, maIc a ShoiiMcssagc insiancc anu invoIc sciMcssagc), assing
in ihc loui aigumcnis loi ihc mcssagc. Bui icmcmlci, ihc mcssagc says only wLn io uo, so
you siill nccu io siull ihc mcssagc inio an cvcni ihai auus wLer ihai mcssagc shoulu hic`.
M|P| mcssz]c: !hc hczr! ef z M|4|Ivcn!
a.setMessage(144, 1, 44, 100);
-
-
:
:
.

-

l
]

-
:

.
-
-
-
|
-
-
l
-

l
-

|
.
]

-
|
-
:

l
]
Anatomy of a message
I44 meons
MOTE OM
ChunneI
Think of o chonneI Iike o musicion in
o bond. ChonneI I is musicion I (fhe
keyboord pIoyer), chonneI 9 is fhe
drummer, efc.
VeIocity
How fosf ond hord did
you press fhe key7 0 is so soff you
probobIy won'f heor onyfhing, buf I00 is o
good defouIf.
IZ8 meons
MOTE OFF
1
|
o
i
?
+
-
|
7

|i
7
Note to pIuy
A number from 0 fo IZ7, going
from Iow fo high nofes.
1 Messuge type
2
3
4
:
l
.
-
l

|
.
]

:
l
-

|
.
]

contents of a Midi event


The frsf orgumenf fo sefMessoge() oIwoys
represenfs fhe messoge 'fype', whiIe fhe ofher
fhree orgumenfs represenf differenf fhings
depending on fhe messoge fype.
1- |.:l ? .-: .-] ---- -- l- --::.-
l]- 1: : . N61! 6N --::.-, :- l-
-l-- .-: .-- -- l-: l- ----:-- ---:
l- --- - ---- l- |.] . --l-
Thc Messoge says what to do, thc
MidiEvent says whcn to do it.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
345
b.setMessage(128, 1, 44, 100);
MidiEvent noteOff = new MidiEvent(b, );
Now ihai you Inow whai`s in a Miui mcssagc, you can siaii cxciimcniing. You
can changc ihc noic ihai`s laycu, how long ihc noic is hclu, auu moic noics,
anu cvcn changc ihc insiiumcni.
0hzn]c z mcssz]c
Chunge the note
Try o number befween 0 ond IZ7 in fhe nofe
on ond nofe off messoges.
1
a.setMessage(144, 1, , 100);
Chunge the durution of the note
Chonge fhe nofe off evenf (nof fhe messoge) so
fhof if hoppens of on eorIier or Iofer beof.
2
|
o
i
?
+
-
|
7

|i7
h rst.setMessage(, 1, , 0);
Chunge the instrument
Add o new messoge, 8EFOPE fhe nofe-pIoying messoge,
fhof sefs fhe insfrumenf in chonneI I fo somefhing ofher
fhon fhe defouIf piono. The chonge-insfrumenf messoge
is 'I9Z', ond fhe fhird orgumenf represenfs fhe ocfuoI
insfrumenf (fry o number befween 0 ond IZ7)
3
:

.
-

-
~

-
:
l
-
-
-
-
-
l

-
-
:
:
.

-

:

.
-
-
-
|

|

|
-
-
:

.
-

|
`
l
-

-
:
l
-
-
-
-
-
l

|
o
i
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
This vcision siill lays |usi a singlc noic, lui you gci io usc commanu-linc aigu-
mcnis io changc ihc insiiumcni anu noic. Exciimcni ly assing in iwo ini valucs
liom 0 io 127. Thc hisi ini scis ihc insiiumcni, ihc scconu ini scis ihc noic io lay.
Vcrs|en 2: 0s|n] remmzn4-||nc zr]s !e crpcr|mcn! w| !h seen4s
import javax.sound.midi.*;
public class MiniMusicCmdLine { // this is the hrst one

public static void main(String[] args) {
MiniMusicCmdLine mini = new MiniMusicCmdLine();
if (args.length < 2) {
System.out.println(Don't forget the instrument and note args);
} else {
int instrument = Integer.parseInt(args[0]);
int note = Integer.parseInt(args[1]);
mini.play(instrument, note);
}
} // close main
public void play(int instrument, int note) {
try {

Sequencer player = MidiSystem.getSequencer();
player.open();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();

MidiEvent event = null;
ShortMessage hrst = new ShortMessage();
hrst.setMessage(192, 1, instrument, 0);
MidiEvent changeInstrument = new MidiEvent(hrst, 1);
track.add(changeInstrument);
ShortMessage a = new ShortMessage();
a.setMessage(144, 1, note, 100);
MidiEvent noteOn = new MidiEvent(a, 1);
track.add(noteOn);
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, note, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
player.setSequence(seq);
player.start();
} catch (Exception ex) {ex.printStackTrace();}
} // close play
} // close class
change the instrument and note
File Edit Window Help Attenuate
%java MiniMusicCmdLine 102 30
%java MiniMusicCmdLine 80 20
%java MiniMusicCmdLine 40 70
-- l -l l-- -l .-: --- o
l- |i7 1-] l-:- -- :l.-l--:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
347
When we're done, we'II hove o working
8eof8ox fhof's oIso o Drum Chof CIienf.
We'II need fo Ieorn obouf 0UIs (incIud-
ing evenf hondIing), I/O, nefworking, ond
fhreods. The nexf fhree chopfers (IZ, I3,
ond I4) wiII gef us fhere.
Where we're headed with the rest
of the CodeKitchens
Andy: groove #2
6hr|s: groove2 rev|sed
N|ge|: dance beat
dance beat
Chapter 15: the goal
-.l --- -.l l-- -.l l--- -.l ---
This CodeIifchen Iefs us buiId o IiffIe
"music video" (bif of o sfrefch fo coII if
fhof...) fhof drows rondom recfongIes fo
fhe beof of fhe MIDI music. We'II Ieorn
how fo consfrucf ond pIoy o Iof of MIDI
evenfs (insfeod of jusf o coupIe, os we do
in fhe currenf chopfer).
Chapter 12: MD events
Mow we'II ocfuoIIy buiId fhe reoI 8eof8ox,
0UI ond oII. 8uf if's Iimifed-os soon os you
chonge o poffern, fhe previous one is Iosf.
There's no Sove ond Pesfore feofure, ond
if doesn'f communicofe wifh fhe nefwork.
(8uf you con sfiII use if fo work on your
drum poffern skiIIs.)
Chapter 13: 8tand-alone
BeatBox
You've mode fhe perfecf poffern, ond
now you con sove if fo o fIe, ond reIood if
when you wonf fo pIoy if ogoin. This gefs
us reody for fhe fnoI version (chopfer Ib),
where insfeod of wrifing fhe poffern fo o
fIe, we send if over o nefwork fo fhe chof
server.
Chapter 14: 8ave and
Restore
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
fs-s cs |s.ss

This chapter explored the wonderful world of


exceptions. our |ob is to decide whether each of the
following exception-related statements is true or false.
1. A iiy llocI musi lc lollowcu ly a caich nrJ a hnally llocI.
2. Il you wiiic a mcihou ihai mighi causc a comilci-chccIcu cxcciion, you
u wia ihai iisIy couc in a iiy / caich llocI.
S. Caich llocIs can lc olymoihic.
4. Only comilci chccIcu` cxcciions can lc caughi.
. Il you uchnc a iiy / caich llocI, a maiching hnally llocI is oiional.
6. Il you uchnc a iiy llocI, you can aii ii wiih a maiching caich oi hnally llocI,
oi loih.
7. Il you wiiic a mcihou ihai ucclaics ihai ii can ihiow a comilci-chccIcu cx-
cciion, you musi also wia ihc cxcciion ihiowing couc in a iiy / caich llocI.
S. Thc main ) mcihou in youi iogiam musi hanulc all unhanulcu cxcciions
ihiown io ii.
9. A singlc iiy llocI can havc many uillcicni caich llocIs.
10. A mcihou can only ihiow onc Iinu ol cxcciion.
11. A hnally llocI will iun icgaiulcss ol whcihci an cxcciion is ihiown.
12. A hnally llocI can cxisi wiihoui a iiy llocI.
1S. A iiy llocI can cxisi ly iiscll, wiihoui a caich llocI oi a hnally llocI.
14. Hanuling an cxcciion is somciimcs iclciicu io as uucIing`.
1. Thc oiuci ol caich llocIs ncvci maiicis.
16. A mcihou wiih a iiy llocI anu a hnally llocI, can oiionally ucclaic ihc
cxcciion.
17. Runiimc cxcciions musi lc LnrJIeJ oi JeIn.eJ.
exercise: True or FaIse
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
349
A working 1ava program is scrambled up on the fridge. Can you
reconstruct all the code snippets to make a working 1ava program
that produces the output listed belowI 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!
try {
public static void main{String args| {
String test = args0,
System.out.print{"o"|,
class MyEx extends Exception { }

public class ExTestDrive {
File Edit Window Help ThrowUp
% java ExTestDrive yes
thaws
% java ExTestDrive no
throws
if {"yes".equals{t|| {
CaJe Kagaets
System.out.print{"r"|,
System.out.print{"t"|,
static void doRisky{String t| throws MyEx {
System.out.print{"h"|,
} catch {MyEx e| {
System.out.print{"a"|,
System.out.print{"w"|,
System.out.println{"s"|,
doRisky{test|,
} nally {
throw new MyEx{|,

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
]||(iss ).c
ou know what to do!
Down
2. Currently usable
3. Template's creation
4. Don't show the kids
5. Mostly static AP| class
7. Not about behavior
9. The template
ll. Poll another one off
the line
Across
l. To give value
4. Plew off the top
6. All this and more!
8. Start
l0. The family tree
l3. No ducking
l5. Problem ob|ects
l8. One of 1ava's '49'
More Hints:
A c r o s s 2 0 . A l s o a t y p e o f c o l l e c t i o n
6 . A 1 a v a c h i l d 2 l . Q u a c k
8 . S t a r t a m e t h o d 2 7 . S t a r t s a p r o b l e m
l 3 . | n s t e a d o f d e c l a r e 2 8 . N o t A b s t r a c t
l 2 3
l2 ll l0
8 7
l5
4
24
27
5
6
l8
2l
l4
28
l7
9
l3
l6
l9
22
25
20
23
26
29
20. Class hierarchy
2l. Too hot to handle
24. Common primitive
25. Code recipe
27. Unruly method action
28. No Picasso here
29. Start a chain of events
l2. 1avac saw it coming
l4. Attempt risk
l6. Automatic acquisition
l7. Changing method
l9. Announce a duck
22. Deal with it
23. Create bad news
26. One of my roles
D o w n 9 . O n l y p u b l i c o r d e f a u l t
2 . O r a m o u t h w a s h l 6 . _ _ _ _ _ t h e f a m i l y f o r t u n e
3 . P o r _ _ _ _ _ _ ( n o t e x a m p l e ) l 7 . N o t a ' g e t t e r '
5 . N u m b e r s . . .
puzzIe: crossword
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
351
class MyEx extends Exception { }
public class ExTestDrive {
public static void main{String args| {
String test = args0,
try {
System.out.print{"t"|,
doRisky{test|,
System.out.print{"o"|,
} catch { MyEx e| {
System.out.print{"a"|,
} nally {
System.out.print{"w"|,
}
System.out.println{"s"|,
}
static void doRisky{String t| throws MyEx {
System.out.print{"h"|,
if {"yes".equals{t|| {
throw new MyEx{|,
}
System.out.print{"r"|,
}
} File Edit Window Help Chill
% java ExTestDrive yes
thaws
% java ExTestDrive no
throws
1. Ialsc, ciihci oi loih.
2. Ialsc, you can ucclaic ihc cxcciion.
S. Tiuc.
4. Ialsc, iuniimc cxcciion can lc caughi.
. Tiuc.
6. Tiuc, loih aic accciallc.
7. Ialsc, ihc ucclaiaiion is sulhcicni.
S. Ialsc, lui il ii uocsn`i ihc ]VM may shui
uown.
9. Tiuc.
10. Ialsc.
11. Tiuc. Ii`s olicn uscu io clcan-u aiiially
comlcicu iasIs.
12. Ialsc.
1S. Ialsc.
14. Ialsc, uucIing is synonomous wiih ucclai-
ing.
1. Ialsc, lioaucsi cxcciions musi lc caughi
ly ihc lasi caich llocIs.
16. Ialsc, il you uon`i havc a caich llocI, you
ucclaic.
17. Ialsc.
fs-s cs |s.ss
]e;ejze o|ajoz
CaJe Kagaets
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

chapter 11
A S S I 0 M M E M T
l 2 3
l2 ll l0
8 7
l5
4
24
27
5
6
l8
2l
l4
28
l7
9
l3
l6
l9
22
25
20
23
26
29
A S S I 0 M M E M T P O P P E D
M C M P
A O S U 8 C L A S S I M V O I E
T P T T V C
H I E P A P C H Y A H A M D L E L
M M H T T A
S C E T E X C E P T I O M S
T E C P M S
A S I E Y W O P D H
M E E E T P E E
T T D U C I C P T
I M T A A L 0 O P I T H M
A E I T A T P
T H P O W S C O M C P E T E O
E A H E M E W
]||(iss nsacis
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
this is a new chapter 353
12 getting gui
Face it, you need to make GUIs. |f you're building applications that other
people are going to use, you a graphical interface. |f you're building programs for yourself,
you a graphical interface. Lven if you believe that the rest of your natural life will be
spent writing server-side code, where the client user interface is a web page, sooner or later
you'll need to write tools, and you'll want a graphical interface. Sure, command-line apps are
retro, but not in a good way. They're weak, inflexible, and unfriendly. we'll spend two chapters
working on GU|s, and learn key 1ava language features along the way including vent
HandIing and Inner CIasses. |n this chapter, we'll put a button on the screen, and make it do
something when you click it. we'll paint on the screen, we'll display a |peg image, and we'll even
do some animation.
A Very Graphic
8tory
I heord your
ex-wife couId onIy cook
commond-Iine meoIs.
Wowl This Iooks greof.
I guess presenfofion
reoIIy is everyfhing.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
354 chapter 12
/-- --'l . l-: l- l- -.-- --:l|]1- - l- -.-- .: l- l-- .---- l- ----, .- ]-- . l-: l- l- ---- .--
f see one more
command-line app,
you're fired.
A ]Iiamc is ihc ol|cci ihai icicscnis
a winuow on ihc sciccn. Ii`s whcic you
ui all ihc inicilacc ihings liIc luiions,
chccIloxcs, icxi hclus, anu so on. Ii can
havc an honcsi-io-goouncss mcnu lai
wiih mcnu iicms. Anu ii has all ihc liiilc
winuowing icons loi whaicvci lailoim
you`ic on, loi minimizing, maximizing, anu
closing ihc winuow.
Thc ]Iiamc looIs uillcicni uccnuing on
ihc lailoim you`ic on. This is a ]Iiamc on
Mac OS X:
. )|
-.-
- -
l . -
--- .-
.- l-
- '-
-l:' |. -ll--
.- . -.- -ll--`
Making a GU is easy:
your first gui
|! z|| s!zr!s w| !h z w|n4ew
JFrame frame = new JFrame();
Oncc you havc a ]Iiamc, you can ui
ihings wiugcis`) in ii ly auuing ihcm
io ihc ]Iiamc. Thcic aic a ion ol Swing
comoncnis you can auu, looI loi ihcm
in ihc |avax.swing acIagc. Thc mosi
common incluuc ]Buiion, ]RauioBuiion,
]ChccIBox, ]Ialcl, ]Iisi, ]SciollPanc,
]Sliuci, ]TcxiAica, ]TcxiIiclu, anu
]Tallc. Mosi aic ically simlc io usc, lui
somc liIc ]Tallc) can lc a lii moic
comlicaicu.
|e! w|4]c!s |n !hc w|n4ew
Moke o frome (o JFrome)
JButton button = new JButton(click me);
frame.getContentPane().add(button);
1
Moke o widgef (buffon, fexf feId, efc.) 2
Add fhe widgef fo fhe frome 3
frame.setSize(300,300);
frame.setVisible(true);
DispIoy if (give if o si;e ond moke if visibIe) 4
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 355
import javax.swing.*;
public class SimpleGui1 {
public static void main (String[] args) {
JFrame frame = new JFrame();
JButton button = new JButton(click me);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);
frame.setSize(300,300);
frame.setVisible(true);
}
}
y[z[ [[z(', z
z]]y @jg @a((n.
The buffon fIIs oII fhe
ovoiIobIe spoce in fhe frome.
Lofer we'II Ieorn fo confroI
where (ond how big) fhe
buffon is on fhe frome.
Yeer f|rs! 00|: z |e!!en en z frzmc
--'l ---l l- ---l l:
:-- .:.-
|]-- :.- .:: l- -ll-- :--:l--:l--
l- l-l ]-- -.-l -- l- -ll--`
- l- -.-- . :--, - -|:
-.||], -.- l :|-'' | ]-- ---l l: :l-, ]-- ---'l :-- .-]l- --- ]-- --- l: :--`
. l- -ll-- l- l- -.--': :--l--l .--
Let's see what happens when we run it:
%ava SimpleGuil
-.- . -.-- .- . -ll--
l: |-- -.-: l- ---.- -l .: :--- .: ]--
:|-:- l- ---- | ]-- |-.- l: --l l -||
-:l :l l--- -- l- ::---- -----`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
356 chapter 12
Thai`s noi cxacily iiuc. Whcn you icss ihc luiion ii shows ihai
icsscu` oi ushcu in` looI which changcs uccnuing on ihc
lailoim looI anu lccl, lui ii always uocs oeL.r io show whcn
ii`s lcing icsscu).
Thc ical qucsiion is, How uo I gci ihc luiion io uo somcihing
sccihc whcn ihc usci clicIs ii."
Be! ne!h|n] hzppcns whcn | r||rk | !...
We need two things:
A method fo be coIIed when fhe user
cIicks (fhe fhing you wonf fo hoppen os
o resuIf of fhe buffon cIick).
1
A woy fo know when fo frigger
fhof mefhod. In ofher words, o woy
fo know when fhe user cIicks fhe
buffonl
2
When the user cIicks, we want
to know.
We're interested in the user-
takes-action-on-a-button event.
(-,- a,- |
oa|| qa--(:|-

WiII a button Iook Iike a
Windows button when you run on
Windows!
|f you want it to. ou can
choose from a few "look and
feelsclasses in the core library
that control what the interface looks
like. |n most cases you can choose
between at least two different looks:
the standard 1ava look and feel, also
known as Mernl and the native look
and feel for your platform. The Mac
OS X screens in this book use either
the OS X Aqun look and feel, or the
Mernl look and feel.

Can I make a program Iook
Iike Aqua aII the time! ven when
it's running under Windows!
Nope. Not all look and feels
are available on every platform. |f
you want to be safe, you can either
explicitly set the look and feel to
Metal, so that you know exactly what
you get regardless of where the app
is running, or don't specify a look
and feel and accept the defaults.

I heard Swing was dog-sIow
and that nobody uses it.
This was true in the past,
but isn't a given anymore. On weak
machines, you might feel the pain of
Swing. 8ut on the newer desktops,
and with 1ava version l.3 and be-
yond, you might not even notice the
difference between a Swing GU| and
a native GU|. Swing is used heavily
today, in all sorts of applications.
user interface events
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 357
Imaginc you wani ihc icxi on ihc luiion io
changc liom I.I e io I`.e beer I.IeJ whcn
ihc usci icsscs ihc luiion. Iiisi wc can wiiic a
mcihou ihai changcs ihc icxi ol ihc luiion a
quicI looI ihiough ihc API will show you ihc
mcihou):
0c!!|n] z escr cvcn!
public void changeIt() {
button.setText(I've been clicked!);
}
Bui row whai. How will wc Irow whcn ihis
mcihou shoulu iun. How wiII we hnow when the
button is cIiched
In ]ava, ihc ioccss ol gciiing anu hanuling a
usci cvcni is callcu e.er-LnrJI.r. Thcic aic
many uillcicni cvcni iycs in ]ava, alihough
mosi involvc GUI usci aciions. Il ihc usci clicIs
a luiion, ihai`s an cvcni. An cvcni ihai says
Thc usci wanis ihc aciion ol ihis luiion io
hacn." Il ii`s a Slow Tcmo" luiion, ihc usci
wanis ihc slow-icmo aciion io occui. Il ii`s a
Scnu luiion on a chai clicni, ihc usci wanis ihc
scnu-my-mcssagc aciion io hacn. So ihc mosi
siiaighiloiwaiu cvcni is whcn ihc usci clicIcu
ihc luiion, inuicaiing ihcy wani an aciion io
occui.
Wiih luiions, you usually uon`i caic aloui any
inicimcuiaic cvcnis liIc luiion-is-lcing-icsscu
anu luiion-is-lcing-iclcascu. Whai you wani io
say io ihc luiion is, I uon`i caic how ihc usci
lays wiih ihc luiion, how long ihcy holu ihc
mousc ovci ii, how many iimcs ihcy changc ihcii
minu anu ioll oll lcloic lciiing go, cic. ]ust teII
me when the user meons business: In oihci woius,
uon`i call mc unlcss ihc usci clicIs in a way ihai
inuicaics hc wanis ihc uain luiion io uo whai ii
says ii`ll uo!"
First, the button needs to know
that we care.
your code
b
u
f
f
o
n o
b
j
e
c
f

+-] -ll--, | :.-- .--l
-.l .--: l- ]--
1
2 1- -:-- :|:- --'
8econd, the button needs a way
to call us back when a button-
clicked event occurs.
l) How could you tell a button ob|ect that you
care about its eventsI That you're a concerned
listenerI
2) How will the button call you backI Assume
that there's no way for you to tell the button the
name of your unique method (change|t()). So
what else can we use to reassure the button that
we have a specific method it can call when the
event happensI |hint: think Pet|
WWkm
w&W

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
358 chapter 12
event Iisteners
A Iistener interfuce is fhe bridge befween fhe
Iistener (you) ond event source (fhe buffon).
<<interfece>>
K
eyListener
|eyPressed(KeyEverl ev) |eyRe|eased(KeyEverl ev)
|eyTyped(KeyEverl ev)
<<interfece>>
/tem
Listener
|ler3laleC|ared(llerEverl ev)
<
<
in
te
r
fe
c
e
>
>
A
c
tio
n
L
is
te
n
e
r
a
c
l|o
r
P
e
rlo
rr
e
d
(A
c
l|o
r
E
v
e
r
l e
v
)
Thc Swing GUI comoncnis aic cvcni souiccs. In ]ava icims,
an cvcni souicc is an ol|cci ihai can iuin usci aciions clicI
a mousc, iyc a Icy, closc a winuow) inio cvcnis. Anu liIc
viiiually cvciyihing clsc in ]ava, an cvcni is icicscnicu as an
ol|cci. An ol|cci ol somc cvcni class. Il you scan ihiough ihc
|ava.awi.cvcni acIagc in ihc API, you`ll scc a lunch ol cvcni
classcs casy io soi-ihcy all havc Event in ihc namc). You`ll
h nu MouscEvcni, KcyEvcni, WinuowEvcni, AciionEvcni, anu
scvcial oihcis.
An cvcni source liIc a luiion) cicaics an event object whcn ihc
usci uocs somcihing ihai maiicis liIc I.I ihc luiion). Mosi
ol ihc couc you wiiic anu all ihc couc in ihis looI) will .ee..e
cvcnis iaihci ihan .ene cvcnis. In oihci woius, you`ll scnu
mosi ol youi iimc as an cvcni I.ere. iaihci ihan an cvcni ou.e.
Evciy cvcni iyc has a maiching lisicnci inicilacc. Il you wani
MouscEvcnis, imlcmcni ihc MouscIisicnci inicilacc. Wani
WinuowEvcnis. Imlcmcni WinuowIisicnci. You gci ihc iuca.
Anu icmcmlci youi inicilacc iulcs-io imlcmcni an inicilacc
you JeIn.e ihai you imlcmcni ii class Dog imlcmcnis Pci),
which mcans you musi w..e .Ieern.or eLoJ loi cvciy
mcihou in ihc inicilacc.
Somc inicilaccs havc moic ihan onc mcihou lccausc ihc
cvcni iiscll comcs in uillcicni u avois. Il you imlcmcni
MouscIisicnci, loi cxamlc, you can gci cvcnis loi
mouscPicsscu, mouscRclcascu, mouscMovcu, cic. Each ol
ihosc mousc cvcnis has a scaiaic mcihou in ihc inicilacc,
cvcn ihough ihcy all iaIc a MouscEvcni. Il you imlcmcni
MouscIisicnci, ihc mouscPicsscu) mcihou is callcu whcn ihc
usci you gucsscu ii) icsscs ihc mousc. Anu whcn ihc usci lcis
go, ihc mouscRclcascu) mcihou is callcu. So loi mousc cvcnis,
ihcic`s only onc cvcni obe, MouscEvcni, lui scvcial uillcicni
cvcni eLoJ, icicscniing ihc uillcicni ,e ol mousc cvcnis.
If you care about the button's events,
implement an interface that says,
"I'm listening for your events."
y[n ya j]n( z
]j,(n jn(|ze, ya gjv
([ a((n z wzy ( ez]]
ya ze[. [[ jn(|ze j,
w[ ([ ez]]-ze[ ([]
j, ]e]z].
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 359
"8uffon, pIeose odd me fo
your Iisf of Iisfeners ond coII
my ocfionPerformed() mefhod
when fhe user cIicks you."
How the listener and source
communicate:
The I:steae:
The lveat Saa::e
|f your class wants to know about
a button's ActionLvents, you
implement the ActionListener
interface. The button needs to
know you're interested, so you
register with the button by calling its
addActionListener(this) and passing an
ActionListener reference to it (in this case,
you are the ActionListener so you pass
th|s).The button needs a way to call you
back when the event happens, so it calls
the method in the listener interface. As an
ActionListener, you must implement the
interface's sole method, actionPerformed().
The compiler guarantees it.
A button is a source of ActionLvents,
so it has to know which ob|ects are
interested listeners. The button has an
addActionListener() method to give
interested ob|ects (listeners) a way to
tell the button they're interested.
when the button's
addActionListener() runs (because
a potential listener invoked it), the
button takes the parameter (a
reference to the listener ob|ect) and
stores it in a list. when the user clicks
the button, the button 'res' the event
by calling the actionPerformed()
method on each listener in the list.
"OI, you're on AcfionLisfener,
so I know how fo coII you bock
when fhere's on evenf -- I'II coII
fhe ocfionPerformed() mefhod
fhof I know you hove."
o
c
fion
P
erformed(fh
e
E
v
e
n
f
)
b
u
f
f
o
n
.
o
d
d
A
cfionLisfener
(
f
h
i
s
)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
360 chapter 12
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui1B implements ActionListener {
JButton button;
public static void main (String[] args) {
SimpleGui1B gui = new SimpleGui1B();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
button = new JButton(click me);
button.addActionListener(this);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
button.setText(I've been clicked!);
}
}
|-
|--
--l l- -l--
.:- 1
: :.]:,
.- -:l.-:- -

-
|-6
-|B
|
~
A

A
:l--|
:l----'
|1
- -ll-- -
|| - ---l: --|] l-
A
:l--|
:l---- -
|--
--l--:`
--:l-- ]--- -l---:l -
l l- -ll-- 1
: :.]:
l- l- -ll--, A

-
- l- ]--- |:l -
|:l----:'
1
- .---
--l ]-- .:: M
c

1
- .- --:l
---
.
:|.:: l.l -
|--
--l: A
:l--|
:l----''
. --- ---l :l.l----l -- l- .:.- l.l
A:l--|:l---- .- A:l--!--l .-- -
|-|----l l- A:l--|:l---- -l--.:-':
.:l--|------|` --l- 1: : l-
.:l-.| ---l~.-|- --l-'
1- -ll-- :.||: l: --l- l- |-l ]-- --- .- ---l
.--- |l :--: ]-- .- A:l--!--l --:l .: l-
.-----l, -l -- --'l --- l r---- l- ---l .--- : ---- -- -- -:
2
3
1
ImpIemenf fhe AcfionLisfener inferfoce
1
Pegisfer wifh fhe buffon (feII if you
wonf fo Iisfen for evenfs)
2
Defne fhe evenf-hondIing mefhod (impIemenf
fhe ocfionPerformed() mefhod from fhe
AcfionLisfener inferrfoce)
3

Getting a button's ActionEvent
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 361
As on evenf source, my job is fo
uccept regisfrofions (from Iisfeners),
get evenfs from fhe user. ond
cuII fhe Iisfener's evenf-hondIing
mefhod (when fhe user cIicks me)
Ioi mosi ol youi sicllai ]ava caicci, ,ou will noi lc ihc ou.e
ol cvcnis.
No maiici how much you lancy youiscll ihc ccnici ol youi social
univcisc.)
Gci uscu io ii. Your job is to be o good Iistener.
Which, il you uo ii sinccicly, nr imiovc youi social lilc.)
I|s!cncrs, 8eerrcs, zn4 Ivcn!s
As o Iisfener, my job is fo
impIement fhe inferfoce,
register wifh fhe buffon, ond
provide fhe evenf-hondIing.
Listener GET8 the
event
8ource 8END8
the event
Event ob]ect
HOLD8 DATA
about the event
E
v
e
n
f o
b
j
e
c
f

Hey, whof obouf me7 I'm o pIoyer foo, you
knowl As on evenf objecf, I'm fhe urgument
fo fhe evenf coII-bock mefhod (from fhe
inferfoce) ond my job is fo curry dutu obouf
fhe evenf bock fo fhe Iisfener.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
362 chapter 12
(-,- a,- |
oa|| qa--(:|-

Why can't I be a source of events!

ou CAN. we |ust said that most of the time
you'll be the receiver and not the originator of the
event (at least in the eotly days of your brilliant 1ava
career). Most of the events you might care about
are 'fired' by classes in the 1ava AP|, and all you have
to do is be a listener for them. ou might, however,
design a program where you need a custom event, say,
StockMarketLvent thrown when your stock market
watcher app finds something it deems important. |n
that case, you'd make the Stockwatcher ob|ect be an
event source, and you'd do the same things a button
(or any other source) doesmake a listener interface
for your custom event, provide a registration method
(addStockListener()), and when somebody calls it, add
the caller (a listener) to the list of listeners. Then, when
a stock event happens, instantiate a StockLvent ob|ect
(another class you'll write) and send it to the listeners
in your list by calling their stockChanged(StockLvent
ev) method. And don't forget that for every event tye
there must be a motch|n l|stenet |ntetloce (so you'll
create a StockListener interface with a stockChanged()
method).

I don't see the importance of the event object
that's passed to the event caII-back methods. If
somebody caIIs my mousePressed method, what
other info wouId I need!
A lot of the time, for most designs, you don't
need the event ob|ect. |t's nothing more than a little
data carrier, to send along more info about the event.
8ut sometimes you might need to query the event for
specific details about the event. Por example, if your
mousePressed() method is called, you know the mouse
was pressed. 8ut what if you want to know exactly
where the mouse was pressedI |n other words, what if
you want to know the X and screen coordinates for
where the mouse was pressedI
Or sometimes you might want to register the some
listener with mult|le ob|ects. An onscreen calculator,
for example, has l0 numeric keys and since they all do
the same thing, you might not want to make a separate
listener for every single key. |nstead, you might
register a single listener with each of the l0 keys, and
when you get an event (because your event call-back
method is called) you can call a method on the event
ob|ect to find out who the real event source was. |n
other words, wh|ch ley sent th|s event.
+,-+ :+ ,-+:.|
windowClosing()
actionPerformed()
itemStateChanged()
mousePressed()
keyTyped()
mouseExited()
focusGained()
check box
text feld
scrolling list
button
dialog box
radio button
menu item
Widgets Event methods
Lach of these widgets (user interface ob|ects) are the
source of one or more events. Match the widgets with
the events they might cause. Some widgets might be a
source of more than one event, and some events can be
generated by more than one widget.
qw ] ya [0y j|
zn je( j, zn vn(
,ae/
Look in the AP.
0[. j[ | w[z(/
A method that starts with
add', ends with Listener',
and takes a listener inter-
face argument. f you see:
addKeyL|stener(KeyL|stener k}
you know that a class
with this method is a
source of KeyEvents.
There's a naming pattern.
event handIing
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
getting gui
you are here 363
Now ihai wc Inow a liiilc aloui how cvcnis woiI wc`ll lcain
moic laici), lci`s gci lacI io uiiing siull on ihc sciccn.
Wc`ll scnu a lcw minuics laying wiih somc lun ways io gci
giahic, lcloic iciuining io cvcni hanuling.
0c!!|n] |zrk !e ]rzph|rs...
Three ways to put things on your GU:
Put widgets on u frume
Add buffons, menus, rodio buffons, efc.
frame.getContentPane().add(myButton);
The jovox.swing pockoge hos more fhon o do;en
widgef fypes.
1
Put u JPES on u widget
You con puf your own imoges on o widgef.
graphics.drawImage(myPic,10,10,this);
3
Druw ZD gruphics on u widget
Use o grophics objecf fo poinf shopes.
graphics.llOval(70,70,100,100);
You con poinf o Iof more fhon boxes ond circIes,
fhe JovoZD API is fuII of fun, sophisficofed
grophics mefhods.
2
Number of Head
First Java books
mistakenly
bought by coffee
house baristas.
.
-l
, .
-
-:, :-
-|.
l
-
-:, -l
:
:.-l:,
-:--::
-.::,
-l:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
364 chapter 12
Il you wani io ui youi own giahics on ihc sciccn, youi lcsi
lci is io maIc youi own ainiallc wiugci. You lo ihai wiugci
on ihc liamc, |usi liIc a luiion oi any oihci wiugci, lui whcn ii
shows u ii will havc youi imagcs on ii. You can cvcn maIc ihosc
imagcs movc, in an animaiion, oi maIc ihc colois on ihc sciccn
changc cvciy iimc you clicI a luiion.
Ii`s a iccc ol caIc.
Make a subclass of JPanel and override one
method, paintComponent{}.
All ol youi giahics couc gocs insiuc ihc ainiComoncni)
mcihou. ThinI ol ihc ainiComoncni) mcihou as ihc mcihou
callcu ly ihc sysicm io say, Hcy wiugci, iimc io aini youiscll."
Il you wani io uiaw a ciiclc, ihc ainiComoncni) mcihou will
havc couc loi uiawing a ciiclc. Whcn ihc liamc holuing youi
uiawing ancl is uislaycu, ainiComoncni) is callcu anu youi
ciiclc acais. Il ihc usci iconihcs/minimizcs ihc winuow, ihc
]VM Inows ihc liamc nccus icaii" whcn ii gcis uc-iconihcu,
so ii calls ainiComoncni) again. Anyiimc ihc ]VM ihinIs ihc
uislay nccus iclicshing, youi ainiComoncni) mcihou will lc
callcu.
Onc moic ihing, you never coII this method yourseI[: Thc aigumcni
io ihis mcihou a Giahics ol|cci) is ihc aciual uiawing canvas
ihai gcis slacu onio ihc uislay. You can`i gci ihis ly
youiscll, ii musi lc hanucu io you ly ihc sysicm. You`ll scc
laici, howcvci, ihai you asI ihc sysicm io iclicsh ihc uislay
icaini)), which uliimaicly lcaus io ainiComoncni) lcing
callcu.
Mzkc yeer ewn 4rzw|n] w|4]c!
making a drawing paneI
import java.awt.*;
import javax.swing.*;
class MyDrawPanel extends JPanel {

public void paintComponent(Graphics g) {
g.setColor(Color.orange);
g.llRect(20,50,100,100);
}
}
]
-- ---

-l

-
l

-:-
M
.- . :-:|.:: - )|.--|, . --l
l.l ]-- :.- . l- . -.-- -:l |-
.-]l- -|:- !:-l l: --- : ]---
--- :-:l---- --l
1: : l- B |---l.-l 6-.:: --l-
/-- -|| N!/! :.|| l: ]---:-| 1-
:]:l-- :.||: l .- :.]:, +---': . -:-
--: -.-- :--.:-, - l]- 6-.::,
l.l ]-- -.] .-l -- ---'
|-.-- l.l '' : . .-l- -.:-- /--'--
l-||- l -.l :-|-- l- .-l -l .- l--
-.l :.- l- .-l |-l :----.l-: --
---- l --: .- -- l :`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 365
Ici`s looI ai a lcw moic ihings you can uo in ainiComoncni).
Thc mosi lun, ihough, is whcn you siaii cxciimcniing youiscll.
Tiy laying wiih ihc numlcis, anu chccI ihc API loi class
Giahics laici wc`ll scc ihai ihcic`s cvcn you can uo lcsiucs
whai`s in ihc Giahics class).
Ien !h|n]s !e 4e |n pz|n!0empencn!|I
public void paintComponent(Graphics g) {
Image image = new ImageIcon(catzilla.jpg).getImage();
g.drawImage(image,3,4,this);

}
public void paintComponent(Graphics g) {

g.llRect(0,0,this.getWidth(), this.getHeight());

int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color randomColor = new Color(red, green, blue);
g.setColor(randomColor);
g.llOval(70,70,100,100);
}

|| l- --l-- .--| -
l |.:
|l-
-
.-|l :-|--`
1- -:l l-- .-: --- l- |,]` --- |-l
:-----, --|.l- l- l- .--|, -- ---- -.--
:l.-l:, :- o, o --.-: :l.-l o -|: --- l-
|-l -- .- o -|: --- l- l- --' 1-
-l-- l-- .-: :.], M.- l- -l - l:
--:l.-|- .: -- .: l- .--| |l:-l|``, .-
-.- l- -l .: l.|| .: l- .--| |l:-l`'
]---
|- -.-
- --: ---
1- ,] :----.l-: -- ---- l- :l---': l-
|-l :----- :--| - 1: :.]: ? -|: ---
l- |-l -- - l- .--| .- + -|: --- l-
l- -- - l- .--|' 1-:- -----: .-- .|-.]:
--|.l- l- l- --l |- l: :.:- ]--- )|.--|
:-:|.::`, --l l- --l-- -.--
:l.-l 7o -|: --- l- |-l, 7o ---
l- l-, -.- l |oo -|: --, .-
|oo -|: l.||
/-- :.- -.- . :-|-- ] .::- - ? -l:
l- ----:--l l- 6B .|--:
Display a JPEG
Paint a randomly-colored circle
on a black background
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
366 chapter 12
Thc aigumcni io ainiComoncni) is ucclaicu as iyc
Giahics |ava.awi.Giahics).
Bch|n4 cvcry ]ee4 0rzph|rs rcfcrcnrc
|s z 0rzph|rs2P e|jcr!.
drawing gradients with Graphics2D
public void paintComponent(Graphics g) { } Methods you can call on a
Graphics reference:
drawmage()
drawLine()
drawPolygon
drawRect()
drawOval()
fllRect()
fllRoundRect()
setColor()
So ihc aiamcici g` IS-A Giahics ol|cci. Which mcans ii
ouIJ lc a ubIn ol Giahics lccausc ol olymoihism).
Anu in laci, ii ..
The object re[erenced by the g` porometer is octuoIIy on
instonce o[ the Graphics2D cIoss.
Why uo you caic. Bccausc ihcic aic ihings you can uo wiih
a Giahics2D iclcicncc ihai you can`i uo wiih a Giahics
iclcicncc. A Giahics2D ol|cci can uo moic ihan a Giahics
ol|cci, anu ii ically is a Giahics2D ol|cci luiIing lchinu ihc
Giahics iclcicncc.
Rcmcmlci youi olymoihism. Thc comilci ucciucs which
mcihous you can call lascu on ihc iclcicncc iyc, noi ihc
ol|cci iyc. Il you havc a Dog ol|cci iclcicnccu ly an Animal
iclcicncc vaiiallc:
Animal a = new Dog();
You can NOT say:
a.bark();
Evcn ihough you Inow ii`s ically a Dog lacI ihcic. Thc
comilci looIs ai a`, sccs ihai ii`s ol iyc Animal, anu hnus
ihai ihcic`s no icmoic coniiol luiion loi laiI) in ihc Animal
class. Bui you can siill gci ihc ol|cci lacI io ihc Dog ii ically .
ly saying:
Dog d = (Dog) a;
d.bark();
So ihc loiiom linc wiih ihc Giahics ol|cci is ihis:
II you nccd to usc a mcthod Irom thc Graphics2D class, you
can't use thc thc paintComponcnt paramctcr ('g') straight
Irom thc mcthod. But you can cost it with a ncw Graphics2D
variablc.
Graphics2D g2d = (Graphics2D) g;
Methods you can call on
a Graphics2D reference:
fll3DRect()
draw3DRect()
rotate()
scale()
shear()
transform()
setRenderingHints()
|l-:- .-- --l :--|-l- --l- |:l:,
:-: l- A|| -- ----`
To cast the Graphics2D ob]ect to
a Graphics2D reference:
Graphics2D g2d = (Graphics2D) g;
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 367
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
GradientPaint gradient = new GradientPaint(70,70,Color.blue, 150,150, Color.orange);

g2d.setPaint(gradient);
g2d. llOval(70,70,100,100);
}
Bcrzesc ||fcs !ee sher! !e pz|n! !hc
r|rr|c z se||4 re|er whcn !hcrcs z
]rz4|cn! ||cn4 wz| !|n] fer yee.
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;

int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color startColor = new Color(red, green, blue);
red = (int) (Math.random() * 255);
green = (int) (Math.random() * 255);
blue = (int) (Math.random() * 255);
Color endColor = new Color(red, green, blue);
GradientPaint gradient = new GradientPaint(70,70,startColor, 150,150, endColor);
g2d.setPaint(gradient);
g2d. llOval(70,70,100,100);
}
l': --.||] . 6-.::il
--:l
-.:---.- .: . ---- 6-.::
--:l
:.:l l :- -- :.- :.|| :---l- l.l
6-.::il .: -l 6-.:: --:-'l
l: :-l: l- -l-.| .-l --: l- . -.--l -:l-. - . :-| :-|--
:l
.
-
l
-


-
-
l
:l
.
-
l
-

:
-
|-
-
-
-


-
-
l
-
-

:
-
|-
-
l- ||6.||` --l- --.||] --.-: ||
l- -.| -l -.l--- : |-.- -- ]---
.-l--: |- l- -.--l`'
l: : -:l |- l- --- .--,
-:-l l -.-: -.--- :-|--: --
l- :l.-l .- :l- :-|--: - l-
-.--l 1
-] l'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
368 chapter 12
events and graphics
To ra|e a 0ul, slarl W|l| a W|rdoW, usua||y a JFrare
JFrame frame = new JFrame();
You car add W|dels (oullors, lexl l|e|ds, elc.) lo l|e
JFrare us|r:
frame.getContentPane().add(button);
ur|||e rosl ol|er corporerls, l|e JFrare doesr'l |el
you add lo |l d|recl|y, so you rusl add lo l|e JFrare's
corlerl pare.
To ra|e l|e W|rdoW (JFrare) d|sp|ay, you rusl |ve |l
a s|ze ard le|| |l oe v|s|o|e:
frame.setSize(300,300);
frame.setVisible(true);
To |roW W|er l|e user c||c|s a oullor (or la|es sore
ol|er acl|or or l|e user |rlerlace) you reed lo ||sler lor
a 0ul everl.
To ||sler lor ar everl, you rusl re|sler your |rleresl
W|l| ar everl source. Ar everl source |s l|e l||r (oul-
lor, c|ec|oox, elc.) l|al 'l|res' ar everl oased or user
|rleracl|or.
T|e ||slerer |rlerlace |ves l|e everl source a Way
lo ca|| you oac|, oecause l|e |rlerlace del|res l|e
rel|od(s) l|e everl source W||| ca|| W|er ar everl
|appers.
To re|sler lor everls W|l| a source, ca|| l|e source's
re|slral|or rel|od. Re|slral|or rel|ods a|Ways la|e
l|e lorr ol: edd<Event7ye>Listener. To re|sler lor a
oullor's Acl|orEverls, lor exarp|e, ca||:
button.addActionListener(this);
lrp|ererl l|e ||slerer |rlerlace oy |rp|ererl|r a|| ol
l|e |rlerlace's everl-|ard||r rel|ods. Pul your everl-
|ard||r code |r l|e ||slerer ca||-oac| rel|od. For
Acl|orEverls, l|e rel|od |s:
public void actionPerformed(ActionEvent
event) {
button.setText(you clicked!);
}
T|e everl oojecl passed |rlo l|e everl-|ard|er rel|od
carr|es |rlorral|or aooul l|e everl, |rc|ud|r l|e source
ol l|e everl.
8ll P0lk5
6kkPkl65
You car draW 20 rap||cs d|recl|y or lo a W|del.
You car draW a .|l or .jpe d|recl|y or lo a W|del.
To draW your oWr rap||cs (|rc|ud|r a .|l or .jpe),
ra|e a suoc|ass ol JPare| ard overr|de l|e pa|rlCor-
porerl() rel|od.
T|e pa|rlCorporerl() rel|od |s ca||ed oy l|e 0ul
sysler. Y0u NEvER CALL lT Y0uR3ELF. T|e aru-
rerl lo pa|rlCorporerl() |s a 0rap||cs oojecl l|al
|ves you a surlace lo draW or, W||c| W||| erd up or
l|e screer. You carrol corslrucl l|al oojecl yourse|l.
Typ|ca| rel|ods lo ca|| or a 0rap||cs oojecl (l|e pa|rl-
Corporerl pararerler) are:
graphics.setColor(Color.blue);
g.llRect(20,50,100,120);
To draW a .jp, corslrucl ar lrae us|r:
Image image = new ImageIcon(catzilla.
jpg).getImage();
ard draW l|e |ra|re us|r:
g.drawImage(image,3,4,this);
T|e oojecl relererced oy l|e 0rap||cs parareler
lo pa|rlCorporerl() |s aclua||y ar |rslarce ol l|e
0rap||cs20 c|ass. T|e 0rap||cs 20 c|ass |as a var|ely
ol rel|ods |rc|ud|r:
fll3DRect(), draw3DRect(), rotate(), scale(), shear(),
transform()
To |rvo|e l|e 0rap||cs20 rel|ods, you rusl casl l|e
parareler lror a 0rap||cs oojecl lo a 0rap||cs20
oojecl:
Graphics2D g2d = (Graphics2D) g;
k5
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 369
Ici`s hooI u an cvcni io a changc in oui uiawing ancl. Wc`ll maIc ihc ciiclc
changc colois cach iimc you clicI ihc luiion. Hcic`s how ihc iogiam uows:
Wc rzn ]c! zn cvcn!.
Wc rzn pz|n! ]rzph|rs.
Be! rzn wc pz|n! ]rzph|rs whcn wc ]c! zn cvcn!!

VoiIol A new coIor is poinfed becouse


poinfComponenf() runs ogoin, fIIing fhe
circIe wifh o rondom coIor.
The frome is buiIf wifh fhe fwo widgefs
(your drowing poneI ond o buffon). A
Iisfener is creofed ond regisfered wifh
fhe buffon. Then fhe frome is dispIoyed
ond if jusf woifs for fhe user fo cIick.
Sforf fhe opp
The user cIicks fhe buffon ond fhe
buffon creofes on evenf objecf ond
coIIs fhe Iisfener's evenf hondIer.

The evenf hondIer coIIs repoinf() on fhe


frome. The sysfem coIIs poinfComponenf()
on fhe drowing poneI.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
370 chapter 12
buiIding a GUI frame
Woif o minufe...how
do you puf TWO
fhings on o frome7
Wc covci GUI layouis in ihc chaici, lui wc`ll uo a
quicIic lcsson hcic io gci you going. By uclauli, a liamc
has hvc icgions you can auu io. You can auu only ihing
io cach icgion ol a liamc, lui uon`i anic! Thai onc ihing
mighi lc a ancl ihai holus ihicc oihci ihings incluuing a
ancl ihai holus iwo moic ihings anu... you gci ihc iuca. In
laci, wc wcic chcaiing` whcn wc auucu a luiion io ihc liamc
using:
00| |zyee!s: pe!!|n] merc !hzn enc
w|4]c! en z frzmc
frame.getContentPane().add(button);
1
: :-'l --.||] l- -.] ]--'-- :--:-
l- - l |l- ---~.- . --l-`
frame.getContentPane().add(BorderLayout.CENTER, button);
1: : l- -ll-- |.- -:-.||]
-.-.l--]` -.] l- . l- . -.--':
-.-|l :--l--l .-- A|-.]: :-:]
w
+!! |-: ----` ]-- -.-l l-
--l l- -
w
-- ]-- :.|| l- :-|-~.- .
--l- |l- --- -- :--|-'l -:-`
l- --l -|| .-l--.l:.||] |.- -
l- :--l-- --:--
-- :.|| l- l--~.-----l . --l-,
l.l l.-: . ---- |-:- . :--:l.-l` .- l- --l l- . l- l.l ----
+,-+ :+ ,-+:.|
Given the pictures on page 351, write the
code that adds the button and the panel to
the frame.
-.-|l ----
---l
:--l
-.:l
--:l
:--l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 371
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleGui3C implements ActionListener {
JFrame frame;
public static void main (String[] args) {
SimpleGui3C gui = new SimpleGui3C();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton(Change colors);
button.addActionListener(this);

MyDrawPanel drawPanel = new MyDrawPanel();

frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
}
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
// Code to ll the oval with a random color
// See page 347 for the code
}
}
The circle changes color each time you
click the button.
B-ll-- : - l-
6c1
+ ---- -
l- -.--
1
- :-:l-- -.-- .--|
|-:l.-:- - M
]l
-.-|.--|`
: - l- c!N1
! ----
- l- -.--
A l- |:l---- |l:`
l- l- -ll--
A l- l-- --l: |-l~
l-- .- -.-- .--|` l-
l- l-- ----: - l-
-.--
w-- l- -:-- :|::, l-|| l- -.--
l- --.-l|` l:-| 1.l --.-:
.-lc------l|` : :.||- -- ---]
--l - l- -.--'
1- -.-- .--|': .-lc------l|`
--l- : :.||- ---] l-- l- -:--
:|::
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
372 chapter 12
-.:l
Thc souih luiion will aci as ii uocs now, simly calling icaini on ihc
liamc. Thc scconu luiion which wc`ll siicI in ihc casi icgion) will
changc ihc icxi on a lalcl. A lalcl is |usi icxi on ihc sciccn.)
Ic!s !ry | ! w| !h IW0 |e!!ens
muItipIe Iisteners
8e new wc ncc4 I00K w|4]c!s
:-|--~:.--
-ll-- -|| - ---
|.-| -||
- ---
-.-- .--| --:
- l- :--l--
|.

-
|~
:

.
-

-
l
l
-
-
-
||
-

-
-
-
---l
:--l
--:l
:--l--
Uh-oh.
Is ihai cvcn ossillc. How uo
you gci cvcnis whcn you
havc only aciionPciloimcu)
mcihou.
n4 wc ncc4 !e ]c!
IW0 cvcn!s
1: -ll-- :.--: l- l-l
-- l- --:l- :-
1: -ll-- :.--: l- :-|--
- l- :-:|-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
getting gui
you are here 373
Hew 4e yee ]c! zr!|en cvcn!s fer ! we 4|ffcrcn! |e!!ens,
whcn czrh |e!!en ncc4s !e 4e semc!h|n] 4|ffcrcn!!
1 option one
mplement two actionPerformed{} methods
Flaw: You can'tl ou can't implement the same method twice in a 1ava class. |t won't compile.
And even if you coulJ, how would the event source know wh|ch of the two methods to callI
class MyGui implements ActionListener {
// lots of code here and then:
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
public void actionPerformed(ActionEvent event) {
label.setText(That hurt!);
}
}
2
option two
Register the same listener with both buttons.
Flaw: this does work, but in most cases it's not very OO. One event handler
doing many different things means that you have a single method doing many different things.
|f you need to change how one source is handled, you have to mess with evetyooJys event
handler. Sometimes it |s a good solution, but usually it hurts maintainability and extensibility.
-:l-- l- :.-- |:l----
-l -l -ll--:
class MyGui implements ActionListener {
// declare a bunch of instance variables here
public void go() {
// build gui
colorButton = new JButton();
labelButton = new JButton();
colorButton.addActionListener(this);
labelButton.addActionListener(this);
// more gui code here ...
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == colorButton) {
frame.repaint();
} else {
label.setText(That hurt!);
}
}
}
6---] l- ---l --:l
l- - --l -: -ll--
.:l-.||] -- l, .- -:-
l.l l- -:- -.l l- -
B-l l: : --::|-'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
374 chapter 12
3
option three
Create two separate ActionListener classes
Flaw: these classes won't have access to the variables they need
to act on, frame' and label'. ou could x it, but you'd have to give each of the
listener classes a reference to the main GU| class, so that inside the actionPerformed()
methods the listener could use the GU| class reference to access the variables of the GU|
class. 8ut that's breaking encapsulation, so we'd probably need to make getter methods
for the gui widgets (getPrame(), getLabel(), etc.). And you'd probably need to add a
constructor to the listener class so that you can pass the GU| reference to the listener at
the time the listener is instantiated. And, well, it gets messier and more complicated.
7here hns ger re be n berrer wnyl
class MyGui {
JFrame frame;
JLabel label;
void gui() {
// code to instantiate the two listeners and register one
// with the color button and the other with the label button
}
} // close class
class ColorButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
}
class LabelButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
label.setText(That hurt!);
}
}
|--|--' 1: :|.:: .: -- ------:- l- l- .-.|- '|.-|'
w--'l ---' 1: :|.:: --:-'l .- . ------:- l-
l- '-.--' .-.|- - l- M]6- :|.::
muItipIe Iisteners
Hew 4e yee ]c! zr!|en cvcn!s fer ! we 4|ffcrcn! |e!!ens,
whcn czrh |e!!en ncc4s !e 4e semc!h|n] 4|ffcrcn!!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 375
WouIdn'f if be wonderfuI if you
couId hove fwo differenf Iisfener cIosses,
buf fhe Iisfener cIosses couId occess fhe
insfonce voriobIes of fhe moin 0UI cIoss,
oImosf os if fhe Iisfener cIosses beIonged
fo fhe ofher cIoss. Then you'd hove fhe besf
of bofh worIds. Yeoh, fhof wouId be dreomy.
8uf if's jusf o fonfosy...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
376 chapter 12
You nr havc onc class ncsicu insiuc anoihci. Ii`s casy.
]usi maIc suic ihai ihc uchniiion loi ihc innci class is
.r.Je ihc cuily liaccs ol ihc ouici class.
|nncr r|zss !e !hc rcsrec|
class MyOuterClass {

class MyInnerClass {
void go() {
}
}
}
8imple inner class:
class MyOuterClass {
private int x;

class MyInnerClass {
void go() {
x = 42;
}
} // close inner class
} // close outer class
-:- '' .: l ---- . .-.|-
- l- ---- :|.::'
nner class using an outer class variable
An innci class gcis a sccial ass io usc ihc ouici class`s siull. E.er
Le ...ne u. Anu ihc innci class can usc ihosc iivaic vaiiallcs
anu mcihous ol ihc ouici class as il ihc vaiiallcs anu mcmlcis
wcic uchncu in ihc innci class. Thai`s whai`s so hanuy aloui innci
classcs-ihcy havc mosi ol ihc lcnchis ol a noimal class, lui wiih
sccial acccss iighis.
Aa :aae: :|ass :aa
ase a|| the ethaJs
aaJ va::al|es aI the
aate: :|ass, evea the
::vate aaes.
The :aae: :|ass gets
ta ase thase va::al|es
aaJ ethaJs ast
as :I the ethaJs
aaJ va::al|es ve:e
Je:|a:eJ v:th:a the
:aae: :|ass.
inner cIasses
|---- :|.:: :
-||]
--:|-:-
] --l-- :|.::
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 377
M
y
I
n
ner o
b
j
e
c
f

Rcmcmlci, whcn wc ialI aloui an innci In acccssing
somcihing in ihc ouici class, wc`ic ically ialIing aloui an
.rnre ol ihc innci class acccssing somcihing in an .rnre ol
ihc ouici class. Bui wL.L insiancc.
Can nr, ailiiiaiy insiancc ol ihc innci class acccss ihc mcihous
anu vaiiallcs ol nr, insiancc ol ihc ouici class.
Ar obe u be .eJ o n e. obe or
Le Len.
n |nncr r|zss |ns!znrc mes! |c !|c4 !e
zn ee!cr r|zss |ns!znrc'.
C
c
l
l
|
n
g

|
n

l
c
u
c
h

w
|
l
h

q
c
u
r

|
n
n
c
r

c
l
a
-
-
O
v
e
r 6
5
,5
3
6
c
o
p
/e
s
s
o
/d
/
T
h
e
n
e
w
b
e
s
ts
e
lle
r fro
m
th
e

a
u
th
o
r o
f '
W
h
o
M
o
v
e
d
m
y
C
h
a
r?
"

0
r
. P
e
ly
M
e
r
p
h
is
m
1
M
y
O
u
fer
o
b
j
e
c
f

Moke on insfonce of
fhe oufer cIoss
2
Moke on insfonce of
fhe inner cIoss, by
using fhe insfonce
of fhe oufer cIoss.
inne
r

The oufer ond inner objecfs


ore now infimofeIy Iinked.
ou
f
e
r
1-:- l-- --:l: -- l- -.
.- . :-:.| -- 1- ----
:.- -:- l- --l--': .-.|-:
|.- :-~--:.`
An inner ob]ect
shares a special
bond with an
outer ob]ect.
-l
l-- :
*There's an exception to this, for a very special casean inner class defned
within a static method. But we're not going there, and you might go your entire
Java life without ever encountering one of these.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
378 chapter 12
class MyOuter {
private int x;
MyInner inner = new MyInner();
public void doStuff() {
inner.go();
}

class MyInner {
void go() {
x = 42;
}
} // close inner class
} // close outer class
1- --l-- :|.:: .: . -.l-
-:l.-:- .-.|- ''
M.- .- -:l.-:- - l-
---- :|.::
1- --l- - l- ---- :|.:: -:-: l-
--l-- :|.:: -:l.-:- .-.|- '', .: ''
-|--- l- l- ---- :|.::
Il you insianiiaic an innci class liom couc an ouici class, ihc insiancc
ol ihc ouici class is ihc onc ihai ihc innci ol|cci will lonu` wiih. Ioi
cxamlc, il couc wiihin a mcihou insianiiaics ihc innci class, ihc innci
ol|cci will lonu io ihc insiancc whosc mcihou is iunning.
Couc in an ouici class can insianiiaic onc ol iis own innci classcs, in cxacily
ihc samc way ii insianiiaics any oihci class... new MyInner()
Hew !e mzkc zn |ns!znrc ef zn |nncr r|zss
MyOufer

MyInner

inf
x
MyOufer

inf
x
:-:.|
--
ou con instantiate an inner instance from code running outs|Je the outer class, but you
have to use a special syntax. Chances are you'll go through your entire 1ava life and never
need to make an inner class from outside, but |ust in case you're interested...
class Foo {
public static void main (String[] args) {
MyOuter outerObj = new MyOuter();
MyOuter.MyInner innerObj = outerObj.new MyInner();
}
}
inner cIass instances

:.|| . --l- -- l-
---- :|.::
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 379
public class TwoButtons {
JFrame frame;
JLabel label;
public static void main (String[] args) {
TwoButtons gui = new TwoButtons ();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton labelButton = new JButton(Change Label);
labelButton.addActionListener(new LabelListener());
JButton colorButton = new JButton(Change Circle);
colorButton.addActionListener(new ColorListener());
label = new JLabel(I'm a label);
MyDrawPanel drawPanel = new MyDrawPanel();

frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.getContentPane().add(BorderLayout.EAST, labelButton);
frame.getContentPane().add(BorderLayout.WEST, label);
frame.setSize(300,300);
frame.setVisible(true);
}

class LabelListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
label.setText(Ouch!);
}
} // close inner class
class ColorListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
} // close inner class

}
l- -.- 6c| :|.:: --:-'l
-|----l A:l--|:l---- ---
-:l-. - .::- |l:` l- l-
-ll--': |:l---- --:l-.l--
--l-, .:: . --- -:l.-:- -
l- .---.l- |:l---- :|.::
N-- -- -l l- .-
1w6 A:l--|:l----:
- . :-|- :|.:: '
l- ---- :|.:: -l: l- -:- l- '-.--'
-:l.-:- .-.|-, -l--l .- .-
-|:l ------:- l- l- --l-- :|.::
--:l
---- :|.:: ---:
.--l '|.-|'
Now we can get the two-button
code working
Two8uffons
objecf
CoIorLisfener
objecf
LobeILisfener
objecf
-
-l
--
-
-
--
-
-
--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
380 chapter 12
inner cIasses
HeadFirst: What makes inner classes important?
Inner object: Where oo I start? We give you a chance to
implement the same interlace more than once in a class.
Remember, you can`t implement a methoo more than
once in a normal Java class. But using ioo.r classes, each
inner class can implement the oo. interlace, so you can
have all these oiff.r.ot implementations ol the very same
interlace methoos.
HeadFirst: Why woulo you ever ooot to implement the
same methoo twice?
Inner object: Let`s revisit GUI event hanolers. Think
about it... il you want t/r.. buttons to each have a
oillerent event behavior, then use t/r.. inner classes, all
implementing ActionListenerwhich means each class
gets to implement its own actionFerlormeo methoo.
HeadFirst: So are event hanolers the only reason to use
inner classes?
Inner object: Oh, gosh no. Event hanolers are just an
obvious example. Anytime you neeo a separate class, but
still want that class to behave as il it were part ol oot/.r
class, an inner class is the bestano sometimes ol,way
to oo it.
HeadFirst: I`m still conluseo here. Il you want the inner
class to o./o.. like it belongs to the outer class, why have
a separate class in the nrst place? Why woulon`t the inner
class cooe just be io the outer class in the nrst place?
Inner object: I just o.. you one scenario, where you
neeo more than one implementation ol an interlace. But
even when you`re not using interlaces, you might neeo
two oillerent clo. because those classes represent two
oillerent t/io. It`s gooo OO.
HeadFirst: Whoa. Holo on here. I thought a big part ol
OO oesign is about reuse ano maintenance. You know, the
ioea that il you have two separate classes, they can each
be mooineo ano useo inoepenoently, as opposeo to stulnng
it all into one class yaoa yaoa yaoa. But with an ioo.r class,
you`re still just working with one r.ol class in the eno, right?
The enclosing class is the only one that`s reusable ano
separate lrom everybooy else. Inner classes aren`t exactly
reusable. In lact, I`ve hearo them calleo Reuseless
useless over ano over again.
Inner object: Yes it`s true that the inner class is not o
reusable, in lact sometimes not reusable at all, because it`s
intimately tieo to the instance variables ano methoos ol
the outer class. But it
HeadFirst: which only proves my point Il they`re not
reusable, why bother with a separate class? I mean, other
than the interlace issue, which sounos like a workarouno
to me.
Inner object: As I was saying, you neeo to think about
IS-A ano polymorphism.
HeadFirst: OK. Ano I`m thinking about them because...
Inner object: Because the outer ano inner classes
might neeo to pass oiff.r.ot IS-A tests Let`s start with the
polymorphic GUI listener example. What`s the oeclareo
argument type lor the button`s listener registration
methoo? In other woros, il you go to the AFI ano check,
what kino ol t/io ,class or interlace type, oo you have to
pass to the aooActionListener,, methoo?
HeadFirst: You have to pass a listener. Something that
implements a particular listener interlace, in this case
ActionListener. Yeah, we know all this. What`s your point?
Inner object: My point is that polymorphically, you have
a methoo that takes only one particular t,.. Something
that passes the IS-A test lor ActionListener. Butano
here`s the big thingwhat il your class neeos to be an IS-
A ol something that`s a clo type rather than an interlace?
HeadFirst: Woulon`t you have your class just .xt.oo the
class you neeo to be a part ol ? Isn`t that the whole point
ol how subclassing works? Il B is a subclass ol A, then
anywhere an A is expecteo a B can be useo. The whole
pass-a-Dog-where-an-Animal-is-the-oeclareo-type thing.
Inner object: Yes Bingo So now what happens il you
neeo to pass the IS-A test lor two oillerent classes? Classes
that aren`t in the same inheritance hierarchy?
This weeks interview:
Instance of an Inner CIass
1a-a spese3
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 381
HeadFirst: Oh, well you just... hmmm. I think I`m get-
ting it. You can always iol.o.ot more than one interlace,
but you can .xt.oo only o. class. You can only be one kino
ol IS-A when it comes to clo types.
Inner object: Well oone Yes, you can`t be both a Dog
ano a Button. But il you`re a Dog that neeos to some-
times be a Button ,in oroer to pass yoursell to methoos
that take a Button,, the Dog class ,which extenos Animal
so it can`t exteno Button, can have an ioo.r class that acts
on the Dog`s behall as a Button, by extenoing Button,
ano thus wherever a Button is requireo the Dog can
pass his inner Button insteao ol himsell. In other woros,
insteao ol saying x.takeButton,this,, the Dog object calls
x.takeButton,new MyInnerButton,,,.
HeadFirst: Can I get a clear example?
Inner object: Remember the orawing panel we useo,
where we maoe our own subclass ol JFanel? Right now,
that class is a separate, non-inner, class. Ano that`s nne,
because the class ooesn`t neeo special access to the instance
variables ol the main GUI. But what il it oio? What il
we`re ooing an animation on that panel, ano it`s getting its
cooroinates lrom the main application ,say, baseo on some-
thing the user ooes elsewhere in the GUI,. In that case, il
we make the orawing panel an inner class, the orawing
panel class gets to be a subclass ol JFanel, while the outer
class is still lree to be a subclass ol something else.
HeadFirst: Yes I see Ano the orawing panel isn`t reus-
able enough to be a separate class anyway, since what it`s
actually painting is specinc to this one GUI application.
Inner object: Yes You`ve got it
HeadFirst: Gooo. Then we can move on to the nature ol
the r.lotio/i between you ano the outer instance.
Inner object: What is it with you people? Not enough
soroio gossip in a serious topic like polymorphism?
HeadFirst: Hey, you have no ioea how much the public is
willing to pay lor some gooo olo tabloio oirt. So, someone
creates you ano becomes instantly bonoeo to the outer
object, is that right?
Inner object: Yes that`s right. Ano yes, some have
compareo it to an arrangeo marriage. We oon`t have a say
in which object we`re bonoeo to.
HeadFirst: Alright, I`ll go with the marriage analogy.
Can you get a oi.rc. ano remarry something .l.?
Inner object: No, it`s lor lile.
HeadFirst: Whose lile? Yours? The outer object? Both?
Inner object: Mine. I can`t be tieo to any other outer
object. My only way out is garbage collection.
HeadFirst: What about the outer object? Can it be
associateo with any other inner objects?
Inner object: So now we have it. This is what you r.oll,
wanteo. Yes, yes. My so-calleo mate` can have as many
inner objects as it wants.
HeadFirst: Is that like, serial monogamy? Or can it have
them all at the same time?
Inner object: All at the same time. There. Satisneo?
HeadFirst: Well, it ooes make sense. Ano let`s not
lorget, it was ,o extolling the virtues ol multiple
implementations ol the same interlace. So it makes sense
that il the outer class has three buttons, it woulo neeo
three oillerent inner classes ,ano thus three oillerent inner
class objects, to hanole the events. Thanks lor everything.
Here`s a tissue.
He fhinks he's
gof if mode, hoving fwo
inner cIoss objecfs. 8uf we
hove occess fo oII his privofe
dofo, so jusf imogine fhe domoge
we couId do...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
382 chapter 12
Wc saw why innci classcs aic hanuy loi cvcni lisicncis, lccausc
you gci io imlcmcni ihc samc cvcni-hanuling mcihou moic
ihan oncc. Bui now wc`ll looI ai how usclul an innci class is whcn
uscu as a sulclass ol somcihing ihc ouici class uocsn`i cxicnu. In
oihci woius, whcn ihc ouici class anu innci class aic in uillcicni
inhciiiancc iiccs!
Oui goal is io maIc a simlc animaiion, whcic ihc ciiclc movcs
acioss ihc sciccn liom ihc uci lcli uown io ihc lowci iighi.
0s|n] zn |nncr r|zss fer zn|mz!|en
:l.-l
-:
How simple animation works
1 Poinf on objecf of o porficuIor x ond y coordinofe
g.llOval(20,50,100,100);
io -|: --- l- |-l,
-o -|: --- l- l-
2 Pepoinf fhe objecf of o differenf x ond y coordinofe
g.llOval(25,55,100,100);
i- -|: --- l- |-l, --
-|: --- l- l-
|l- --:l --- . |ll|-
--- .- l- l- -l`
3 Pepeof fhe previous sfep wifh chonging x ond y voIues
for os Iong os fhe onimofion is supposed fo confinue.
(-,- a,- |
oa|| qa--(:|-

Why are we Iearning about


animation here! I doubt if I'm
going to be making games.
ou might not be making
games, but you might be
creating simulations, where
things change over time to show
the results of a process. Or you
might be building a visualization
tool that, for example, updates
a graphic to show how much
memory a program is using,
or to show you how much
traffic is coming through
your load-balancing server.
Anything that needs to take a
set of continuously-changing
numbers and translate them into
something useful for getting
information out of the numbers.
Doesn't that all sound business-
likeI That's |ust the "official
|ustification, of course. The real
reason we're covering it here is
|ust because it's a simple way
to demonstrate another use
of inner classes. (And because
we |ust animation, and our
next Head Pirst book is about
12LL and we we can't get
animation in that one.)
inner cIasses
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
getting gui
you are here 383
What we really want is something like...
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.orange);
g.llOval(x,y,100,100);
}
}
-.: l-- .-lc------l|` :
:.||-, l- -.| -l: .-l- .l .
----l |-:.l--
But where do we get the new x and y
coordinates?
And who calls repaint{}?
+,-+ :+ ,-+:.|
See if you can design a simpIe soIution to get the ball to animate from the top left of the
drawing panel down to the bottom right. Our answer is on the next page, so don't turn
this page until you're done!
8ig Huge Hint: make the drawing panel an inner class.
Another Hint: don't put any kind of repeat loop in the paintComponent() method.
Write your ideas (or the code) here:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
384 chapter 12
animation using an inner cIass
import javax.swing.*;
import java.awt.*;
public class SimpleAnimation {
int x = 70;
int y = 70;
public static void main (String[] args) {
SimpleAnimation gui = new SimpleAnimation ();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
for (int i = 0; i < 130; i++) {
x++;
y++;
drawPanel.repaint();

try {
Thread.sleep(50);
} catch(Exception ex) { }
}

}// close go() method
class MyDrawPanel extends JPanel {

public void paintComponent(Graphics g) {
g.setColor(Color.green);
g.llOval(x,y,40,40);
}
} // close inner class
} // close outer class
-.- l-- -:l.-:- .-.|-: - l-
-.- 6c| :|.::, -- l- .- ]
:----.l-: - l- :-:|-
1: : ---- l-
.:l-- :'
N-l- --- --- M.- l- --l:
.- -l l-- - l- -.--
---.l l: |?o l--:
-:-----l l- .- ]
:----.l-:
l-|| l- .--| l- --.-l l:-| |:- --
:.- :-- l- :-:|- - l- --- |-:.l-- `
|-- l --- . |ll|- |-l---:- l -|| --- :-
-:|] ]-- ---'l !! l ---` l--'l ----], ]-- -----'l :--:- l- .|--.] --- l: w-'|| -l l- l--.: - :.l-- |-
c:- l- :--l--.||]~-.l- .- ]
:----.l-: - l- --l-- :|.::
N
-
-

l
':

.
-

-
-
-
-

:
|.
:
:

The complete simple animation code


Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 385
Uh-oh. t didn't move... it smeared.
N-l -.:l|] l- |--
-- ---- -- --
Whof did we do wrong7
There's one IiffIe ow in fhe poinfComponenf()
mefhod.
We forgot to erase what was
already therel 8o we got trails.
To fx if, oII we hove fo do is fII in fhe enfire poneI wifh
fhe bockground coIor, before poinfing fhe circIe eoch
fime. The code beIow odds fwo Iines of fhe sforf of fhe
mefhod: one fo sef fhe coIor fo whife (fhe bockground
coIor of fhe drowing poneI) ond fhe ofher fo fII fhe
enfire poneI recfongIe wifh fhof coIor. In EngIish, fhe
code beIow soys, "FiII o recfongIe sforfing of x ond y of
0 (0 pixeIs from fhe Ieff ond 0 pixeIs from fhe fop) ond
moke if os wide ond os high os fhe poneI is currenfIy.
public void paintComponent(Graphics g) {
g.setColor(Color.white);
g.llRect(0,0,this.getWidth(), this.getHeight());
g.setColor(Color.green);
g.llOval(x,y,40,40);
}
-lwl|` .- -l+-l|` .-- --l-: ---l- --- )|.--|
\,-+ :+ ,-+:.| |:,t.:+|. +st |: |++l
what changes would you make to the x and y coordinates to produce the animations belowI
(assume the rst one example moves in 3 pixel increments)

start nish

start nish
X +?
Y +?
start nish

X
Y
X
Y

start nish

start nish
X
Y
start nish

X
Y
X
Y
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
386 chapter 12
CaJe kit:hea
Iet's a|e a asi: viJea. he'|| ase Java-geae:ateJ :aaJa
g:ahi:s that |ee tie vith the asi: leats.
A|aag the vay ve'|| :egiste: laaJ |istea Ia:I a aev |iaJ aI
aaa-6l! eveat, t:igge:eJ ly the asi: itse|I.
-.l --- -.l l-- -.l l---
-.l ---
------, l: .-l : .|| -l--.| B-l -- l- l': -- -- ]--
A- ]--'|| |- l A- ]-- :.- -:- l l- ---:: --|-
|6, :---, l -l --- --|] -- --|- -- .-- --.||] -.:] l- ---::,
-l :l||`
Code Kitchen
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 387
OK, maylc noi a music viuco, lui wc w.II maIc
a iogiam ihai uiaws ianuom giahics on ihc
sciccn wiih ihc lcai ol ihc music. In a nuishcll,
ihc iogiam lisicns loi ihc lcai ol ihc music
anu uiaws a ianuom giahic iccianglc wiih cach
lcai.
Thai liings u somc ncw issucs loi us. So lai,
wc`vc lisicncu loi only GUI cvcnis, lui now
wc nccu io lisicn loi a aiiiculai Iinu ol MIDI
cvcni. Tuins oui, lisicning loi a non-GUI cvcni is
|usi liIc lisicning loi GUI cvcnis: you imlcmcni
a lisicnci inicilacc, icgisici ihc lisicnci wiih an
cvcni souicc, ihcn sii lacI anu waii loi ihc cvcni
souicc io call youi cvcni-hanulci mcihou ihc
mcihou uchncu in ihc lisicnci inicilacc).
Thc simlcsi way io lisicn loi ihc lcai ol ihc
music woulu lc io icgisici anu lisicn loi ihc
aciual MIDI cvcnis, so ihai whcncvci ihc
scqucncci gcis ihc cvcni, oui couc will gci ii
ioo anu can uiaw ihc giahic. Bui... ihcic`s a
iollcm. A lug, aciually, ihai won`i lci us lisicn
loi ihc MIDI cvcnis we`.e maIing ihc oncs loi
NOTE ON).
So wc havc io uo a liiilc woiI-aiounu. Thcic
is anoihci iyc ol MIDI cvcni wc can lisicn
loi, callcu a ConiiollciEvcni. Oui soluiion
is io icgisici loi ConiiollciEvcnis, anu ihcn
maIc suic ihai loi cvciy NOTE ON cvcni,
ihcic`s a maiching ConiiollciEvcni hicu ai
ihc samc lcai`. How uo wc maIc suic ihc
ConiiollciEvcni is hicu ai ihc samc iimc. Wc
auu ii io ihc iiacI |usi liIc ihc oihci cvcnis! In
oihci woius, oui music scqucncc gocs liIc ihis:
BEAT 1 - NOTE ON, CONTROIIER EVENT
BEAT 2 - NOTE OII
BEAT S - NOTE ON, CONTROIIER EVENT
BEAT 4 - NOTE OII
anu so on.
Bcloic wc uivc inio ihc lull iogiam, ihough,
lci`s maIc ii a liiilc casici io maIc anu auu MIDI
mcssagcs/cvcnis sincc in L. iogiam, wc`ic
gonna maIc a loi ol ihcm.
I|s!cn|n] fer z nen-00| cvcn!
1 Moke o series of MIDI messoges/
evenfs fo pIoy rondom nofes on o piono
(or whofever insfrumenf you choose)
What the music art program
needs to do:
2 Pegisfer o Iisfener for fhe evenfs
3 Sforf fhe sequencer pIoying
4 Eoch fime fhe Iisfener's evenf
hondIer mefhod is coIIed, drow o
rondom recfongIe on fhe drowing
poneI, ond coII repoinf.
1 Version One: Code fhof simpIifes mok-
ing ond odding MIDI evenfs, since we'II
be moking o Iof of fhem.
We'll build it in three iterations:
2 Version Two: Pegisfer ond Iisfen for
fhe evenfs, buf wifhouf grophics.
Prinfs o messoge of fhe commond-Iine
wifh eoch beof.
4 Version Three: The reoI deoI. Adds
grophics fo version fwo.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
388 chapter 12
ShortMessage a = new ShortMessage();
a.setMessage(144, 1, note, 100);
MidiEvent noteOn = new MidiEvent(a, 1);
track.add(noteOn);
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, note, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
Righi now, maIing anu auuing mcssagcs anu
cvcnis io a iiacI is icuious. Ioi cach mcssagc,
wc havc io maIc ihc mcssagc insiancc in ihis
casc, ShoiiMcssagc), call sciMcssagc), maIc a
MiuiEvcni loi ihc mcssagc, anu auu ihc cvcni
io ihc iiacI. In lasi chaici`s couc, wc wcni
ihiough cach sic loi cvciy mcssagc. Thai
mcans cighi lincs ol couc |usi io maIc a noic
lay anu ihcn sio laying! Ioui lincs io auu a
NOTE ON cvcni, anu loui lincs io auu a NOTE
OII cvcni.
n czs|cr wzy !e mzkc
mcssz]cs / cvcn!s
1 Moke o messoge insfonce
ShortMessage rst = new ShortMessage();
Things that have to happen for
each event:
2 CoII sefMessoge() wifh fhe insfrucfions
rst.setMessage(192, 1, instrument, 0)
3 Moke o MidiEvenf insfonce for fhe messoge
MidiEvent noteOn = new MidiEvent(rst, 1);
4 Add fhe evenf fo fhe frock
track.add(noteOn);
public static MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);

}catch(Exception e) { }
return event;
}
Let's build a static utility method that
makes a message and returns a MidiEvent
l- --- .-----l:
-- l- --::.-
1- ---l 'l:' --
w+!N l: --::.-
:--| .--
-.- l- --::.- .- l- ---l, -:-
l- --l- .-.--l--:
---' A --l- -l - .-.--l--:
--l--- l- ---l |. M!--l .||
|-.- - -l l- --::.-`
utiIity method for events
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 389
import javax.sound.midi.*;
public class MiniMusicPlayer1 {

public static void main(String[] args) {
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();


Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();

for (int i = 5; i < 61; i+= 4) {

track.add(makeEvent(144,1,i,100,i));
track.add(makeEvent(128,1,i,100,i + 2));
} // end loop

sequencer.setSequence(seq);
sequencer.setTempoInBPM(220);
sequencer.start();
} catch (Exception ex) {ex.printStackTrace();}
} // close main
public static MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);

}catch(Exception e) { }
return event;
}
} // close class
-.- |.- ---` . :----:--
-.- . :----:-
.- . l-.:
-.- . --: - ---l: l- -.- l- --l-: --
-- - |--- .-- --l- - l- .-- --l- ||`
--'l ---l l- -
--l
:.|| --- --- -.-!--l|` --l- l- -.- l-
--::.- .- ---l, l-- . l- --:-|l |l-
M!--l --l---- --- -.-!--l|`` l-
l- l-.: 1-:- .-- N61! 6N ||++` .-
N61! 6|| ||i` .-:
:l.-l l -----
Thcic`s no cvcni hanuling oi giahics hcic, |usi a scqucncc ol 1
noics ihai go u ihc scalc. Thc oini ol ihis couc is simly io lcain
how io usc oui ncw maIcEvcni) mcihou. Thc couc loi ihc ncxi
iwo vcisions is much smallci anu simlci ihanIs io ihis mcihou.
Irzmp|c: hew !e esc !hc ncw s!z!|r
mzkcIvcn!|I mc!he4
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
390 chapter 12
import javax.sound.midi.*;
public class MiniMusicPlayer2 implements ControllerEventListener {

public static void main(String[] args) {
MiniMusicPlayer2 mini = new MiniMusicPlayer2();
mini.go();
}
public void go() {
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
int[] eventsIWant = {127};
sequencer.addControllerEventListener(this, eventsIWant);
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
for (int i = 5; i < 60; i+= 4) {
track.add(makeEvent(144,1,i,100,i));
track.add(makeEvent(176,1,127,0,i));
track.add(makeEvent(128,1,i,100,i + 2));
} // end loop
sequencer.setSequence(seq);
sequencer.setTempoInBPM(220);
sequencer.start();
} catch (Exception ex) {ex.printStackTrace();}
} // close
public void controlChange(ShortMessage event) {
System.out.println(la);
}
public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);

}catch(Exception e) { }
return event;
}
} // close class
Code fhof's differenf from fhe previous
version is highIighfed in groy. (ond we're
nof running if oII wifhin moin() fhis fime)
w- --- l- |:l-- -- c--l--||--!--l:,
:- -- -|----l l- |:l---- -l--.:-
-:l-- -- ---l: -l l- :----:--
1- ---l --:l-.l-- --l- l.-: l-
|:l---- ANl .- -l .--.] ----:--l-
l- |:l - c--l--||--!--l: ]-- -.-l
w- -.-l --|] --- ---l, +|i7
+---': -- -- : - l- -.l ~~ -- -:--l --- 6wN c--l--||--!--l ||7| :.]: l- ---l l]- : c--l--||--!--l` -l .- .-----l --
---l ----- +|i7 1: ---l -|| - N61+~ |N6' w- -l l - )c1 :- l.l -- :.- -l .- ---l -.: l-- . --l- : |.]- |- -l-- ---:, l: :-|- ---:- : :- l.l :---l- -||
-- l.l w! :.- |:l-- -- |-- :.-'l |:l-- -- N61! 6N/6|| ---l:` N-l- l.l --'-- -.- l: ---l .-- .l l- AM! l: .:
l- N61! 6N - --- l- N61! 6N ---l .--:, --'|| --- .--l l -:.-:- 6c ---l
-|| -- .l l- :.-- l--
1- ---l .-|-- --l- |--- l- c--l--||--~
!--l |:l---- -l--.:-` !.: l-- -- -l l-
---l, --'|| --l |.' l- l- :---.-~|--
Vcrs|en Iwe: rc]|s!cr|n] zn4 ]c!!|n] 0en!re||crIvcn!s
controIIer events
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 391
This hnal vcision luilus on vcision iwo ly auuing ihc GUI aiis. Wc luilu a
liamc, auu a uiawing ancl io ii, anu cach iimc wc gci an cvcni, wc uiaw a
ncw iccianglc anu icaini ihc sciccn. Thc only oihci changc liom vcision
iwo is ihai ihc noics lay ianuomly as ooscu io simly moving u ihc
scalc.
Thc mosi imoiiani changc io ihc couc lcsiucs luiluing a simlc GUI)
is ihai wc maIc ihc uiawing ancl imlcmcni ihc ConiiollciEvcniIisicnci
iaihci ihan ihc iogiam iiscll. So whcn ihc uiawing ancl an innci class)
gcis ihc cvcni, ii Inows how io iaIc caic ol iiscll ly uiawing ihc iccianglc.
Comlcic couc loi ihis vcision is on ihc ncxi agc.
Vcrs|en Ihrcc: 4rzw|n] ]rzph|rs |n !|mc w| !h !hc mes|r
class MyDrawPanel extends JPanel implements ControllerEventListener {

boolean msg = false;
public void controlChange(ShortMessage event) {
msg = true;
repaint();
}
public void paintComponent(Graphics g) {
if (msg) {

Graphics2D g2 = (Graphics2D) g;
int r = (int) (Math.random() * 250);
int gr = (int) (Math.random() * 250);
int b = (int) (Math.random() * 250);
g.setColor(new Color(r,gr,b));
int ht = (int) ((Math.random() * 120) + 10);
int width = (int) ((Math.random() * 120) + 10);
int x = (int) ((Math.random() * 40) + 10);
int y = (int) ((Math.random() * 40) + 10);
g.llRect(x,y,ht, width);
msg = false;
} // close if
} // close method
} // close inner class
The drawing panel inner class:
1- -.-- .--| : . |:l----
w- :-l . |. l- .|:-, .- --'|| :-l l
l- l--- --|] --- -- -l .- ---l
w- -l .- ---l, :- -- :-l l- |. l-
l--- .- :.|| --.-l|`
w- .- l- -:- . |. -:.-:- 61+! l-: -l l--- . --.-l|`, .- -- -.-l l- .-l 6N|/ --- l---': . c--l--||--!--l
1- --:l : :-- l- ----.l-
. -.--- :-|-- .- .-l .
:--~-.--- --:l.-|-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
392 chapter 12
import javax.sound.midi.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
public class MiniMusicPlayer3 {
static JFrame f = new JFrame(My First Music Video);
static MyDrawPanel ml;
public static void main(String[] args) {
MiniMusicPlayer3 mini = new MiniMusicPlayer3();
mini.go();
} // close method

public void setUpGui() {
ml = new MyDrawPanel();
f.setContentPane(ml);
f.setBounds(30,30, 300,300);
f.setVisible(true);
} // close method

public void go() {
setUpGui();
try {

Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.addControllerEventListener(ml, new int[] {127});
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
int r = 0;
for (int i = 0; i < 60; i+= 4) {
r = (int) ((Math.random() * 50) + 1);
track.add(makeEvent(144,1,r,100,i));
track.add(makeEvent(176,1,127,0,i));
track.add(makeEvent(128,1,r,100,i + 2));
} // end loop

sequencer.setSequence(seq);
sequencer.start();
sequencer.setTempoInBPM(120);
} catch (Exception ex) {ex.printStackTrace();}
} // close method
+,-+ :+ ,-+:.|
This is fhe compIefe code Iisfing for Version
Three. If buiIds direcfoy on Version Two. Try
fo onnofofe if yourseIf, wifhouf Iooking of fhe
previous poges.
MiniMusicPIayer3 code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
getting gui
you are here 393
public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);

}catch(Exception e) { }
return event;
} // close method
class MyDrawPanel extends JPanel implements ControllerEventListener {
boolean msg = false;
public void controlChange(ShortMessage event) {
msg = true;
repaint();
}
public void paintComponent(Graphics g) {
if (msg) {

Graphics2D g2 = (Graphics2D) g;
int r = (int) (Math.random() * 250);
int gr = (int) (Math.random() * 250);
int b = (int) (Math.random() * 250);
g.setColor(new Color(r,gr,b));
int ht = (int) ((Math.random() * 120) + 10);
int width = (int) ((Math.random() * 120) + 10);
int x = (int) ((Math.random() * 40) + 10);
int y = (int) ((Math.random() * 40) + 10);

g.llRect(x,y,ht, width);
msg = false;
} // close if
} // close method
} // close inner class
} // close class
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
394 chapter 12

A bunch of 1ava hot-shots, in full costume, are playing the party game "who
am |I They give you a clue, and you try to guess who they are, based on
what they say. Assume they always tell the truth about themselves. |f they
happen to say something that could be true for more than one guy, then
write down all for whom that sentence applies. Pill in the blanks next to the
sentence with the names of one or more attendees.
7onight's attendees:
Any of the charming personaIities from this chapter just
might show upl
I got the whoIe GUI, in my hands.
Every event type has one of these.
The Iistener's key method.
This method gives JFrame its size.
You add code to this method but never caII it.
When the user actuaIIy does something, it's an _____ .
Most of these are event sources.
I carry data back to the Iistener.
An addXxxListener( ) method says an object is an _____ .
How a Iistener signs up.
The method where aII the graphics code goes.
I'm typicaIIy bound to an instance.
The 'g' in (Graphics g), is reaIIy of cIass.
The method that gets paintComponent( ) roIIing.
The package where most of the Swingers reside.

exercise: Who Am I
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 395
[[ ]zvz |j] n ([j, zg ,n(, z
e]( ,ae |j]. (a j j, ( ]zy
ej] zn] ](jn w[([ ([j, |j]
wj]] ej]. ]| j( wn'( ej], [w
wa]] ya |jy j(, zn] j| j( ],
ej], w[z( wa]] j( ]/
import avax.swing.*,
import ava.awt.event.*,
import ava.awt.*,
class InnerButton {
JFrame frame,
JButton b,
public static void main{String args| {
InnerButton gui = new InnerButton{|,
gui.go{|,
}
public void go{| {
frame = new JFrame{|,
frame.setDefaultCloseOperation{
JFrame.EXIT_ON_CLOSE|,
b = new JButton{"A"|,
b.addActionListener{|,

frame.getContentPane{|.add{
BorderLayout.SOUTH, b|,
frame.setSize{200,l00|,
frame.setVisible{true|,
}
class BListener extends ActionListener {
public void actionPerformed{ActionEvent e| {
if {b.getText{|.equals{"A"|| {
b.setText{"B"|,
} else {
b.setText{"A"|,
}
}
}
}

] ge eomgj|e;
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

our is to take code snippets from
the pool and place them into the blank
lines in the code. ou may use the
same snippet more than once,
and you won't need to use all the
snippets. our is to make a
class that will compile and run
and produce the output listed.
Note: ach snippet
from the pooI can be
used more than oncel
Dutput
drawP.setSize(500,270)
frame.setSize(500,270)
panel.setSize(500,270)
x++
y++
Thc Amazing, ShiinIing, Bluc Rccianglc.
This iogiam will iouucc a lluc
iccianglc ihai will shiinI anu shiinI anu
uisacai inio a hclu ol whiic.
g.setColor(blue)
g.setColor(white)
g.setColor(Color.blue)
g.setColor(Color.white)
g.fillPect(x,y,x-500,y-250)
g.fillPect(x,y,500-x`2,250-y`2)
g.fillPect(500-x`2,250-y`2,x,y)
g.fillPect(0,0,250,500)
g.fillPect(0,0,500,250)
g
draw
frame
panel
i++
i++, y++
i++, y++, x++
Animate frame new Animate()
MyDrawP drawP new MyDrawP()
ContentPane drawP new ContentPane() drawP.paint()
draw.repaint()
drawP.repaint()
puzzIe: PooI PuzzIe
import avax.swing.*,
import ava.awt.*,
public class Animate {
int x = l,
int y = l,
public static void main {String args| {
Animate gui = new Animate {|,
gui.go{|,
}
public void go{| {
JFrame _________ = new JFrame{|,
frame.setDefaultCloseOperation{
JFrame.EXIT_ON_CLOSE|,
______________________________________,
_________.getContentPane{|.add{drawP|,
__________________________,
_________.setVisible{true|,
for {int i=0, i<l24, _______________| {
_____________________,
_____________________,
try {
Thread.sleep{50|,
} catch{Exception ex| { }
}
}
class MyDrawP extends JPanel {
public void paintComponent {Graphic
_________| {
__________________________________,
__________________________________,
__________________________________,
__________________________________,
}
}
}
396 chapter 12
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 397
import avax.swing.*,
import ava.awt.event.*,
import ava.awt.*,
class InnerButton {
JFrame frame,
JButton b,
public static void main{String args| {
InnerButton gui = new InnerButton{|,
gui.go{|,
}
public void go{| {
frame = new JFrame{|,
frame.setDefaultCloseOperation{
JFrame.EXIT_ON_CLOSE|,
b = new JButton{"A"|,
b.addActionListener{ ncw BI|s!cncr| I |,

frame.getContentPane{|.add{
BorderLayout.SOUTH, b|,
frame.setSize{200,l00|,
frame.setVisible{true|,
}
class BListener |mp|cmcn!s ActionListener {
public void actionPerformed{ActionEvent e| {
if {b.getText{|.equals{"A"|| {
b.setText{"B"|,
} else {
b.setText{"A"|,
}
}
}
}
The oddAcfionLisfener( )
mefhod fokes o cIoss fhof
impIemenfs fhe AcfionLis-
fener inferfoce
AcfionLisfener is on
inferfoce, inferfoces
ore impIemenfed, nof
exfended
] ge eomgj|e;
Once fhis code
is fxed, if wiII
creofe o 0UI wifh
o buffon fhof
foggIes befween
A ond 8 when you
cIick if.
I goi ihc wholc GUI, in my hanus. JFrome
Evciy cvcni iyc has onc ol ihcsc. Iisfener inferfoce
Thc lisicnci`s Icy mcihou. ocfionPerformed( )
This mcihou givcs ]Iiamc iis sizc. sefSi;e( )
You auu couc io ihis mcihou lui
ncvci call ii. poinfComponenf( )
Whcn ihc usci aciually uocs
somcihing, ii`s an ____ evenf
Mosi ol ihcsc aic cvcni souiccs. swing componenfs
I caiiy uaia lacI io ihc lisicnci. evenf objecf
An auuXxxIisicnci ) mcihou
says an ol|cci is an ___ evenf source
How a lisicnci signs u. oddAcfionLisfener( )
Thc mcihou whcic all ihc
giahics couc gocs. poinfComponenf( )
I`m iyically lounu io an insiancc. inner cIoss
Thc g` in Giahics g), is
ically ol ihis class. 0rophicsZd
Thc mcihou ihai gcis
ainiComoncni ) iolling. repoinf( )
Thc acIagc whcic mosi ol ihc
Swingcis icsiuc. jovox.swing

[yej, ]a(jn,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
398 chapter 12

import avax.swing.*,
import ava.awt.*,
public class Animate {
int x = l,
int y = l,
public static void main {String args| {
Animate gui = new Animate {|,
gui.go{|,
}
public void go{| {
JFrame frome = new JFrame{|,
frame.setDefaultCloseOperation{
JFrame.EXIT_ON_CLOSE|,
MyDrowP drowP ~ new MyDrowP(),
frome.getContentPane{|.add{drawP|,
frome.sefSi;e(b00,Z70),
frome.setVisible{true|,
for {int i = 0, i < l24, i++,x++,y++ | {
x++,
drowP.repoinf(),
try {
Thread.sleep{50|,
} catch{Exception ex| { }
}
}
class MyDrawP extends JPanel {
public void paintComponent{Graphics g | {
g.sefCoIor(CoIor.whife),
g.fIIPecf(0,0,b00,Zb0),
g.sefCoIor(CoIor.bIue),
g.fIIPecf(x,y,b00-x*Z,Zb0-y*Z),
}
}
}
Thc Amazing, ShiinIing, Bluc
Rccianglc.
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 399
13 using swing
Swing is easy. Unless you actually cote where things end up on the screen. Swing code
lools easy, but then you compile it, run it, look at it and think, "hey, thots not supposed to go
thete. The thing that makes it eosy to coJe is the thing that makes it hotJ to conttolthe
Layout Manager. Layout Manager ob|ects control the size and location of the widgets in a
1ava GU|. They do a ton of work on your behalf, but you won't always like the results. ou want
two buttons to be the same size, but they aren't. ou want the text field to be three inches long,
but it's nine. Or one. And unJet the label instead of next to it. 8ut with a little work, you can get
layout managers to submit to your will. |n this chapter, we'll work on our Swing and in addition
to layout managers, we'll learn more about widgets. we'll make them, display them (where we
choose), and use them in a program. |t's not looking too good for Suzy.
Why won'f
fhe boII go where wonf
if fo go7 (Iike, smock in Su;y
Smifh's foce) I've goffo Ieorn
fo confroI if.
Work on Your
8wing
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
400 chapter 13
is ihc moic coiicci icim loi whai wc`vc lccn calling a w.Je.
Thc L.r you ui in a GUI. TLe L.r n ue. ee nrJ .re.n w.L. Tcxi
hclus, luiions, sciollallc lisis, iauio luiions, cic. aic all comoncnis. In
laci, ihcy all cxicnu javax.swing.JComponent.
components and containers
8w|n] rempencn!s
In Swing, viiiually nII comoncnis aic caallc ol holuing oihci
comoncnis. In oihci woius, ,ou nr .I u nbou nr,L.r .ro nr,L.r
eIe. Bui mosi ol ihc iimc, you`ll auu ue. .re.n..e comoncnis such as
luiions anu lisis inio bnI.ourJ comoncnis such as liamcs anu ancls.
Alihough ii`s o.bIe io ui, say, a ancl insiuc a luiion, ihai`s iciiy
wciiu, anu won`i win you any usaliliiy awaius.
Wiih ihc cxcciion ol ]Iiamc, ihough, ihc uisiinciion lciwccn .re.n..e
comoncnis anu bnI.ourJ comoncnis is aiiihcial. A ]Pancl, loi
cxamlc, is usually uscu as a lacIgiounu loi giouing oihci comoncnis,
lui cvcn a ]Pancl can lc iniciaciivc. ]usi as wiih oihci comoncnis, you
can icgisici loi ihc ]Pancl`s cvcnis incluuing mousc clicIs anu IcysiioIcs.
0empencn!s rzn |c ncs!c4
Four steps to making a GU {review}
JFrame frame = new JFrame();
Moke o window (o JFrome)
JButton button = new JButton(click me);
frame.getContentPane().add(BorderLayout.EAST, button);
1
Moke o componenf (buffon, fexf feId, efc.) 2
Add fhe componenf fo fhe frome 3
frame.setSize(300,300);
frame.setVisible(true);
DispIoy if (give if o si;e ond moke if visibIe) 4
Put interactive components: nto background components:
)B-ll--
)c-:B-
)1-l|-|
)|-.--
)|.--|
A v:Jget :s te:ha::a||y
a Sv:ag Caaaeat.
A|ast eve:y th:ag
yaa :aa st::| :a a
6l! exteaJs I:a
avax.sv:ag.JCaaaeat.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 401
Izyee! Mznz]crs
|.--| A': |.]--l -.-.--
:--l--|: l- :-- .-
|.:----l - |.--| B
As o Ioyouf monoger,
I'm in chorge of fhe si;e
ond pIocemenf of your componenfs.
In fhis 0UI, I'm fhe one who decided
how big fhese buffons shouId be, ond
where fhey ore reIofive fo eoch
ofher ond fhe frome.
A layoui managci is a ]ava ol|cci associaicu
wiih a aiiiculai comoncni, almosi always a
bnI.ourJ comoncni. Thc layoui managci
coniiols ihc comoncnis coniaincu w.L.r ihc
comoncni ihc layoui managci is associaicu
wiih. In oihci woius, il a liamc holus a ancl,
anu ihc ancl holus a luiion, ihc ancl`s layoui
managci coniiols ihc sizc anu laccmcni ol
ihc luiion, whilc ihc liamc`s layoui managci
coniiols ihc sizc anu laccmcni ol ihc
ancl. Thc luiion, on ihc oihci hanu,
uocsn`i nccu a layoui managci lccausc ihc
luiion isn`i holuing oihci comoncnis.
Il a ancl holus hvc ihings, cvcn il ihosc
hvc ihings cach havc ihcii own layoui
managcis, ihc sizc anu locaiion ol ihc hvc
ihings in ihc ancl aic all coniiollcu ly ihc
ancl`s layoui managci. Il ihosc hvc ihings,
in iuin, holu oLe. ihings, ihcn ihosc oLe.
ihings aic laccu accoiuing io ihc layoui
managci ol ihc ihing holuing ihcm.
Whcn wc say LoIJ wc ically mcan nJJ as in, a
ancl LoIJ a luiion lccausc ihc luiion was
nJJeJ io ihc ancl using somcihing liIc:
myPanel.add(button);
Iayoui managcis comc in scvcial uavois, anu
cach lacIgiounu comoncni can havc iis own
layoui managci. Iayoui managcis havc ihcii
own olicics io lollow whcn luiluing a layoui.
Ioi cxamlc, onc layoui managci mighi insisi
ihai all comoncnis in a ancl musi lc ihc samc
sizc, aiiangcu in a giiu, whilc anoihci layoui
managci mighi lci cach comoncni choosc iis
own sizc, lui siacI ihcm vciiically. Hcic`s an
cxamlc ol ncsicu layouis:
PoneI A
PoneI 8
buffon I
buffon Z
buffon 3
|
.--| B
': |.]--l
-
.-.--
:--l
--|: l
- :-
- .-
|.:--
--l

-
l
- l
--- -l
l
--:
|.--| A': |.]--l -.-.-- .: N61+|N6 l-
:.] .--l l- l--- -ll--: 1- --.-:]
- :--l--| : --|] --- |--|-|.--| A': |.]--l
-.-.-- :--l--|: --|] l- l-: .- --:l|]
l- |.--| A, .- --: --l :--l--| .-]l-
--:l- -l- l-:- .- :------l:
JPanel panelA = new JPanel();
JPanel panelB = new JPanel();
panelB.add(new JButton(button 1));
panelB.add(new JButton(button 2));
panelB.add(new JButton(button 3));
panelA.add(panelB);
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
402 chapter 13
Dillcicni layoui managcis havc uillcicni olicics loi aiianging
comoncnis liIc, aiiangc in a giiu, maIc ihcm all ihc samc sizc,
siacI ihcm vciiically, cic.) lui ihc comoncnis lcing laycu oui uo
gci ai lcasi oe small say in ihc maiici. In gcncial, ihc ioccss ol
laying oui a lacIgiounu comoncni looIs somcihing liIc ihis:
Hew 4ecs !hc |zyee! mznz]cr 4cr|4c!
P|ffcrcn! |zyee! mznz]crs hzvc 4|ffcrcn! pe||r|cs
Moke o poneI ond odd fhree buffons fo if. 1
The poneI's Ioyouf monoger osks eoch buffon how big
fhof buffon prefers fo be.
Add fhe poneI fo o frome. 4
2
The poneI's Ioyouf monoger uses ifs Ioyouf poIicies fo decide
whefher if shouId respecf oII, porf, or none of fhe buffons'
preferences.
3
The frome's Ioyouf monoger osks fhe poneI how big fhe poneI
prefers fo be.
5
The frome's Ioyouf monoger uses ifs Ioyouf poIicies fo decide
whefher if shouId respecf oII, porf, or none of fhe poneI's
preferences.
6
Lef's see here... fhe
frsf buffon wonfs fo be
30 pixeIs wide, ond fhe fexf feId
needs b0, ond fhe frome is Z00 pixeIs
wide ond I'm supposed fo orronge
everyfhing verficoIIy...
|.]--l
-
.-.--
A layout scenario:
Somc layoui managcis icscci ihc sizc ihc comoncni wanis io
lc. Il ihc luiion wanis io lc S0 ixcls ly 0 ixcls, ihai`s whai ihc
layoui managci allocaics loi ihai luiion. Oihci layoui managcis
icscci only aii ol ihc comoncni`s iclciicu sizc. Il ihc luiion
wanis io lc S0 ixcls ly 0 ixcls, ii`ll lc S0 ixcls ly howcvci
wiuc ihc luiion`s lacIgiounu nreI is. Siill oihci layoui managcis
icscci ihc iclcicncc ol only ihc In.e ol ihc comoncnis
lcing laycu oui, anu ihc icsi ol ihc comoncnis in ihai ancl
aic all mauc ihai samc sizc. In somc cascs, ihc woiI ol ihc layoui
managci can gci vciy comlcx, lui mosi ol ihc iimc you can
hguic oui whai ihc layoui managci will iolally uo, oncc you gci
io Inow ihai layoui managci`s olicics.
Iayout managers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
using swing
you are here 403
Ihc B|] Ihrcc |zyee! mznz]crs:
|er4cr, f|ew, zn4 |er.
BorderLayout
A 8orderLoyouf monoger divides o bockground
componenf info fve regions. You con odd onIy one
componenf per region fo o bockground confroIIed
by o 8orderLoyouf monoger. Componenfs Ioid ouf
by fhis monoger usuoIIy don'f gef fo hove fheir
preferred si;e. orderLuyout is the defuuIt Iuyout
munuger for u frume|
FlowLayout
A FIowLoyouf monoger ocfs kind of Iike o word
processor, excepf wifh componenfs insfeod of
words. Eoch componenf is fhe si;e if wonfs fo be,
ond fhey're Ioid ouf Ieff fo righf in fhe order fhof
fhey're odded, wifh "word-wrop" furned on. So
when o componenf won'f ff hori;onfoIIy, if drops
fo fhe nexf "Iine" in fhe Ioyouf. FIowLuyout is the
defuuIt Iuyout munuger for u puneI|
BoxLayout
A 8oxLoyouf monoger is Iike FIowLoyouf in fhof
eoch componenf gefs fo hove ifs own si;e, ond
fhe componenfs ore pIoced in fhe order in which
fhey're odded. 8uf, unIike FIowLoyouf, o 8oxLoyouf
monoger con sfock fhe componenfs verficoIIy (or
hori;onfoIIy, buf usuoIIy we're jusf concerned wifh
verficoIIy). If's Iike o FIowLoyouf buf insfeod of
hoving oufomofic 'componenf wropping', you con
inserf o sorf of 'componenf refurn key' ond force
fhe componenfs fo sforf o new Iine.
--- :------l
-- ----
:------l: .- |-l
l- -l, --.- l- .
--- |-- --- ----
:------l: .- l-
l- -ll--, --- -- '|--'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
404 chapter 13
BorderLayout cares
about five regions:
east, west, north,
south, and center
import javax.swing.*;
import java.awt.*;
public class Button1 {
public static void main (String[] args) {
Button1 gui = new Button1();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
JButton button = new JButton(click me);
frame.getContentPane().add(BorderLayout.EAST, button);
frame.setSize(200,200);
frame.setVisible(true);
}
}
B----|.]--l : - ...-l .:.-
:-:] l- ----
Let's add a button to the east region:
border Iayout

8f8l 88f00ll
How did fhe 8orderLoyouf monoger come up wifh
fhis si;e for fhe buffon7
Whof ore fhe focfors fhe Ioyouf monoger hos fo
consider7
Why isn'f if wider or foIIer7
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 405
Since if's in fhe eosf
region of o border Ioyouf,
I'II respecf ifs preferred widfh. 8uf
I don'f core how foII if wonfs fo be,
if's gonno be os foII os fhe frome,
becouse fhof's my poIicy.
public void go() {
JFrame frame = new JFrame();
JButton button = new JButton(click like you mean it);
frame.getContentPane().add(BorderLayout.EAST, button);
frame.setSize(200,200);
frame.setVisible(true);
}
Watch what happens when we give
the button more characters...
w
- :.-- --|] l- l-l
-- l- -ll--
8
u
f
fon o
b
j
e
c
f

Firsf, I osk fhe
buffon for ifs
preferred si;e.
I hove o Iof of words
now, so I'd prefer fo be
o0 pixeIs wide ond Zb
pixeIs foII.
8
u
f
fon o
b
j
e
c
f

Mexf fime
I'm goin' wifh ow
Ioyouf. Then I gef
EVEPYTHIM0 I
wonf.
1
- -ll-- -l:
l: ------ -l,
-l --l -l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
406 chapter 13
border Iayout
public void go() {
JFrame frame = new JFrame();
JButton button = new JButton(There is no spoon...);
frame.getContentPane().add(BorderLayout.NORTH, button);
frame.setSize(200,200);
frame.setVisible(true);
}
Let's try a button in the NORTH region
public void go() {
JFrame frame = new JFrame();
JButton button = new JButton(Click This!);
Font bigFont = new Font(serif, Font.BOLD, 28);
button.setFont(bigFont);
frame.getContentPane().add(BorderLayout.NORTH, button);
frame.setSize(200,200);
frame.setVisible(true);
}

Now let's make the button ask to be taller
How do we do fhof7 The buffon is oIreody os wide
os if con ever be-os wide os fhe frome. 8uf we
con fry fo moke if foIIer by giving if o bigger fonf.
1
- -ll-- : .: l.|| .: l
-.-l: l- -, -l .: -- .:
l- -.-
-
1- -l :l.]: l- :.--, -l ---
l- -ll-- : l.||-- 1- ---l
---- :l--l:- l- .::---.l-
l- -ll--': --- ------ -l
A
-- --l -|| --:- l-
-.-
- l- .||-:.l- -
--- :.:-
-- l- -ll--': -l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 407
public void go() {
JFrame frame = new JFrame();

JButton east = new JButton(East);
JButton west = new JButton(West);
JButton north = new JButton(North);
JButton south = new JButton(South);
JButton center = new JButton(Center);

frame.getContentPane().add(BorderLayout.EAST, east);
frame.getContentPane().add(BorderLayout.WEST, west);
frame.getContentPane().add(BorderLayout.NORTH, north);
frame.getContentPane().add(BorderLayout.SOUTH, south);
frame.getContentPane().add(BorderLayout.CENTER, center);
frame.setSize(300,300);
frame.setVisible(true);
}
The center region gets whatever's leftl
(except in one special case we'll look at later)
8
u
f
fon o
b
j
e
c
f

I fhink I'm geffing if... if I'm in eust or
west, I gef my preferred widfh buf fhe
heighf is up fo fhe Ioyouf monoger. And
if I'm in north or south, if's jusf fhe
opposife-I gef my preferred heighf, buf
nof widfh.
5at vhat haeas
:a the :eate: :eg:aa!
c------l: - l- -.:l .-
--:l -l l-- ------ -l
c------l: - l- ---l .-
:--l -l l-- ------
-l
c------l: - l- :--l-- -l -.l--- :.:- : |-l ---, .:- -- l- -.-- ---:--: |?oo ?oo - l: :--`
?oo -|:
?
o
o

-
|
:
w-- ]-- -l :---l-
- l- ---l -- :--l, l
--: .|| l- -.] .:--::
l- -.--, :- l- l-:
- l- -.:l .- --:l
---'l - .: l.|| .: l-]
---| - l- ---l .- :--l ----: ---- --l]
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
408 chapter 13
fIow Iayout
FlowLayout cares
about the how of the
components:
left to right, top to bottom, in
the order they were added.
import javax.swing.*;
import java.awt.*;
public class Panel1 {
public static void main (String[] args) {
Panel1 gui = new Panel1();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
frame.getContentPane().add(BorderLayout.EAST, panel);
frame.setSize(200,200);
frame.setVisible(true);
}
}

Let's add a panel to the east region:
1- .--| --:-'l .- .-]l-
- l, :- l --:-'l .: -- --:
-l - l- -.:l ----
A JPoneI's Ioyouf monoger is FIowLoyouf, by defouIf. When we odd
o poneI fo o frome, fhe si;e ond pIocemenf of fhe poneI is sfiII
under fhe 8orderLoyouf monoger's confroI. 8uf onyfhing inside fhe
poneI (in ofher words, componenfs odded fo fhe poneI by coIIing
panel.add(aComponent)) ore under fhe poneI's FIowLoyouf
monoger's confroI. We'II sforf by puffing on empfy poneI in fhe frome's
eosf region, ond on fhe nexf poges we'II odd fhings fo fhe poneI.
M.- l- .--| -.] :- -- :.- :--
---- l : -- l- -.--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 409
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(shock me);
panel.add(button);
frame.getContentPane().add(BorderLayout.EAST, panel);
frame.setSize(250,200);
frame.setVisible(true);
}
Let's add a button to the panel
A l- -ll-- l- l- .--| .- . l-
.--| l- l- -.-- 1- .--|': |.]--l -.-.--
||--` :--l--|: l- -ll--, .- l- -.--':
|.]--l -.-.-- |----` :--l--|: l- .--|
1- .--| -.--'
A- l- -ll-- -l l:
------ :-- - -l
---:--:, -:.-:- l- .--|
-:-: |-- |.]--l, .- l-
-ll-- : .-l - l- .--|
|--l l- -.--`
P
o
n
e
I ob
j
e
c
f

I hove o buffon now,
so my Ioyouf monoger's
gonno hove fo fgure ouf
how big I need fo be...
8
u
f
fon o
b
j
e
c
f

The frome's
orderLuyout monoger
8osed on my fonf si;e
ond fhe number of
chorocfers, I wonf fo be 70
pixeIs wide ond Z0 pixeIs foII.
Ok... I need fo
know how big fhe
puneI wonfs fo be...
The poneI's
FIowLuyout monoger
I need
fo know how big fhe
button wonfs fo
confroIs confroIs

.
-
-
|
.--|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
410 chapter 13
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(shock me);
JButton buttonTwo = new JButton(bliss);

panel.add(button);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.EAST, panel);
frame.setSize(250,200);
frame.setVisible(true);
}

What happens if we add TWO buttons
to the panel?
-
.- 1
w
6
-ll--:
. B61+ l- l- .--|
what we wanted: what we got:
w
- -.-l l- -ll--:
:l.:- -- l- - -.:
-l--
1- .--| -.-- l- l -l -ll--: :- ] :-
--l:- l.l l- '|::' -ll-- : :-.||-- l.-
l- ':-: --' -ll-- l.l': -- |--
|.]--l ---: 1
- -ll-- -l: -:l -.l l
---: |.- -- ----`
+,-+ :+ ,-+:.|
JButton button = new JButton(shock me);
JButton buttonTwo = new JButton(bliss);
JButton buttonThree = new JButton(huh?);
panel.add(button);
panel.add(buttonTwo);
panel.add(buttonThree);
|f the code above were modied to the code below,
what would the GU| look likeI
Draw what you
think the GU| would
look like if you ran
the code to the left.
(Then try it!)
fIow Iayout
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 411
BoxLayout to the rescuel
t keeps components
stacked, even if there's room
to put them side by side.
Unlike FlowLayout, BoxLayout can force a
new line' to make the components wrap to
the next line, even if there's room for them
to ht horizontally.
8uf now you'II hove fo chonge fhe poneI's Ioyouf monoger from fhe
defouIf FIowLoyouf fo 8oxLoyouf.
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

JButton button = new JButton(shock me);
JButton buttonTwo = new JButton(bliss);
panel.add(button);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.EAST, panel);
frame.setSize(250,200);
frame.setVisible(true);
}
c.-- l- |.]--l -.-.-- l- - . ---
-:l.-:- - B-|.]--l
1- B-|.]--l :--:l--:l-- ---: l- ---
l- :------l l: |.]- --l |-, l- .--|`
.- -: .: l- -:- |-- -:- /_Ax| -- .
--l:.| :l.:`
N-l:- -- l- .--| : -.------ ..-,
-:.-:- l --:-'l --- l- l -l -ll--:
-----l.||] - l- .--| l-| l- -.--
l ---- ---- ---- -- --|] l- |.--:l
-ll--, ':-: --'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
412 chapter 13
Iayout managers
(-,- a,- |
oa|| qa--(:|-
How come you can't add directIy to a frame the way
you can to a paneI!
A 1Prame is special because it's where the rubber
meets the road in making something appear on the screen.
while all your Swing components are pure 1ava, a 1Prame
has to connect to the underlying OS in order to access the
display. Think of the content pane as a l00% pure 1ava layer
that sits on to of the 1Prame. Or think of it as though 1Prame
is the window frame and the content pane is the... glass. ou
know, the window one. And you can even swo the content
pane with your own 1Panel, to make your 1Panel the frame's
content pane, using,
myFrame.setContentPane(myPanel);
Can I change the Iayout manager of the frame!
What if I want the frame to use ow instead of border!
The easiest way to do this is to make a panel, build
the GU| the way you want in the panel, and then make that
panel the frame's content pane using the code in the previ-
ous answer (rather than using the default content pane).

What if I want a different preferred size! Is there a
setSize() method for components!
es, there is a setSize(), but the layout managers will
ignore it. There's a distinction between the teletteJ s|ze of
the component and the size you want it to be. The preferred
size is based on the size the component actually neeJs
(the component makes that decision for itself ). The layout
manager calls the component's getPreferredSize() method,
and thot method doesn't cote if you've previously called
setSize() on the component.
Can't I just put things where I want them! Can I turn
the Iayout managers off!
ep. On a component by component basis, you can call
setLayout(null) and then it's up to you to hard-code
the exact screen locations and dimensions. |n the long run,
though, it's almost always easier to use layout managers.
8ll P0lk5
Layoul raraers corlro| l|e s|ze ard |ocal|or ol
corporerls resled W|l||r ol|er corporerls.
w|er you add a corporerl lo arol|er corporerl
(sorel|res relerred lo as a oaokgrouno corporerl,
oul l|al's rol a lec|r|ca| d|sl|rcl|or), l|e added
corporerl |s corlro||ed oy l|e |ayoul raraer ol l|e
oaokgrouno corporerl.
A |ayoul raraer as|s corporerls lor l|e|r
prelerred s|ze, oelore ra||r a dec|s|or aooul
l|e |ayoul. 0eperd|r or l|e |ayoul raraer's
po||c|es, |l r||l respecl a||, sore, or rore ol l|e
corporerl's W|s|es.
T|e 8orderLayoul raraer |els you add a
corporerl lo ore ol l|ve re|ors. You rusl spec|ly
l|e re|or W|er you add l|e corporerl, us|r l|e
lo||oW|r syrlax:
add(BorderLayout.EAST, panel);
w|l| 8orderLayoul, corporerls |r l|e rorl| ard
soul| el l|e|r prelerred |e||l, oul rol W|dl|.
Corporerls |r l|e easl ard Wesl el l|e|r prelerred
W|dl|, oul rol |e||l. T|e corporerl |r l|e cerler
els W|alever |s |ell over (ur|ess you use pack()).
T|e pac|() rel|od |s |||e s|r|r|-Wrap lor l|e
corporerls, |l uses l|e lu|| prelerred s|ze ol l|e
cerler corporerl, l|er delerr|res l|e s|ze ol l|e
lrare us|r l|e cerler as a slarl|r po|rl, ou||d|r
l|e resl oased or W|al's |r l|e ol|er re|ors.
F|oWLayoul p|aces corporerls |ell lo r||l, lop lo
oollor, |r l|e order l|ey Were added, Wrapp|r lo a
reW ||re ol corporerls or|y W|er l|e corporerls
Wor'l l|l |or|zorla||y.
F|oWLayoul |ves corporerls l|e|r prelerred s|ze |r
ool| d|rers|ors.
8oxLayoul |els you a||r corporerls slac|ed
verl|ca||y, ever |l l|ey cou|d l|l s|de-oy-s|de. L||e
F|oWLayoul, 8oxLayoul uses l|e prelerred s|ze ol
l|e corporerl |r ool| d|rers|ors.
8orderLayoul |s l|e delau|l |ayoul raraer lor a
lrare, F|oWLayoul |s l|e delau|l lor a pare|.
ll you Warl a pare| lo use sorel||r ol|er l|ar l|oW,
you |ave lo ca|| setLayout() or l|e pare|.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
using swing
you are here 413
||zy|n] w| !h 8w|n] rempencn!s
You`vc lcaincu ihc lasics ol layoui managcis, so now lci`s iiy oui a
lcw ol ihc mosi common comoncnis: a icxi hclu, sciolling icxi aica,
chccIlox, anu lisi. Wc won`i show you ihc wholc uain API loi cach ol
ihcsc, |usi a lcw highlighis io gci you siaiicu.
JTextField
Constructors
JTextField eld = new JTextField(20);
How to use it
0ef fexf ouf of if
System.out.println(eld.getText());
1
Puf fexf in if
eld.setText(whatever);
eld.setText();
2
0ef on AcfionEvenf when fhe user
presses refurn or enfer
eld.addActionListener(myActionListener);
3
/-- :.- .|:- --:l-- -- -] ---l: ]--
--.||] -.-l l- -.- .--l l ---] l-- l-
-:-- --::-: . -]
io --.-: io :-|---:, --l io -|:
1: ---: l- ------ -l -
l- l-l -|
JTextField eld = new JTextField(Your name);
SeIecf/HighIighf fhe fexf in fhe feId
eld.selectAll();
4
Puf fhe cursor bock in fhe feId (so fhe user
con jusf sforf fyping)
eld.requestFocus();
5
)1-l|-|
)
|
.

-
|
1: :|-.-: l- -|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
414 chapter 13
JTextArea
Constructor
JTextArea text = new JTextArea(10,20);
How to use it
Moke if hove o verficoI scroIIbor onIy
JScrollPane scroller = new JScrollPane(text);
text.setLineWrap(true);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
1
PepIoce fhe fexf fhof's in if
text.setText(Not all who are lost are wandering);
2
M
.- . ):--|||.-- .- - l l-
l-l .--. l.l l': -- l- ::--|| --
|o --.-: |o |--: |:-l: l- ------ -l`
SeIecf/HighIighf fhe fexf in fhe feId
text.selectAll();
4
Puf fhe cursor bock in fhe feId (so fhe user
con jusf sforf fyping)
text.requestFocus();
5
io --.-: io :-|---: |:-l: l- ------ -l`
UnIike JTexfFieId, JTexfAreo con hove more fhon one Iine of fexf. If
fokes o IiffIe confgurofion fo moke one, becouse if doesn'f come ouf of
fhe box wifh scroII bors or Iine wropping. To moke o JTexfAreo scroII, you
hove fo sfick if in o ScroIIPone. A ScroIIPone is on objecf fhof reoIIy Ioves
fo scroII, ond wiII foke core of fhe fexf oreo's scroIIing needs.
Append fo fhe fexf fhof's in if
text.append(button clicked);
3
1--- -- |-- --.-
1-|| l- ::--|| .-- l- -:- --|]
. --l:.| ::--||.-
|---l.-l'' /-- - l- l-l .--. l- l- ::--|| .-- |l--- l-
::--|| .-- :--:l--:l--`, l-- . l- ::--|| .-- l- l- .--| /--
--'l . l- l-l .--. --:l|] l- l- .--|'
text area
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 415
JTextArea example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TextArea1 implements ActionListener {
JTextArea text;
public static void main (String[] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton(Just Click It);
button.addActionListener(this);
text = new JTextArea(10,20);
text.setLineWrap(true);

JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

panel.add(scroller);

frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.SOUTH, button);

frame.setSize(350,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ev) {
text.append(button clicked \n );
}
}

|-:--l . --- |-- :- l- ---: - -- . :-.-.l- |-- -.: l-- l- -ll-- : :|:- 6l---:-, l-]'|| --- l--l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
416 chapter 13
JCheckBox
Constructor
JCheckBox check = new JCheckBox(Goes to 11);
How to use it
Lisfen for on ifem evenf (when if's seIecfed or deseIecfed)
check.addItemListener(this);
1
HondIe fhe evenf (ond fnd ouf whefher or nof if's seIecfed)
public void itemStateChanged(ItemEvent ev) {
String onOrOff = off;
if (check.isSelected()) onOrOff = on;
System.out.println(Check box is + onOrOff);
}
2
SeIecf or deseIecf if in code
check.setSelected(true);
check.setSelected(false);
3
check box
(-,- a,- |
oa|| qa--(:|-

Aren't the Iayout manag-
ers just more troubIe than they're
worth! If I have to go to aII this
troubIe, I might as weII just hard-
code the size and coordinates for
where everything shouId go.
Getting the exact layout
you want from a layout man-
ager can be a challenge. 8ut think
about what the layout manager
is really doing for you. Lven the
seemingly simple task of figuring
out where things should go on
the screen can be complex. Por
example, the layout manager takes
care of keeping your components
from overlapping one another.
|n other words, it knows how to
manage the spacing between
components (and between the
edge of the frame). Sure you can
do that yourself, but what happens
if you want components to be
very tightly packedI ou might get
them placed |ust right, by hand,
but that's only good for your 1vM!
whyI 8ecause the components
can be slightly different from
platform to platform, especially if
they use the underlying platform's
native 'look and feel'. Subtle things
like the bevel of the buttons can
be different in such a way that
components that line up neatly
on one platform suddenly squish
together on another.
And we're still not at the really 8ig
Thing that layout managers do.
Think about what happens when
the user resizes the window! Or
your GU| is dynamic, where com-
ponents come and go. |f you had
to keep track of re-laying out all
the components every time there's
a change in the size or contents of
a background component...yikes!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 417
JList
Constructor
String [] listEntries = {alpha, beta, gamma, delta,
epsilon, zeta, eta, theta };
list = new JList(listEntries);
How to use it
Moke if hove o verficoI scroIIbor
JScrollPane scroller = new JScrollPane(list);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
1
Pesfricf fhe user fo seIecfing onIy OME fhing of o fime
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
3
Pegisfer for Iisf seIecfion evenfs
list.addListSelectionListener(this);
4
HondIe evenfs (fnd ouf which fhing in fhe Iisf wos seIecfed)
public void valueChanged(ListSelectionEvent lse) {
if( !lse.getValueIsAdjusting()) {
String selection = (String) list.getSelectedValue();
System.out.println(selection);
}
}
5
Sef fhe number of Iines fo show before scroIIing
list.setVisibleRowCount(4);
2
1: : -:l |- -l )1-lA--. ~~ ]-- -.- .
):--|||.-- |.- - l l- |:l`, l-- . l-
::--|| .-- |N61 l- |:l` l- l- .--|
/--'|| -l l- ---l 1w|c! ]-- --'l
-l - l: l-:l
-l-|-:l-/.|--|` .:l-.||]
--l---: .- 6-:l A |:l :-'l
|-l- l- --|] l-- --:l:
)|:l :--:l--:l-- l.-: .- .--.] - .-] --:l
l]- 1-] --'l .- l- - l--:, -l .
l-- ----:--l.l-- -|| .-.- - l- |:l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
418 chapter 13
CaJe kit:hea
This a:t's atiaaa|. he':e a|iag the Ia|| 5eat5ax, 6l!
aaJ a||. !a the Saviag 0le:ts :hate:, ve'|| |ea:a hav ta
save aaJ :esta:e J:a atte:as. Iiaa||y, ia the aetva:|iag
:hate: lKa|e a Caaae:tiaaI, ve'|| ta:a the 5eat5ax iata a
va:|iag :hat :|ieat.
Code Kitchen
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 419
This is ihc lull couc lisiing loi ihis vcision ol ihc BcaiBox, wiih luiions loi siaiiing,
sioing, anu changing ihc icmo. Thc couc lisiing is comlcic, anu lully-
annoiaicu, lui hcic`s ihc ovcivicw:
Mzk|n] !hc Bcz!Ber
1
2
3
4
8uiId o 0UI fhof hos Zbo checkboxes (JCheck8ox) fhof sforf ouf
unchecked, Io IobeIs (JLobeI) for fhe insfrumenf nomes, ond four
buffons.
Pegisfer on AcfionLisfener for eoch of fhe four buffons. We don'f
need Iisfeners for fhe individuoI checkboxes, becouse we oren'f
frying fo chonge fhe poffern sound dynomicoIIy (i.e. os soon os fhe
user checks o box). Insfeod, we woif unfiI fhe user hifs fhe 'sforf'
buffon, ond fhen woIk fhrough oII Zbo checkboxes fo gef fheir sfofe
ond moke o MIDI frock.
Sef-up fhe MIDI sysfem (you've done fhis before) incIuding geffing
o Sequencer, moking o Sequence, ond creofing o frock. We ore using
o sequencer mefhod fhof's new fo Jovo b.0, sefLoopCounf( ). This
mefhod oIIows you fo specify how mony fimes you wonf o sequence
fo Ioop. We're oIso using fhe sequence's fempo focfor fo odjusf fhe
fempo up or down, ond moinfoin fhe new fempo from one iferofion of
fhe Ioop fo fhe nexf.
When fhe user hifs 'sforf', fhe reoI ocfion begins. The evenf-hondIing
mefhod for fhe 'sforf' buffon coIIs fhe buiIdTrockAndSforf() mefhod.
In fhof mefhod, we woIk fhrough oII Zbo checkboxes (one row of
o fime, o singIe insfrumenf ocross oII Io beofs) fo gef fheir sfofe,
fhen use fhe informofion fo buiId o MIDI frock (using fhe hondy
mokeEvenf() mefhod we used in fhe previous chopfer). Once fhe frock
is buiIf, we sforf fhe sequencer, which keeps pIoying (becouse we're
Iooping if) unfiI fhe user hifs 'sfop'.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
420 chapter 13
import java.awt.*;
import javax.swing.*;
import javax.sound.midi.*;
import java.util.*;
import java.awt.event.*;
public class BeatBox {
JPanel mainPanel;
ArrayList<JCheckBox> checkboxList;
Sequencer sequencer;
Sequence sequence;
Track track;
JFrame theFrame;
String[] instrumentNames = {Bass Drum, Closed Hi-Hat,
Open Hi-Hat,Acoustic Snare, Crash Cymbal, Hand Clap,
High Tom, Hi Bongo, Maracas, Whistle, Low Conga,
Cowbell, Vibraslap, Low-mid Tom, High Agogo,
Open Hi Conga};
int[] instruments = {35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63};

public static void main (String[] args) {
new BeatBox2().buildGUI();
}

public void buildGUI() {
theFrame = new JFrame(Cyber BeatBox);
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout layout = new BorderLayout();
JPanel background = new JPanel(layout);
background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
checkboxList = new ArrayList<JCheckBox>();
Box buttonBox = new Box(BoxLayout.Y_AXIS);
JButton start = new JButton(Start);
start.addActionListener(new MyStartListener());
buttonBox.add(start);

JButton stop = new JButton(Stop);
stop.addActionListener(new MyStopListener());
buttonBox.add(stop);
JButton upTempo = new JButton(Tempo Up);
upTempo.addActionListener(new MyUpTempoListener());
buttonBox.add(upTempo);
JButton downTempo = new JButton(Tempo Down);
BeatBox code
w- :l--- l- :-:--: - .- A--.]|:l
1-:- .-- l- -.--: - l- -:l-----l:, .: . l--
.--.], -- -|- l- 6c| |.-|: |-- -.: ---`
1-:- ----:--l l- .:l-.| --- '-]:'
1- --- :.---| : |- . .--, -:-l
-.: '-]' -- l- .-- : . ----l ---
- l- ----- '?-' : l- -] -- l- B.::
---, +i : c|-:- +~+.l, -l:
N-l- :-:.| ---, -:l |-l: - 6c|
:-- /--'- :--- --:l - l ----
A- '--l] ----' -: -: . -.-- -l---- l- --: - l- .--| .- ---- l- :------l: .-- |.:-
|---|] .-:l-l:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 421
downTempo.addActionListener(new MyDownTempoListener());
buttonBox.add(downTempo);
Box nameBox = new Box(BoxLayout.Y_AXIS);
for (int i = 0; i < 16; i++) {
nameBox.add(new Label(instrumentNames[i]));
}

background.add(BorderLayout.EAST, buttonBox);
background.add(BorderLayout.WEST, nameBox);
theFrame.getContentPane().add(background);

GridLayout grid = new GridLayout(16,16);
grid.setVgap(1);
grid.setHgap(2);
mainPanel = new JPanel(grid);
background.add(BorderLayout.CENTER, mainPanel);
for (int i = 0; i < 256; i++) {
JCheckBox c = new JCheckBox();
c.setSelected(false);
checkboxList.add(c);
mainPanel.add(c);
} // end loop
setUpMidi();
theFrame.setBounds(50,50,300,300);
theFrame.pack();
theFrame.setVisible(true);
} // close method
public void setUpMidi() {
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequence = new Sequence(Sequence.PPQ,4);
track = sequence.createTrack();
sequencer.setTempoInBPM(120);

} catch(Exception e) {e.printStackTrace();}
} // close method
l|| ---- 6c| :-l~- :--
N-l- ---.-.|-
M.- l- :-:--:, :-l l-- l-
'.|:-' |:- l-] .---'l :-:-` .-
. l-- l- l- A--.]|:l ANl l-
l- 6c| .--|
1- -:-.| M|l| :-l~- :l- --
-ll- l- ----:--, l- ----:-,
.- l- 1-.: A.-, --l- :-:.|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
422 chapter 13
public void buildTrackAndStart() {
int[] trackList = null;

sequence.deleteTrack(track);
track = sequence.createTrack();
for (int i = 0; i < 16; i++) {
trackList = new int[16];

int key = instruments[i];
for (int j = 0; j < 16; j++ ) {

JCheckBox jc = (JCheckBox) checkboxList.get(j + (16*i));
if ( jc.isSelected()) {
trackList[j] = key;
} else {
trackList[j] = 0;
}
} // close inner loop


makeTracks(trackList);
track.add(makeEvent(176,1,127,0,16));
} // close outer
track.add(makeEvent(192,9,1,0,15));
try {

sequencer.setSequence(sequence);
sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY);
sequencer.start();
sequencer.setTempoInBPM(120);
} catch(Exception e) {e.printStackTrace();}
} // close buildTrackAndStart method


public class MyStartListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
buildTrackAndStart();
}
} // close inner class
w-'|| -.- . ||~-|----l .--.] l- -| l- .|--: --
--- -:l-----l, .:--:: .|| || -.l: | l- -:l-----l :
:--:- l- |.] -- l.l -.l, l- .|-- .l l.l -|----l
-|| - l- -] | l.l -:l-----l : N61 :--:- l-
|.] -- l.l -.l, -l - . ----
|: l- :-:- .l l: -.l :-|-:l- | ]-:, -l
l- -] .|-- - l: :|-l - l- .--.] |l- :|-l l.l
----:--l: l: -.l` 6l---:-, l- -:l-----l :
N61 :--:- l- |.] .l l: -.l, :- :-l l l- ----
- l: -- -.: - l- || 6w |- B.::, c---, -l:`
-l l- '-]' l.l ----:--l: -: -:l-----l l:
: |B.::, +~+.l, -l: 1- -:l-----l: .--.] -|: l-
.:l-.| M|l| -----: -- -.: -:l-----l`
N6w ||A/ 1+! 1+|N6''
|-:l - l- ---- :|.::-:,
|:l----: -- l- -ll--:
N-l- :-:.| ---
1: : ---- l .|| .--:' w--- --
l--- :-:- :l.l- -l- M|l| ---l:,
.- . l-- l- l- 1-.:
BeatBox code
l- l: -- -.: - l- B!A1 -- l: ---
|-- l: -:l-----l, .- -- .|| || -.l:,
-.- ---l: .- . l-- l- l- l-.:
w- .|-.]: -.-l l- -.- :--- l.l l--- | .- ---l .l
-.l || |l --: o l- |-` 6l---:-, l- B-.lB- -l
--l - l- -|| || -.l: ---- l :l.-l: ---
-l - - l- -| l-.:, -.- . --: ---
|-l': ]-- :-:] l- -----
- |-- l--.l--:, -- - l:
:.:-, :--l----: |---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
using swing
you are here 423
public class MyStopListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
sequencer.stop();
}
} // close inner class
public class MyUpTempoListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
oat tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((oat)(tempoFactor * 1.03));
}
} // close inner class
public class MyDownTempoListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
oat tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((oat)(tempoFactor * .97));
}
} // close inner class


public void makeTracks(int[] list) {

for (int i = 0; i < 16; i++) {
int key = list[i];
if (key != 0) {
track.add(makeEvent(144,9,key, 100, i));
track.add(makeEvent(128,9,key, 100, i+1));
}
}
}

public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);
} catch(Exception e) {e.printStackTrace(); }
return event;
}
} // close class
1- -l-- ---- :|.::
|:l----: -- l- -ll--:
M.- l- N61! 6N .-
N61 6|| ---l:, .-
. l-- l- l- 1-.:
1: : l- -l|l] --l- --- |.:l
:.l--': c--rl:-- N-l- ---
1: -.-: ---l: -- --- -:l-----l .l . l--, --
.|| || -.l: - l -l -l .- -l| 1 -- l- B.::
---, .- -.: -- - l- .--.] -|| -| -l--
l- -] - l.l -:l-----l, -- . ---- | l': . ----,
l- -:l-----l :-'l :--:- l- |.] .l l.l -.l
6l---:-, -.- .- ---l .- . l l- l- l-.:
1- 1--- |.:l-- ::.|-:
l- :----:--': l--- ]
l- .:l-- --- 1-
-.-|l : |o, :- --'--
.-:l- +/~ ?* --
:|:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
424 chapter 13

y[je[ e] g, wj([
w[je[ ]zya(/
Five of the six screens below were made from one
of the code fragments on the opposite page. Match
each of the fve code fragments with the layout that
fragment would produce.
exercise: Which Layout?
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 425
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
frame.getContentPane().add(BorderLayout.NORTH,panel);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.CENTER,button);

JFrame frame = new JFrame();


JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.CENTER,button);
frame.getContentPane().add(BorderLayout.EAST, panel);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.CENTER,button);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
panel.add(button);
frame.getContentPane().add(BorderLayout.NORTH,buttonTwo);
frame.getContentPane().add(BorderLayout.EAST, panel);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
frame.getContentPane().add(BorderLayout.SOUTH,panel);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.NORTH,button);

(] Jzgn(,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
426 chapter 13
(([(iss ).c
ou can do it.

2. Swing's dad
3. Prame's purview
5. Help's home
6. More fun than text
7. Component slang
8. Pomulin command
9. Arrange
l0. 8order's top

l. Artist's sandbox
4. 8order's catchall
5. 1ava look
9. Generic waiter
ll. A happening
l2. Apply a widget
l5. 1Panel's default
l6. Polymorphic test
l7. Shake it baby
2l. Lots to say
23. Choose many
25. 8utton's pal
26. Home of
actionPerformed
l3. Manager's rules
l4. Source's behavior
l5. 8order by default
l8. User's behavior
l9. |nner's squeeze
20. 8ackstage widget
22. Mac look
24. 8order's right
l 2
l5
l7
24
l8 l9
l0
25
5
ll
4
9
22
26
l6
l2
2l
23
8
3
6
l4
l3
7
20
puzzIe: crossword
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 427
1

B
4
B
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.CENTER,button);
frame.getContentPane().add(BorderLayout.EAST, panel);
B
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.CENTER,button);
0
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
panel.add(button);
frame.getContentPane().add(BorderLayout.NORTH,buttonTwo);
frame.getContentPane().add(BorderLayout.EAST, panel);
A
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
frame.getContentPane().add(BorderLayout.SOUTH,panel);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.NORTH,button);
B
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
frame.getContentPane().add(BorderLayout.NORTH,panel);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.CENTER,button);
D
[yej, ]a(jn,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
428 chapter 13
(([(iss ).c
l 2
l5
l7
24
l8 l9
l0
25
5
ll
4
9
22
26
l6
l2
2l
23
8
3
6
l4
l3
7
20
]arr[c nsacis
D P A W P A M E L S
W C E M T E P
M E T A L T 0 W
S E L I S T E M E P I
E V E M T A I O A D D
T U P Y Z P P 0
V C F L O W O E T H E
I S A P L U H I T
S L A M I M A T I O M C
I L M C C U P
8 8 E Y T E X T A P E A A
L A I E Q M
E C H E C I 8 O X P U E
I A M L A 8 E L
S
A C T I O M L I S T E M E P
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 429
14 seriaIization and fiIe I/O
Objects can be fIattened and infIated. Ob|ects have state and behavior.
8ehov|ot lives in the closs, but stote lives within each individual ooject. So what happens when
it's time to sove the state of an ob|ectI |f you're writing a game, you're gonna need a Save/
Pestore Game feature. |f you're writing an app that creates charts, you're gonna need a Save/
Open Pile feature. |f your program needs to save state, you con Jo |t the hotJ woy, interrogating
each ob|ect, then painstakingly writing the value of each instance variable to a file, in a
format you create. Or, you can do it the easy DD wayyou simply freeze-dry/flatten/persist/
dehydrate the ob|ect itself, and reconstitute/inflate/restore/rehydrate it to get it back. 8ut you'll
still have to do it the hard way somet|mes, especially when the file your app saves has to be read
by some other non-1ava application, so we'll look at both in this chapter.
If I hove fo reod
one more fIe fuII of
dofo, I fhink I'II hove fo kiII him. He
knows I con sove whoIe objecfs, buf
does he Ief me7 , fhof wouId be
foo eosy. WeII, we'II jusf see how
he feeIs offer I...
8aving Ob]ects
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
430 chapter 14
You`vc nJe ihc cilcci aiicin. You wani io n.e ihc aiicin.
You coulu gial a iccc ol aci anu siaii sciillling ii uown, lui
insicau you hii ihc luiion oi choosc Savc liom ihc Iilc
mcnu). Thcn you givc ii a namc, icI a uiiccioiy,
anu cxhalc Inowing ihai youi masiciiccc won`i go
oui ihc winuow wiih ihc lluc sciccn ol ucaih.
You havc lois ol oiions loi how io savc ihc siaic ol
youi ]ava iogiam, anu whai you choosc will iolally
uccnu on how you lan io ue ihc savcu siaic. Hcic
aic ihc oiions wc`ll lc looIing ai in ihis chaici.
saving objects
0zp!erc !hc Bcz!
Use seriuIizution
Wrife o fIe fhof hoIds offened (serioIi;ed)
objecfs. Then hove your progrom reod fhe
serioIi;ed objecfs from fhe fIe ond inofe fhem
bock info Iiving, breofhing, heop-inhobifing objecfs.
1
f your data will be used by only the Java
program that generated it:
Thcsc aicn`i ihc only oiions, ol couisc. You can savc uaia in any
loimai you choosc. Insicau ol wiiiing chaiacicis, loi cxamlc,
you can wiiic youi uaia as lyics. Oi you can wiiic oui any Iinu
ol ]ava iimiiivc n a ]ava iimiiivc-ihcic aic mcihous io wiiic
inis, longs, loolcans, cic. Bui icgaiulcss ol ihc mcihou you usc,
ihc lunuamcnial I/O icchniqucs aic iciiy much ihc samc:
wiiic somc uaia io oeL.r, anu usually ihai somcihing is ciihci
a hlc on uisI oi a siicam coming liom a nciwoiI conncciion.
Rcauing ihc uaia is ihc samc ioccss in icvcisc: icau somc uaia
liom ciihci a hlc on uisI oi a nciwoiI conncciion. Anu ol couisc
cvciyihing wc ialI aloui in ihis aii is loi iimcs whcn you aicn`i
using an aciual uaialasc.
f your data will be used by other programs:
Write u pIuin tet h Ie
Wrife o fIe, wifh deIimifers fhof ofher progroms con porse.
For exompIe, o fob-deIimifed fIe fhof o spreodsheef or
dofobose oppIicofion con use.
2
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 431
Opfion fwo
Write u pIuin tet h Ie
Creofe o fIe ond wrife fhree Iines of fexf,
one per chorocfer, seporofing fhe pieces
of sfofe wifh commos:
S0,BIt,bcw, swcrd,dust
B00,TrcII,bare hands,bIg ax
1B0,magIcIan,speIIs,InvIsIbIIIty
2
1- :--.|-- |- : --: .--- -- --.-: l- --.,
-l l': --: -.:-- |.- :.--` -- ]--- ---.- l-
--:l--- l- l--- --:l: --- :--.|-.l-- l.- ---
--.- - l- --:l': .-.|- .|--: l.l ---- :.-
l- . l-l |- |-- -.-|-, -.-- .|| l- -.]: - -:
]-- :--| .::--l.||] --. .: l- .|--: - l- ----
----' 1- l]- -l -:--- -:l' -:l-. - !|',
-|- l- !| -:---: . --.--
!
ag:ae yaa
h
ave th
:ee ga
e
:h
a:a:te:s ta save...
8zv|n] 8!z!c
Imaginc you havc a iogiam, say, a laniasy
auvcniuic gamc, ihai iaIcs moic ihan onc
scssion io comlcic. As ihc gamc iogicsscs,
chaiacicis in ihc gamc lccomc siiongci, wcaIci,
smaiici, cic., anu gaihci anu usc anu losc)
wcaons. You uon`i wani io siaii liom sciaich
cach iimc you launch ihc gamc-ii iooI you
loicvci io gci youi chaiacicis in io shac loi
a scciaculai laiilc. So, you nccu a way io savc
ihc siaic ol ihc chaiacicis, anu a way io icsioic
ihc siaic whcn you icsumc ihc gamc. Anu sincc
you`ic also ihc gamc iogiammci, you wani ihc
wholc savc anu icsioic ihing io lc as casy anu
looliool) as ossillc.
Came6haracter
|rl poWer
3lr|r lype
weapor[| Weapors
elweapor()
useweapor()
|rcreasePoWer()
// rore

o
bjec
f

---- -o
l]- !|
--.--: --,
:---, -:l
Opfion one
Write the three seriuIized
churucter objects to u h Ie
Creofe o fIe ond wrife fhree serioIi;ed
chorocfer objecfs. The fIe won'f moke
sense if you fry fo reod if os fexf:
1sr0ame0haracter
%gSmU1pcwerLjavaIang
StrIngweapcnstLjavaIang
StrIngxpBtIturLjava.Iang.StrIng="VA
B(0xptbcwtswcrdtdustsgtTrcIIugtb
are handstbIg axsgxtmagIcIanugtspe
IIstInvIsIbIIIty
1
---- ioo
l]- 1--||
--.--: .--
.-:, .
---- |io
l]- M.:.-
--.--: :-||:,
-:|l]

o
bjec
f


o
bjec
f

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
saving objects
432 chapter 14
Hcic aic ihc sics loi sciializing saving) an ol|cci. Don`i loihci
mcmoiizing all ihis, wc`ll go inio moic uciail laici in ihis chaici.
Wr| !|n] z scr|z||zc4 e|jcr! !e z f||c
FileOutputStream leStream = new FileOutputStream(MyGame.ser);
M
.- . ||-6-l-ll--.- --:l ||-6-l-ll--.-
---: -- l- :----:l l- |.- :--.l-` . |-

Muke u FiIeOutputStreum
os.writeObject(characterOne);
os.writeObject(characterTwo);
os.writeObject(characterThree);

Write the object


os.close();

CIose the ObjectOutputStreum


:--.|--: l- --:l: ------:- ] :.-.:l--~
6--, :.-.:l--1--, .- :.-.:l--1---, .-
--l-: l-- l- l- |- M]6.--:--'
c|-:- l- :l--.- .l l- l- :|-:-: l- ---:
------.l, :- l- ||-6-l-ll--.- |.- l-
|-` -|| :|-:- .-l--.l:.||]
| l- |- M]6.--:--' --:-'l
-:l, l -|| - :--.l- .-l--.l:.||]
ObjectOutputStream os = new ObjectOutputStream(leStream);

Muke un ObjectOutputStreum
6-:l6-l-ll--.- |-l: ]-- --l- --:l:,
-l l :.-'l --:l|] :----:l l- . |- |l
---: l- - - . '-|--' 1: : .:l-.||]
:.||- ':.--' --- :l--.- l- .--l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
seriaIization and fiIe I/O
you are here 433
Thc ]ava I/O API has connection siicams, ihai icicscni conncciions io ucsiinaiions anu
souiccs such as hlcs oi nciwoiI socIcis, anu choin siicams ihai woiI only il chaincu io
oihci siicams.
Olicn, ii iaIcs ai lcasi iwo siicams hooIcu iogcihci io uo somcihing usclul-ore io
icicscni ihc conncciion anu nroLe. io call mcihous on. Why iwo. Bccausc orre.or
siicams aic usually ioo low-lcvcl. IilcOuiuiSiicam a conncciion siicam), loi cxamlc,
has mcihous loi wiiiing b,e. Bui wc uon`i wani io wiiic b,e! Wc wani io wiiic obe, so
wc nccu a highci-lcvcl Ln.r siicam.
OK, ihcn why noi havc |usi a singlc siicam ihai uocs e:nI, whai you wani. Onc ihai lcis
you wiiic ol|ccis lui unucincaih convciis ihcm io lyics. ThinI goou OO. Each class
uocs ore ihing wcll. IilcOuiuiSiicams wiiic lyics io a hlc. Ol|cciOuiuiSiicams iuin
ol|ccis inio uaia ihai can lc wiiiicn io a siicam. So wc maIc a IilcOuiuiSiicam ihai lcis
us wiiic io a hlc, anu wc hooI an Ol|cciOuiuiSiicam a chain siicam) on ihc cnu ol ii.
Whcn wc call wiiicOl|cci) on ihc Ol|cciOuiuiSiicam, ihc ol|cci gcis umcu inio ihc
siicam anu ihcn movcs io ihc IilcOuiuiSiicam whcic ii uliimaicly gcis wiiiicn as lyics
io a hlc.
Thc aliliiy io mix anu maich uillcicni comlinaiions ol conncciion anu chain siicams
givcs you iicmcnuous ucxililiiy! Il you wcic loiccu io usc only a .rIe siicam class, you`u
lc ai ihc mcicy ol ihc API ucsigncis, hoing ihcy`u ihoughi ol e.e.,L.r you mighi cvci
wani io uo. Bui wiih chaining, you can aich iogcihci youi own uo chains.
Pz!z mevcs |n s!rczms frem enc p|zrc !e zne!hcr.
---.
D.::.-+:.--
Objecf
ObjecfOufpufSfreom
(o choin sfreom)
is wriffen fo
objecf is offened (serioIi;ed)
FiIeOufpufSfreom
(o connecfion sfreom)
0II0I00I0II0III00I
objecf is wriffen os byfes fo
0II0I00I
0II0III0
0I
FiIe

0enncr!|en
s!rczms rcprcscn!
z renncr!|en
!e z seerrc er
4cs!|nz!|en |f||c,
serkc!, c!r.I wh||c
rhz|n s!rczms
rzn! renncr! en
!hc|r ewn zn4 mes!
|c rhz|nc4 !e z
renncr!|en s!rczm.
is choined fo
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
434 chapter 14
Objecfs on fhe heop hove sfofe-fhe
voIue of fhe objecf's insfonce
voriobIes. These voIues moke one
insfonce of o cIoss differenf from
onofher insfonce of fhe some cIoss.
Whz! rcz||y hzppcns !e zn e|jcr!
whcn | !s scr|z||zc4!
Foo myFoo = new Foo();
myFoo.setWidth(37);
myFoo.setHeight(70);
FileOutputStream fs = new FileOutputStream(foo.ser);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(myFoo);
Ob]ect on the heap Ob]ect serialized
seriaIized objects
0
0
I
0
0
I
0
I
widfh
0
I
0
0
0
I
I
0
heighf
00I00I0I
0I000II0
SerioIi;ed objecfs suve the vuIues
of the instunce vuriubIes, so fhof
on idenficoI insfonce (objecf) con be
broughf bock fo Iife on fhe heop.
1- -:l.-:- .-.|- .|--:
-- -l .- -l .--
:.- l- l- |- --:--',
.|-- -l . |ll|- ---- --
l- )/M ---: l- --:l---
l- --:l ||- -.l l:
:|.:: l]- :` foo.ser
6
-:l -
l l-
- --
l-
-:l.-:- .-.|-:
1- .|--: .-- :-:-
--l .- --- -l-
l- :l--.-
M.- . ||-6-l-ll--.- l.l :----:l:
l- l- |- --:--', l-- :.- .-
6-:l6-l-ll--.- l- l, .- l-|| l-
6-:l6-l-ll--.- l- --l- l- --:l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 435
Be! whz! crzr!|y |8 zn e|jcr!s s!z!c!
Whz! ncc4s !e |c szvc4!
Now ii siaiis io gci inicicsiing. Easy cnough io savc ihc .....e
valucs S7 anu 70. Bui whai il an ol|cci has an insiancc vaiiallc
ihai`s an ol|cci .ee.ere. Whai aloui an ol|cci ihai has hvc
insiancc vaiiallcs ihai aic ol|cci iclcicnccs. Whai il ihosc ol|cci
insiancc vaiiallcs ihcmsclvcs havc insiancc vaiiallcs.
ThinI aloui ii. Whai aii ol an ol|cci is oicniially uniquc.
Imaginc whai nccus io lc icsioicu in oiuci io gci an ol|cci ihai`s
iucniical io ihc onc ihai was savcu. Ii will havc a uillcicni mcmoiy
locaiion, ol couisc, lui wc uon`i caic aloui ihai. All wc caic aloui
is ihai oui ihcic on ihc hca, wc`ll gci an ol|cci ihai has ihc samc
siaic ihc ol|cci hau whcn ii was savcu.
Engine

Tire []

T
i
r
e

[
]
orro
y
o
b
j
e
c
f

E
n
g
i
n
e ob
j
e
c
f

C
o
r
obj
e
c
f

The Car ob]ect has two
instance variables that
reference two other
ob]ects.

8f8l 88f00ll
what has to happen for the Car
ob|ect to be saved in such a way
that it can be restored back to its
original stateI
Think of whatand howyou
might need to save the Car.
And what happens if an Lngine
ob|ect has a reference to a
CarburatorI And what's inside the
Tire || array ob|ectI
What does it take to
save a Car ob]ect?
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
436 chapter 14
When an ob]ect is serialized, all the ob]ects
it refers to from instance variables are also
serialized. And all the ob]ects those ob]ects
refer to are serialized. And all the ob]ects those
ob]ects refer to are serialized... and the best
part is, it happens automaticallyl
Dog
leel
Dog
|erl
C
o
I
I
o
r
ob
j
e
c
f

S
f
r
i
n
g o
b
j
e
c
f

D
o
g
[

] orro
y
o
b
j
e
c
f

inf
Sfring
reme
CoIIor
tel
D
o
g
ob
j
e
c
f

:ite
"Fido"
C
o
I
I
o
r
ob
j
e
c
f

S
f
r
i
n
g o
b
j
e
c
f

inf
Sfring
reme
CoIIor
tel
D
o
g
ob
j
e
c
f

:ite
"Spike"
This IenneI objecf hos o reference fo o Dog [] orroy objecf. The
Dog [] hoIds references fo fwo Dog objecfs. Eoch Dog objecf hoIds
o reference fo o Sfring ond o CoIIor objecf. The Sfring objecfs
hove o coIIecfion of chorocfers ond fhe CoIIor objecfs hove on inf.
When you suve the kenneI uII of this is suved|
I
e
n
n
eI o
b
j
e
c
f

Dog [ ]
iej:
Se::a|:zat:aa saves the
eat::e ale:t g:ah.
A|| ale:ts :eIe:ea:eJ
ly :astaa:e va::al|es,
sta:t:ag v:th the
ale:t le:ag se::a|:zeJ.
seriaIized objects
!
--]l
- .: l
-
- :.-
- --
-- l
-
--:l
--- l
- r
----| .:
l
- l
: :l
.l
-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 437
|f yee wzn! yeer r|zss !e |c scr|z||zz||c,
|mp|cmcn! 8cr|z||zz||c
Thc Sciializallc inicilacc is Inown as a n.Ie. oi n inicilacc,
lccausc ihc inicilacc uocsn`i havc any mcihous io imlcmcni. Iis
solc uiosc is io announcc ihai ihc class imlcmcniing ii is, wcll,
e..nI..nbIe. In oihci woius, ol|ccis ol ihai iyc aic savcallc ihiough
ihc sciializaiion mcchanism. Il any suciclass ol a class is sciializallc,
ihc sulclass is auiomaiically sciializallc cvcn il ihc sulclass uocsn`i
cxliciily ucclaic .Ieer Se..nI..nbIe. This is how inicilaccs always
wo.I. Il youi suciclass IS-A" Sciializallc, you aic ioo).
objectOutputStream.writeObject(myBox);
w
.l--- --: --- M
c1
-|----l
--.|-.|- -- l -|| .| .l ---l--
import java.io.*;
public class Box implements Serializable {

private int width;
private int height;
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
public static void main (String[] args) {
Box myBox = new Box();
myBox.setWidth(50);
myBox.setHeight(20);
try {
FileOutputStream fs = new FileOutputStream(foo.ser);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(myBox);
os.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
--.|-.|- : - l- ..- .:.-, :-
]-- --- l- ---l
N- --l-: l- -|----l, -l --- ]-- :.]
-|----l: --.|-.|-', l :.]: l- l- )/M,
l': 6r l- :--.|-- --:l: - l: l]-'
|/6 ---.l--: :.- l--- -:-l--:
l-:- l-- .|--: -|| - :.-
c----:l l- . |- -.-- --:--'
l -:l: | l --:-'l, -.- .
--- |- -.-- --:--'
M
.- .- 6-:l6-l-ll--.-
:.-- l- l- :----:l-- :l--.- 1-|| l l- --l- l- --:l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
438 chapter 14
seriaIized objects
8erialization is all or nothing.
Can you imagine what would
happen if some of the ob]ect's
state didn't save correctly?
Either the entire
ob]ect graph is
serialized correctly
or serialization fails.
You can't serialize
a Pond ob]ect if
its Duck instance
variable refuses to
be serialized {by
not implementing
8erializable}.
Eeewwwl Thof
creeps me ouf jusf fhinking
obouf ifl Like, whof if o Dog comes
bock wifh no weighf. Or no eors. Or
fhe coIIor comes bock si;e 3 insfeod
of 30. Thof jusf con'f be oIIowedl
import java.io.*;
public class Pond implements Serializable {
private Duck duck = new Duck();
public static void main (String[] args) {
Pond myPond = new Pond();
try {
FileOutputStream fs = new FileOutputStream(Pond.ser);
ObjectOutputStream os = new ObjectOutputStream(fs);

os.writeObject(myPond);
os.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
c|.:: |-- .: --- -:l.-:-
.-.|-, . l-:
w-- ]-- :--.|-- -]|-- |. |-- --:l`, l: l-: -:l.-:- .-.|- .-l--.l:.||] -l: :--.|--
public class Duck {
// duck code here
}
/-:'' l-: : --l :--.|-.|-'
|l --:-'l -|----l --.|-.|-,
:- --- ]-- l-] l- :--.|-- .
|-- --:l, l .|: -:.-:- l-
|--': l-: -:l.-:- .-.|-
:.-'l - :.-
|-- --:l: :.- - :--.|--
File Edit Window Help Regret
% java Pond
java.io.NotSerializableException: Duck
at Pond.main(Pond.java:13)
w-- ]-- l-] l- --- l- -.- - :|.:: |--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 439
Mark an instance variable as transient
if it can't {or shouldn't} be saved.
Il you wani an insiancc vaiiallc io lc sIicu ly ihc
sciializaiion ioccss, maiI ihc vaiiallc wiih ihc transient
Icywoiu.
import java.net.*;
class Chat implements Serializable {
transient String currentID;

String userName;
// more code
}
l-.-:--l :.]:, --'l
:.- l: .-.|- ---
:--.|-.l--, -:l : l'
-:--N.-- .-.|-
-|| - :.- .: .-l
- l- --:l': :l.l-
--- :--.|-.l--
If's hopeIess,
fhen7 I'm compIefeIy
screwed if fhe idiof who
wrofe fhe cIoss for my insfonce
voriobIe forgof fo moke if
SerioIi;obIe7
Il you havc an insiancc vaiiallc ihai can`i lc savcu lccausc
ii isn`i sciializallc, you can maiI ihai vaiiallc wiih ihc
iiansicni Icywoiu anu ihc sciializaiion ioccss will sIi iighi
ovci ii.
So why woulu a vaiiallc noi lc sciializallc. Ii coulu lc
ihai ihc class ucsignci simly io maIc ihc class
imlcmcni Sciializallc. Oi ii mighi lc lccausc ihc ol|cci
iclics on iuniimc-sccihc inloimaiion ihai simly can`i lc
savcu. Alihough mosi ihings in ihc ]ava class liliaiics aic
sciializallc, you can`i savc ihings liIc nciwoiI conncciions,
ihicaus, oi hlc ol|ccis. Thcy`ic all uccnucni on anu
sccihc io) a aiiiculai iuniimc cxciicncc`. In oihci woius,
ihcy`ic insianiiaicu in a way ihai`s uniquc io a aiiiculai iun
ol youi iogiam, on a aiiiculai lailoim, in a aiiiculai
]VM. Oncc ihc iogiam shuis uown, ihcic`s no way io liing
ihosc ihings lacI io lilc in any mcaninglul way, ihcy havc io
lc cicaicu liom sciaich cach iimc.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
440 chapter 14
q.
If seriaIization is so important,
why isn't it the defauIt for aII cIasses!
Why doesn't cIass Dbject impIement
SeriaIizabIe, and then aII subcIasses
wiII be automaticaIIy SeriaIizabIe.
[. Lven though most classes will,
and should, implement Serializable,
you always have a choice. And you
must make a conscious decision on
a class-by-class basis, for each class
you design, to 'enable' serialization
by implementing Serializable.
Pirst of all, if serialization were the
default, how would you turn it offI
|nterfaces indicate functionality, not
a locl of functionality, so the model
of polymorphism wouldn't work
correctly if you had to say, "implements
NonSerializable to tell the world that
you cannot be saved.
q.
Why wouId I ever write a cIass
that wnsnr seriaIizabIe!
[. There are very few reasons, but
you might, for example, have a security
issue where you don't want a password
ob|ect stored. Or you might have an
ob|ect that makes no sense to save,
because its key instance variables are
themselves not serializable, so there's
no useful way for you to make yout
class serializable.
q.
If a cIass I'm using isn't
seriaIizabIe, but there's no good
reason (except that the designer just
forgot or was stupid), can I subcIass
the 'bad' cIass and make the subclnss
seriaIizabIe!
[. es! |f the class itself is
extendable (i.e. not final), you can
make a serializable subclass, and |ust
substitute the subclass everywhere
your code is expecting the superclass
type. (Pemember, polymorphism
allows this.) which brings up another
interesting issue: what does it meon if
the superclass is not serializableI
q.
You brought it up: what Jees it
mean to have a seriaIizabIe subcIass
of a non-seriaIizabIe supercIass!
[. Pirst we have to look at what
happens when a class is deserialized,
(we'll talk about that on the next few
pages). |n a nutshell, when an ob|ect
is deserialized and its superclass is not
serializable, the superclass constructor
will run |ust as though a new ob|ect of
that type were being created. |f there's
no decent reason for a class to not
be serializable, making a serializable
subclass might be a good solution.
q.
Whoal I just reaIized
something big... if you make a
variabIe 'transient', this means the
variabIe's vaIue is skipped over
during seriaIization. 7hen what
happens to it! We soIve the probIem
of having a non-seriaIizabIe instance
variabIe by making the instance
variabIe transient, but don't we ND
that variabIe when the object is
brought back to Iife! In other words,
isn't the whoIe point of seriaIization
to preserve an object's state!
[. es, this is an issue, but
fortunately there's a solution. |f you
serialize an ob|ect, a transient reference
instance variable will be brought back
as null, regardless of the value it had
at the time it was saved. That means
the entire ob|ect graph connected to
that particular instance variable won't
be saved. This could be bad, obviously,
because you probably need a non-null
value for that variable.
ou have two options:
l) when the ob|ect is brought back,
reinitialize that null instance variable
back to some default state. This
works if your deserialized ob|ect isn't
dependent on a particular value for
that transient variable. |n other words,
it might be important that the Dog
have a Collar, but perhaps all Collar
ob|ects are the same so it doesn't
matter if you give the resurrected Dog
a brand new Collar, nobody will know
the difference.
2) |f the value of the transient variable
Joes matter (say, if the color and design
of the transient Collar are unique for
each Dog) then you need to save the
key values of the Collar and use them
when the Dog is brought back to
essentially re-create a brand new Collar
that's identical to the original.
q.
What happens if two objects in
the object graph are the same object!
Like, if you have two different Cat
objects in the kenneI, but both Cats
have a reference to the same Dwner
object. Does the Dwner get saved
twice! I'm hoping not.
[. Lxcellent question! Serialization
is smart enough to know when two
ob|ects in the graph are the same. |n
that case, only one of the ob|ects is
saved, and during deserialization, any
references to that single ob|ect are
restored.
seriaIized objects
,-,- a,- |
oa|| qa--,.|-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 441
Pcscr|z||zz!|en: rcs!er|n] zn e|jcr!
Thc wholc oini ol sciializing an ol|cci is so ihai you can
icsioic ii lacI io iis oiiginal siaic ai somc laici uaic, in a
uillcicni iun` ol ihc ]VM which mighi noi cvcn lc ihc samc
]VM ihai was iunning ai ihc iimc ihc ol|cci was sciializcu).
Dcsciializaiion is a loi liIc sciializaiion in icvcisc.
FileInputStream leStream = new FileInputStream(MyGame.ser);
M
.- . ||-|--ll--.- --:l 1- ||-|--ll--.-
---: -- l- :----:l l- .- -:l- |-

Muke u FiIeInputStreum
Object one = os.readObject();
Object two = os.readObject();
Object three = os.readObject();

reud the objects


os.close();

CIose the ObjectInputStreum


c|-:- l- :l--.- .l l- l- :|-:-: l- ---:
------.l, :- l- ||-|--ll--.- |.- l-
|-` -|| :|-:- .-l--.l:.||]
| l- |- M]6.--:--' --:-'l
-:l, ]--'|| -l .- -:-l--
ObjectInputStream os = new ObjectInputStream(leStream);

Muke un ObjectInputStreum
6-:l|--ll--.- |-l: ]-- --. --:l:,
-l l :.-'l --:l|] :----:l l- . |-
|l ---: l- - :.-- l- . :----:l--
:l--.-, - l: :.:- . ||-|--ll--.-
GameCharacter elf = (GameCharacter) one;
GameCharacter troll = (GameCharacter) two;
GameCharacter magician = (GameCharacter) three;

Cust the objects


!.: l-- ]-- :.] --.6-:l|`, ]-- -l l- --l --:l - l- :l--.- - ]--'|| --. l-- .: - l- :.-- ---- - -: l-] ---- --ll-- /--'|| -l . .l -:-l-- ]-- l-] l- --. ---- --:l: l.- ]-- ---l-
1- --l--- .|-- -
--.6-:l|` : l]- 6-:l
|-:l |- -l A--.]|:l`, :-
]-- .- l- :.:l l .: l-
l- l]- ]-- --- l --.||] :
:--.|--
-:--.|--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
442 chapter 14
Whz! hzppcns 4er|n] 4cscr|z||zz!|en!
Whcn an ol|cci is ucsciializcu, ihc ]VM aiicmis io liing
ihc ol|cci lacI io lilc ly maIing a ncw ol|cci on ihc hca
ihai has ihc samc siaic ihc sciializcu ol|cci hau ai ihc iimc ii
was sciializcu. Wcll, cxcci loi ihc iiansicni vaiiallcs, which
comc lacI ciihci null loi ol|cci iclcicnccs) oi as uclauli
iimiiivc valucs.
deseriaIizing objects

The objecf is reud from fhe sfreom.

The JVM defermines (fhrough info sfored wifh


fhe serioIi;ed objecf) fhe objecf's cIuss type,

The JVM offempfs fo hnd und Ioud fhe ob-


jecf's cIuss. If fhe JVM con'f fnd ond/or Iood
fhe cIoss, fhe JVM fhrows on excepfion ond
fhe deserioIi;ofion foiIs.

A new objecf is given spoce on fhe heop, buf


fhe seriuIized object's constructor does
NOT runl ObviousIy, if fhe consfrucfor ron, if
wouId resfore fhe sfofe of fhe objecf bock
fo ifs originoI 'new' sfofe, ond fhof's nof whof
we wonf. We wonf fhe objecf fo be resfored
fo fhe sfofe if hod when if wos serioIi;ed, nof
when if wos frsf creofed.
1
: :l- -|| l--- .- -:-l-- l- )/M

:.-'l - -- |-. l- :|.::'
Objecf
ObjecfInpufSfreom
(o choin sfreom)
is reod by
cIoss is found ond Iooded, soved
insfonce voriobIes reossigned
FiIeInpufSfreom
(o connecfion sfreom)
0II0I00I0II0III00I
objecf is reod os byfes
0II0I00I
0II0III0
0I
FiIe
is choined fo
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
seriaIization and fiIe I/O
you are here 443

If fhe objecf hos o non-serioIi;obIe cIoss


somewhere up ifs inherifonce free, fhe
constructor for thut non-seriuIizubIe cIuss
wiII run oIong wifh ony consfrucfors obove
fhof (even if fhey're serioIi;obIe). Once fhe
consfrucfor choining begins, you con'f sfop if,
which meons oII supercIosses, beginning wifh
fhe frsf non-serioIi;obIe one, wiII reinifioIi;e
fheir sfofe.

The objecf's instunce vuriubIes ure given the


vuIues from the seriuIized stute. Tronsienf
voriobIes ore given o voIue of nuII for objecf
references ond defouIfs (0, foIse, efc.) for
primifives.
(-,- a,- |
oa|| qa--(:|-

Why doesn't the cIass get saved as part of the ob-


ject! 7hat way you don't have the probIem with whether
the cIass can be found.

Sure, they could have made serialization work that


way. 8ut what a tremendous waste and overhead. And
while it might not be such a hardship when you're using
serialization to write ob|ects to a file on a local hard drive,
serialization is also used to send ob|ects over a network
connection. |f a class was bundled with each serialized
(shippable) ob|ect, bandwidth would become a much larger
problem than it already is.
Por ob|ects serialized to ship over a network, though, there
actually |s a mechanism where the serialized ob|ect can be
'stamped' with a UPL for where its class can be found. This
is used in 1ava's Pemote Method |nvocation (PM|) so that
you can send a serialized ob|ect as part of, say, a method
argument, and if the 1vM receiving the call doesn't have
the class, it can use the UPL to fetch the class from the
network and load it, all automatically. (we'll talk about PM|
in chapter l7.)

What about static variabIes! Are they seriaIized!

Nope. Pemember, static means "one per class not


"one per ob|ect. Static variables are not saved, and when an
ob|ect is deserialized, it will have whatever static variable
its class cuttently has. The moral: don't make serializable ob-
|ects dependent on a dynamically-changing static variable!
|t might not be the same when the ob|ect comes back.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
444 chapter 14
8zv|n] zn4 rcs!er|n] !hc ]zmc rhzrzr!crs
import java.io.*;
public class GameSaverTest {
public static void main(String[] args) {
GameCharacter one = new GameCharacter(50, Elf, new String[] {bow, sword, dust});
GameCharacter two = new GameCharacter(200, Troll, new String[] {bare hands, big ax});
GameCharacter three = new GameCharacter(120, Magician, new String[] {spells, invisibility});
// imagine code that does things with the characters that might change their state values

try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(Game.ser));
os.writeObject(one);
os.writeObject(two);
os.writeObject(three);
os.close();
} catch(IOException ex) {
ex.printStackTrace();
}
one = null;
two = null;
three = null;

try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(Game.ser));
GameCharacter oneRestore = (GameCharacter) is.readObject();
GameCharacter twoRestore = (GameCharacter) is.readObject();
GameCharacter threeRestore = (GameCharacter) is.readObject();
System.out.println(One's type: + oneRestore.getType());
System.out.println(Two's type: + twoRestore.getType());
System.out.println(Three's type: + threeRestore.getType());
} catch(Exception ex) {
ex.printStackTrace();
}
}
File Edit Window Help Resuscitate
% java GameSaver
Elf
Troll
Magician


---- -o
l]- !|
--.--: --,
:---, -:l
---- |io
l]- M.:.-
--.--: :-||:,
-:|l]


---- ioo
l]- 1--||
--.--: .--
.-:, .


seriaIization exampIe
w- :-l l-- l- --|| :- -- :.-'l
.::-:: l- --:l: -- l- -.
M.- :--- :.-.:l--:
N-- --. l-- .: - --- l- |-
c-: l- :-- l ----
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 445
import java.io.*;
public class GameCharacter implements Serializable {
int power;
String type;
String[] weapons;
public GameCharacter(int p, String t, String[] w) {
power = p;
type = t;
weapons = w;
}
public int getPower() {
return power;
}
public String getType() {
return type;
}
public String getWeapons() {
String weaponList = ;
for (int i = 0; i < weapons.length; i++) {
weaponList += weapons[i] + ;
}
return weaponList;
}
}
Ihc 0zmc0hzrzr!cr r|zss
1: : . .:: :|.:: -:l -- l-:l-
--.|-.l--, .- -- --'l .- .-
.:l-.| .--, -l --'|| |-.- l.l l-
]-- l- ------l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
saving objects
446 chapter 14
8ll P0lk5
You car save ar oojecl's slale oy ser|a||z|r l|e oojecl.
To ser|a||ze ar oojecl, you reed ar 0ojecl0ulpul3lrear (lror l|e
java.|o pac|ae)
3lrears are e|l|er correcl|or slrears or c|a|r slrears
Correcl|or slrears car represerl a correcl|or lo a source or
desl|ral|or, lyp|ca||y a l||e, relWor| soc|el correcl|or, or l|e
corso|e.
C|a|r slrears carrol correcl lo a source or desl|ral|or ard rusl
oe c|a|red lo a correcl|or (or ol|er) slrear.
To ser|a||ze ar oojecl lo a l||e, ra|e a F||e0upul3lrear ard c|a|r |l
|rlo ar 0ojecl0ulpul3lrear.
To ser|a||ze ar oojecl, ca|| ur|reDojeor{rneDojeorj or l|e
0ojecl0ulpul3lrear. You do rol reed lo ca|| rel|ods or l|e
F||e0ulpul3lrear.
To oe ser|a||zed, ar oojecl rusl |rp|ererl l|e 3er|a||zao|e |rlerlace.
ll a superc|ass ol l|e c|ass |rp|ererls 3er|a||zao|e, l|e suoc|ass W|||
auloral|ca||y oe ser|a||zao|e ever |l |l does rol spec|l|ca||y dec|are
|m|emenrs $er|a||zao|e.
w|er ar oojecl |s ser|a||zed, |ls erl|re oojecl rap| |s ser|a||zed. T|al
rears ary oojecls relererced oy l|e ser|a||zed oojecl's |rslarce
var|ao|es are ser|a||zed, ard ary oojecls relererced oy l|ose
oojecls...ard so or.
ll ary oojecl |r l|e rap| |s rol ser|a||zao|e, ar excepl|or W||| oe
l|roWr al rurl|re, ur|ess l|e |rslarce var|ao|e relerr|r lo l|e oojecl
|s s||pped.
Var| ar |rslarce var|ao|e W|l| l|e rrans|enr |eyWord |l you Warl
ser|a||zal|or lo s||p l|al var|ao|e. T|e var|ao|e W||| oe reslored as ru||
(lor oojecl relererces) or delau|l va|ues (lor pr|r|l|ves).
0ur|r deser|a||zal|or, l|e c|ass ol a|| oojecls |r l|e rap| rusl oe
ava||ao|e lo l|e JvV.
You read oojecls |r (us|r read0ojecl()) |r l|e order |r W||c| l|ey
Were or||ra||y Wr|ller.
T|e relurr lype ol read0ojecl() |s lype 0ojecl, so deser|a||zed
oojecls rusl oe casl lo l|e|r rea| lype.
3lal|c var|ao|es are rol ser|a||zedl ll doesr'l ra|e serse lo save
a slal|c var|ao|e va|ue as parl ol a spec|l|c oojecl's slale, s|rce a||
oojecls ol l|al lype s|are or|y a s|r|e va|uel|e ore |r l|e c|ass.
0le:t Se:ia|izatiaa
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 447
Wr| !|n] z 8!r|n] !e z Icr! I||c
Saving ol|ccis, ihiough sciializaiion, is ihc casicsi way io savc anu
icsioic uaia lciwccn iunnings ol a ]ava iogiam. Bui somciimcs you
nccu io savc uaia io a lain olu icxi hlc. Imaginc youi ]ava iogiam
has io wiiic uaia io a simlc icxi hlc ihai somc oihci cihas non-
]ava) iogiam nccus io icau. You mighi, loi cxamlc, havc a scivlci
]ava couc iunning wiihin youi wcl scivci) ihai iaIcs loim uaia ihc
usci iycu inio a liowsci, anu wiiics ii io a icxi hlc ihai somclouy clsc
loaus inio a sicaushcci loi analysis.
Wiiiing icxi uaia a Siiing, aciually) is similai io wiiiing an ol|cci,
cxcci you wiiic a Siiing insicau ol an ol|cci, anu you usc a
IilcWiiici insicau ol a IilcOuiuiSiicam anu you uon`i chain ii io an
Ol|cciOuiuiSiicam).
b0,Ill,rcw, swcra,aus|
800,1rcll,rare hanas,ri ax
180,Haician,sells,invisirili|y
w.l l- .-- :.-.:l-- .l.
-l |-- |- ]-- ---l- l
--l .: . --.-~--..|- l-l |-
To write u seriuIized object:
objectOutputStream.writeObject(someObject);
To write u String:
leWriter.write(My rst String to save);
import java.io.*;
class WriteAFile {
public static void main (String[] args) {
try {
FileWriter writer = new FileWriter(Foo.txt);
writer.write(hello foo!);
writer.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
w- --- l- ..- .:.- -- ||-w-l--
A
|
|
l- |/6 :l-
--:l - - . l-]/:.l:
!--]l- :.- l--- .-
|6!:-l--''
| l- |- |--ll' --: --l
-:l, ||-w
-l-- -|| :--.l- l
1- --l-|` --l- l.-:
. l--
c|-:- l --- ]--'-- ---'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
448 chapter 14
writing a text fiIe
Icr! I||c Irzmp|c: c-I|zshrzr4s
Rcmcmlci ihosc uashcaius you uscu in school. Whcic you
hau a qucsiion on onc siuc anu ihc answci on ihc lacI.
Thcy aicn`i much hcl whcn you`ic iiying io unucisianu
somcihing, lui noihing lcais cm loi iaw uiill-anu-iaciicc
anu ioic mcmoiizaiion. VLer ,ou Ln.e o bu.r .r n n. Anu
ihcy`ic also gicai loi iiivia gamcs.
Wc'rc going to makc an clcctronic vcrsion that has thrcc
classcs:
1) QuizCordBuiIder, a simlc auihoiing iool loi cicaiing anu
saving a sci ol c-Ilashcaius.
2) QuizCordPIoyer, a laylacI cnginc ihai can loau a
uashcaiu sci anu lay ii loi ihc usci.
S) QuizCord, a simlc class icicscniing caiu uaia. Wc`ll
walI ihiough ihc couc loi ihc luiluci anu ihc layci, anu
havc you maIc ihc QuizCaiu class youiscll, using ihis
w
.l': l- -:l
---- :---l-] --
:--l - l
-l--l
M
:.-
c.-.. |6-l.--`
---l
.:
-|~.:--- ? -
-- |.::.-:
QuizCurduiIder
Hos o FiIe menu wifh o "Sove" opfion for soving
fhe currenf sef of cords fo o fexf fIe.
QuizCurdPIuyer
Hos o FiIe menu wifh o "Lood" opfion for Iooding o
sef of cords from o fexf fIe.

0u|zCard(q, a)
quesl|or
arsWer
el0uesl|or()
elArsWer()

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 449
0e|z 0zr4 Be||4cr |re4c ee!||ncI
ullic class QuizCaiuBuiluci [

ullic voiu go() [
// luilu anu uislay gui
}
iivaic class NcxtCardListcncr imlcmcnis AciionIisicnci [
ullic voiu aciionPciloimcuAciionEvcni cv) [
// auu ihc cuiicni caiu io ihc lisi anu clcai ihc icxi aicas
}
}
iivaic class SavcMcnuListcncr imlcmcnis AciionIisicnci [
ullic voiu aciionPciloimcuAciionEvcni cv) [
// liing u a hlc uialog lox
// lci ihc usci namc anu savc ihc sci
}
}
iivaic class NcwMcnuListcncr imlcmcnis AciionIisicnci [
ullic voiu aciionPciloimcuAciionEvcni cv) [
// clcai oui ihc caiu lisi, anu clcai oui ihc icxi aicas
}
}


iivaic voiu savcFilc(Filc hlc) [
// iiciaic ihiough ihc lisi ol caius, anu wiiic cach onc oui io a icxi hlc
// in a aiscallc way in oihci woius, wiih clcai scaiaiions lciwccn aiis)
}
}
B-|: .- :|.]: l- 6c|, -:|--
-.- .- --:l--- ---l |:l----:
1---- --- -:-- l: 'N-l c.-' -ll--.
--.-: l- -:-- -.-l: l- :l--- l.l :.- -
l- |:l .- :l.-l . --- :.-
1---- --- -:- :--:-: '.-' --- l-
||- ----. --.-: l- -:-- -.-l: l- :.- .||
l- :.-: - l- :-----l |:l .: . ':-l' ||-,
6-.-l-- M-:.-:: -l, +-||]--- 1-.,
).. -|-:, -l:`
1---- ] :--:- 'N--' --- l- ||-
----. --.-: l- -:-- -.-l: l- :l.-l .
-.- --- :-l |:- -- :|-.- --l l- :.-
|:l .- l- l-l .--.:`
c.||- ] l- .-M---|:l----.
--: l- .:l-.| |- --l-
|---- :|.::
|---- :|.::
|---- :|.::
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
450 chapter 14
Quiz Card BuiIder code
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class QuizCardBuilder {
private JTextArea question;
private JTextArea answer;
private ArrayList<QuizCard> cardList;
private JFrame frame;

public static void main (String[] args) {
QuizCardBuilder builder = new QuizCardBuilder();
builder.go();
}

public void go() {
// build gui
frame = new JFrame(Quiz Card Builder);
JPanel mainPanel = new JPanel();
Font bigFont = new Font(sanserif, Font.BOLD, 24);
question = new JTextArea(6,20);
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setFont(bigFont);

JScrollPane qScroller = new JScrollPane(question);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
answer = new JTextArea(6,20);
answer.setLineWrap(true);
answer.setWrapStyleWord(true);
answer.setFont(bigFont);

JScrollPane aScroller = new JScrollPane(answer);
aScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
aScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

JButton nextButton = new JButton(Next Card);

cardList = new ArrayList<QuizCard>();
JLabel qLabel = new JLabel(Question:);
JLabel aLabel = new JLabel(Answer:);

mainPanel.add(qLabel);
mainPanel.add(qScroller);
mainPanel.add(aLabel);
mainPanel.add(aScroller);
mainPanel.add(nextButton);
nextButton.addActionListener(new NextCardListener());
JMenuBar menuBar = new JMenuBar();
JMenu hleMenu = new JMenu(File);
JMenuItem newMenuItem = new JMenuItem(New);
1: : .|| 6c| :-- --- N-l-
:-:.|, .|l-- ]-- -l -.-l
l- |-- .l l- M
---B.-, M
---,
.- M
---|l--: :--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 451

JMenuItem saveMenuItem = new JMenuItem(Save);
newMenuItem.addActionListener(new NewMenuListener());

saveMenuItem.addActionListener(new SaveMenuListener());
hleMenu.add(newMenuItem);
hleMenu.add(saveMenuItem);
menuBar.add(hleMenu);
frame.setJMenuBar(menuBar);
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(500,600);
frame.setVisible(true);
}
public class NextCardListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {

QuizCard card = new QuizCard(question.getText(), answer.getText());
cardList.add(card);
clearCard();
}
}
public class SaveMenuListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
QuizCard card = new QuizCard(question.getText(), answer.getText());
cardList.add(card);

JFileChooser hleSave = new JFileChooser();
hleSave.showSaveDialog(frame);
saveFile(hleSave.getSelectedFile());
}
}
public class NewMenuListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
cardList.clear();
clearCard();
}
}

private void clearCard() {
question.setText();
answer.setText();
question.requestFocus();
}
private void saveFile(File le) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(hle));

for(QuizCard card:cardList) {
writer.write(card.getQuestion() + /);
writer.write(card.getAnswer() + \n);
}
writer.close();
} catch(IOException ex) {
System.out.println(couldn't write the cardList out);
ex.printStackTrace();
}
}
}





B--: - . |- .|- - .- -.l: -- l:
|-- --l| l- -:-- :--:-: '.-' --- l-
.|- - A|| l- |- .|- -..l-- .-
:-|-:l- . |-, -l: : --- -- ]-- ] l-
)||-c--:--' |l --.||] : l: -.:]
1- --l- l.l --: l- .:l-.| |- --l-
|:.||- ] l- .-M
---|:l----': ---l .-|--`
1- .-----l : l- '||-' --:l l- -:-- : :.-
w
-'|| |-- .l l- ||- :|.:: -- l- --l .-
w- :.- . B----w-l-- -- l- . ---
||-w-l-- l- -.- --l- ---- -:--l
|w-'|| l.| .--l l.l - . -- .-:`
w.| l--- l- A--.]|:l -
:.-: .- --l- l-- --l, --- :.- -- |--, -l l- --:l-- .- .-~ :--- :-.-.l- ] . /', .- l-- . . ---|-- :.-.:l-- |`-'`
w- -.- . ---- .-, -.- . ||-
----, l-- -l '---' .- ':.-' ----
l--: -l- l- ||- ---- w- . l-
---- l- l- ---- .-, l-- l-|| l-
-.-- l- -:- l: ---- .- M---
l--: :.- -- .- A:l--!--l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
452 chapter 14
Ihc jzvz.|e.I||c r|zss
Thc |ava.io.Iilc class .e.eer a hlc on uisI, lui uocsn`i
aciually icicscni ihc orer ol ihc hlc. Whai. ThinI ol
a Iilc ol|cci as somcihing moic liIc a nLrne ol a hlc
oi cvcn a J..eo.,) iaihci ihan Thc Aciual Iilc Iiscll.
Thc Iilc class uocs noi, loi cxamlc, havc mcihous loi
icauing anu wiiiing. Onc VERY usclul ihing aloui a Iilc
ol|cci is ihai ii ollcis a much salci way io icicscni a
hlc ihan |usi using a Siiing hlc namc. Ioi cxamlc, mosi
classcs ihai iaIc a Siiing hlc namc in ihcii consiiucioi
liIc IilcWiiici oi IilcInuiSiicam) can iaIc a Iilc
ol|cci insicau. You can consiiuci a Iilc ol|cci, vciily
ihai you`vc goi a valiu aih, cic. anu ihcn givc ihai Iilc
ol|cci io ihc IilcWiiici oi IilcInuiSiicam.
writing fiIes
b0,Ill,rcw, swcra,aus|
800,1rcll,rare hanas,ri ax
180,Haician,sells,invisirili|y
A File ob]ect represents the name
and path of a hle or directory on
disk, for example:
/Users/Kathy/ Data/GameFile.txt
But it does NOT represent, or give
you access to, the data in the hlel
8ome things you can do with a File ob]ect:
GameFile.txt
A ||- --:l --: N61
----:--l |-- - ]--
--:l .::-:: l-` l-
.l. -:- l- |-'
A ||- --:l ----:--l: l-
|--.-- 6.--||-ll'
File f = new File(MyCode.txt);
Muke u FiIe object representing un
eisting hIe
1
File dir = new File(Chapter7);
dir.mkdir();
Muke u new directory 2
if (dir.isDirectory()) {
String[] dirContents = dir.list();
for (int i = 0; i < dirContents.length; i++) {
System.out.println(dirContents[i]);
}
}
List the contents of u directory 3
System.out.println(dir.getAbsolutePath());
Set the ubsoIute puth of u hIe or directory 4
boolean isDeleted = f.delete();
DeIete u hIe or directory {returns true if
successfuI}
5
A- .--:: : N61 l-
:.-- .: l- .:l-.|
--:-' A ||- --:l :
|- . :l---l .--::
l ----:--l: l- -.--
.- |-:.l-- - . .-~
l:-|.- |-, -l l :-'l
l- |- l:-|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
seriaIization and fiIe I/O
you are here 453
Sfring
8ufferedWrifer
(o choin sfreom fhof
works wifh chorocfers)
is wriffen fo
Sfring is puf info o buffer
wifh ofher Sfrings
FiIeWrifer
(o connecfion sfreom
fhof wrifes chorocfers
os opposed fo byfes)
"Aspen Denver 8ouIder"
When fhe buffer is fuII, fhe
Sfrings ore oII wriffen fo
Aspen
Denver
8ouIder
FiIe
-:l-.l--
is choined fo
8ealder"
8ealder"
0enver"
Aspen"
The beauty of buffers
If there were no buffers it wouId be Iike
shopping without u curt, You'd huve to
curry euch thing out to your cur one soup
cun or toiIet puper roII ut u time,
Thc cool ihing aloui lullcis is ihai ihcy`ic uL moic clhcicni ihan
woiIing wiihoui ihcm. You can wiiic io a hlc using IilcWiiici alonc, ly
calling wiiicsomcSiiing), lui IilcWiiici wiiics cach anu cvciy ihing you
ass io ihc hlc cach anu cvciy iimc. Thai`s ovcihcau you uon`i wani oi
nccu, sincc cvciy iii io ihc uisI is a Big Dcal comaicu io maniulaiing
uaia in mcmoiy. By chaining a BullcicuWiiici onio a IilcWiiici, ihc
BullcicuWiiici will holu all ihc siull you wiiic io ii uniil ii`s lull. OrI, wLer
Le bue. . uII w.II Le E.IeV..e. nunII, be oIJ o w..e o Le Ie or J.I.
Il you uo wani io scnu uaia beo.e ihc lullci is lull, you uo havc coniiol.
]ust FIush It. Calls io wiiici.uush) say, scnu whaicvci`s in ihc lullci, now!"
---: - ]-- . l----.-] -|-
|.:- l- --- l-: --l| l- -|--
||- l- :.-l` : -|| /-- -l l- -.-
.- ---- l-: --- ]-- -:- . ---
BufferedWriter writer = new BufferedWriter(new FileWriter(aFile));
N-l:- l.l -- --'l ---
--- l- -- . ------:- l-
l- ||-w-l-- --:l 1-
--|] l- -- :.-- .--l : l-
B----w-l--, -:.-:- l.l':
l- --:l --'|| :.|| --l-:
--, .- --- -- :|-:- l-
B----w-l--, l -|| l.-
:.-- - l- --:l - l- :.-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
454 chapter 14
Kcz4|n] frem z Icr! I||c
Rcauing icxi liom a hlc is simlc, lui ihis iimc wc`ll usc a Iilc
ol|cci io icicscni ihc hlc, a IilcRcauci io uo ihc aciual icauing,
anu a BullcicuRcauci io maIc ihc icauing moic clhcicni.
Thc icau hacns ly icauing lincs in a loo, cnuing ihc loo
whcn ihc icsuli ol a icauIinc) is null. Thai`s ihc mosi common
siylc loi icauing uaia iciiy much anyihing ihai`s noi a Sciializcu
ol|cci): icau siull in a whilc loo aciually a whilc loo ),
iciminaiing whcn ihcic`s noihing lcli io icau which wc Inow
lccausc ihc icsuli ol whaicvci icau mcihou wc`ic using is null).
Tha|`s 8 + 8?/4
Tha|`s 80+88/48
A |- -l l-- |--: - l-l
import java.io.*;
class ReadAFile {
public static void main (String[] args) {
try {
File myFile = new File(MyText.txt);
FileReader leReader = new FileReader(myFile);
BufferedReader reader = new BufferedReader( leReader);
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
l--'l ---l l- ---l
c.- l- ||--.-- l- .
B
-----.-- -- ----
-:--l --.- |l'|| - .:
l- l- |- l- --. --|] ---
l- --- : --l] |-:.-:- l-
---.- .: --. ---]l- - l`
A ||--.-- : . :----:l-- :l--.- -- :.-.:l--:, l.l :----:l: l- . l-l |-
M.- . l-- .-.|- l- -|
-.: |-- .: l- |-- : --.
reading fiIes

1: :.]:, -. . |-- - l-l, .- .::- l l- l-


l-- .-.|- '|--' w|- l.l .-.|- : --l --||
|-:.-:- l--- wA :---l- l- --.` --l --l l-
|-- l.l -.: -:l --.'
6- .--l-- -.] - :.]- l, w|- l--- .-- :l|| |--:
l- --., --. l-- .- --l l--'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 455
0e|z 0zr4 ||zycr |re4c ee!||ncI
ullic class QuizCaiuPlayci [

ullic voiu go() [
// luilu anu uislay gui
}
class NcxtCardListcncr imlcmcnis AciionIisicnci [
ullic voiu aciionPciloimcuAciionEvcni cv) [
// il ihis is a qucsiion, show ihc answci, oihciwisc show ncxi qucsiion
// sci a uag loi whcihci wc`ic vicwing a qucsiion oi answci
}
}
class OpcnMcnuListcncr imlcmcnis AciionIisicnci [
ullic voiu aciionPciloimcuAciionEvcni cv) [
// liing u a hlc uialog lox
// lci ihc usci navigaic io anu choosc a caiu sci io ocn
}
}

iivaic voiu loadFilc(Filc hlc) [
// musi luilu an AiiayIisi ol caius, ly icauing ihcm liom a icxi hlc
// callcu liom ihc OcnMcnuIisicnci cvcni hanulci, icaus ihc hlc onc linc ai a iimc
// anu iclls ihc maIcCaiu) mcihou io maIc a ncw caiu oui ol ihc linc
// onc linc in ihc hlc holus loih ihc qucsiion anu answci, scaiaicu ly a /")
}
iivaic voiu makcCard(String lincToParsc) [
// callcu ly ihc loauIilc mcihou, iaIcs a linc liom ihc icxi hlc
// anu aiscs inio iwo icccs-qucsiion anu answci-anu cicaics a ncw QuizCaiu
// anu auus ii io ihc AiiayIisi callcu CaiuIisi
}
}
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
456 chapter 14
Quiz Card PIayer code
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class QuizCardPlayer {
private JTextArea display;
private JTextArea answer;
private ArrayList<QuizCard> cardList;
private QuizCard currentCard;
private int currentCardIndex;
private JFrame frame;
private JButton nextButton;
private boolean isShowAnswer;
public static void main (String[] args) {
QuizCardPlayer reader = new QuizCardPlayer();
reader.go();
}

public void go() {

// build gui
frame = new JFrame(Quiz Card Player);
JPanel mainPanel = new JPanel();
Font bigFont = new Font(sanserif, Font.BOLD, 24);

display = new JTextArea(10,20);
display.setFont(bigFont);

display.setLineWrap(true);
display.setEditable(false);

JScrollPane qScroller = new JScrollPane(display);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
nextButton = new JButton(Show Question);
mainPanel.add(qScroller);
mainPanel.add(nextButton);
nextButton.addActionListener(new NextCardListener());
JMenuBar menuBar = new JMenuBar();
JMenu hleMenu = new JMenu(File);
JMenuItem loadMenuItem = new JMenuItem(Load card set);
loadMenuItem.addActionListener(new OpenMenuListener());
hleMenu.add(loadMenuItem);
menuBar.add(hleMenu);
frame.setJMenuBar(menuBar);
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(640,500);
frame.setVisible(true);

} // close go

)-:l 6c| :-- -- l: .-. --l- :-:.|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 457
public class NextCardListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
if (isShowAnswer) {
// show the answer because they've seen the question
display.setText(currentCard.getAnswer());
nextButton.setText(Next Card);
isShowAnswer = false;
} else {
// show the next question
if (currentCardIndex < cardList.size()) {

showNextCard();

} else {
// there are no more cards!
display.setText(That was last card);
nextButton.setEnabled(false);
}
}
}
}

public class OpenMenuListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
JFileChooser hleOpen = new JFileChooser();
hleOpen.showOpenDialog(frame);
loadFile(hleOpen.getSelectedFile());
}
}
private void loadFile(File le) {
cardList = new ArrayList<QuizCard>();
try {
BufferedReader reader = new BufferedReader(new FileReader(hle));
String line = null;
while ((line = reader.readLine()) != null) {
makeCard(line);
}
reader.close();
} catch(Exception ex) {
System.out.println(couldn't read the card hle);
ex.printStackTrace();
}
// now time to start by showing the hrst card
showNextCard();
}
private void makeCard(String lineToParse) {
String[] result = lineToParse.split(/);
QuizCard card = new QuizCard(result[0], result[1]);
cardList.add(card);
System.out.println(made a card);
}

private void showNextCard() {
currentCard = cardList.get(currentCardIndex);
currentCardIndex++;
display.setText(currentCard.getQuestion());
nextButton.setText(Show Answer);
isShowAnswer = true;
}
} // close class

c-: l- :--A-:--- --|-.- |. l-
:-- l-]'-- :-----l|] --- . --:l--
-- .- .-:---, .- - l- .---.l-
l- ---- -- l- .-:---
B-- - l- |- .|- - .- |-l l--
-..l- l- .- :--:- l- |- l- ---
M.- . B-----.-- :.--
l- . --- ||--.--, - l-
||--.-- l- ||- --:l l- -:--
:-:- --- l- --- |- .|-
-. . |-- .l . l--, .::- l-
|-- l- l- -.-c.-|` --l-
l.l .-:-: l .- l---: l -l- .
--.| 6--c.- .- .: l l- l-
A--.]|:l
!.: |-- - l-l :----:--: l- . :-|-
|.::.-, -l -- .- l- .-:- --l l-
--:l-- .- .-:--- .: :-.-.l- -:-: w-
-:- l- l-- :|l|` --l- l- --. l-
|-- -l- l-- l---: |--- -- l- --:l--
.- --- -- l- .-:---` w-'|| |-- .l l-
:|l|` --l- -- l- --l .-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
458 chapter 14
parsing Strings with spIit()
|zrs|n] w| !h 8!r|n] sp|| !|I
magine you have a hashcard like this:
what Is bIue yeIIcw?
green
--:l--
.-:---
Tha| is rlue + yellcw?/reen
Tha| is rea + rlue?/urle
8aved in a question hle like this:
How do you separate the question and answer?
When you reod fhe fIe, fhe quesfion ond onswer ore smooshed
fogefher in one Iine, seporofed by o forword sIosh "/" (becouse
fhof's how we wrofe fhe fIe in fhe Qui;Cord8uiIder code).
8tring split{} lets you break a 8tring into pieces.
The spIif() mefhod soys, "give me o seporofor, ond I'II breok ouf oII
fhe pieces of fhis Sfring for you ond puf fhem in o Sfring orroy."
foken I foken Z
seporofor
String toTest = What is blue + yellow?/green;
String[] result = toTest.split(/);
for (String token:result) {
System.out.println(token);
}
|- l- 6--c.-||.]-- ., l:
: -.l . :-|- |-- |--: |-
--- l': --. - --- l- |-
|-- l--- l- .--.] .- --l -.: l---
|-:-` |- l: -.-|-, l--- .-- --|] l--
l---: w.l : |-- + ]-||--' .- ----'
1- :|l|` --l- l.-: l- /' .- -:-: l l- --. ..-l l- l-- -l- |- l: :.:-` l--
-:-: |N-l- :|l|` : |A ---- -----| l.- -.l --'-- -:- l -- --- |l :.- - -l----|] :--|- .-:- -l |l--:, -|:.-:, -l:`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 459
(-,- a,- |
oa|| qa--(:|-

Dk, I Iook in the API and there are about ve


miIIion cIasses in the java.io package. How the heck do
you know which ones to use!

The |/O AP| uses the modular 'chaining' concept so


that you can hook together connection streams and chain
streams (also called 'filter' streams) in a wide range of
combinations to get |ust about anything you could want.
The chains don't have to stop at two levels, you can hook
multiple chain streams to one another to get |ust the right
amount of processing you need.
Most of the time, though, you'll use the same
small handful of classes. |f you're writing text files,
8ufferedPeader and 8ufferedwriter (chained to PilePeader
and Pilewriter) are probably all you need. |f you're writing
serialized ob|ects, you can use Ob|ectOutputStream and
Ob|ect|nputStream (chained to Pile|nputStream and
PileOutputStream).
|n other words, 90% of what you might typically do with
1ava |/O can use what we've already covered.

What about the new I/D nio cIasses added in 1.4!

The |ava.nio classes bring a big performance


improvement and take greater advantage of native
capabilities of the machine your program is running
on. One of the key new features of nio is that you have
direct control of buffers. Another new feature is non-
blocking |/O, which means your |/O code doesn't |ust sit
there, waiting, if there's nothing to read or write. Some
of the existing classes (including Pile|nputStream and
PileOutputStream) take advantage of some of the new
features, under the covers. The nio classes are more
complicated to use, however, so unless you teolly need the
new features, you might want to stick with the simpler
versions we've used here. Plus, if you're not careful, nio can
lead to a performance loss. Non-nio |/O is probably right
for 90% of what you'll normally do, especially if you're |ust
getting started in 1ava.
8ut you con ease your way into the nio classes, by using
Pile|nputStream and accessing its chonnel through the
getChannel() method (added to Pile|nputStream as of
version l.4).
8ll P0lk5
To Wr|le a lexl l||e, slarl W|l| a F||ewr|ler
correcl|or slrear.
C|a|r l|e F||ewr|ler lo a 8ulleredwr|ler lor
ell|c|ercy.
A F||e oojecl represerls a l||e al a parl|cu|ar
pal|, oul does rol represerl l|e aclua|
corlerls ol l|e l||e.
w|l| a F||e oojecl you car creale, lraverse,
ard de|ele d|reclor|es.
Vosl slrears l|al car use a 3lr|r l||erare
car use a F||e oojecl as We||, ard a F||e oojecl
car oe saler lo use.
To read a lexl l||e, slarl W|l| a F||eReader
correcl|or slrear.
C|a|r l|e F||eReader lo a 8ulleredReader lor
ell|c|ercy.
To parse a lexl l||e, you reed lo oe sure l|e
l||e |s Wr|ller W|l| sore Way lo recor|ze l|e
d|llererl e|ererls. A corror approac| |s lo
use sore ||rd ol c|aracler lo separale l|e
|rd|v|dua| p|eces.
use l|e 3lr|r sp||l() rel|od lo sp||l a 3lr|r
up |rlo |rd|v|dua| lo|ers. A 3lr|r W|l| ore
separalor W||| |ave lWo lo|ers, ore or eac|
s|de ol l|e separalor. Tne seararor ooesnr
oounr as a roken.

koses ote l|tst, v|olets ote next.


RenJers onJ wrirers ote only lot rexr.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
saving objects
460 chapter 14
Vcrs|en |P: B|] 8cr|z||zz!|en 0e!rhz
Now you`vc sccn ihai I/O in ]ava is aciually iciiy simlc, csccially il
you siicI io ihc mosi common conncciion/chain comlinaiions. Bui
ihcic`s onc issuc you mighi caic aloui.
Version Control is cruciall
Il you sciializc an ol|cci, you musi havc ihc class in oiuci io
ucsciializc anu usc ihc ol|cci. OK, ihai`s olvious. Bui whai mighi
lc lcss olvious is whai hacns il you chonge the cIoss in ihc
mcaniimc. YiIcs. Imaginc iiying io liing lacI a Dog ol|cci whcn
onc ol iis insiancc vaiiallcs non-iiansicni) has changcu liom a
uoullc io a Siiing. Thai violaics ]ava`s iyc-salc scnsililiiics in a Big
Way. Bui ihai`s noi ihc only changc ihai mighi huii comaiililiiy.
ThinI aloui ihc lollowing:
Changes to a class that can hurt deserialization:
Dclciing an insiancc vaiiallc
Changing ihc ucclaicu iyc ol an insiancc vaiiallc
Changing a non-iiansicni insiancc vaiiallc io iiansicni
Moving a class u oi uown ihc inhciiiancc hiciaichy
Changing a class anywhcic in ihc ol|cci giah) liom Sciializallc
io noi Sciializallc ly icmoving imlcmcnis Sciializallc` liom a
class ucclaiaiion)
Changing an insiancc vaiiallc io siaiic
Changes to a class that are usually OK:
Auuing ncw insiancc vaiiallcs io ihc class cxisiing ol|ccis will
ucsciializc wiih uclauli valucs loi ihc insiancc vaiiallcs ihcy uiun`i
havc whcn ihcy wcic sciializcu)
Auuing classcs io ihc inhciiiancc iicc
Rcmoving classcs liom ihc inhciiiancc iicc
Changing ihc acccss lcvcl ol an insiancc vaiiallc has no allcci on
ihc aliliiy ol ucsciializaiion io assign a valuc io ihc vaiiallc
Changing an insiancc vaiiallc liom iiansicni io non-iiansicni
icviously-sciializcu ol|ccis will simly havc a uclauli valuc loi ihc
icviously-iiansicni vaiiallcs)







1 You wrife o Dog cIoss


2
You serioIi;e o Dog objecf
using fhof cIoss
D
o
g obje
c
f

:|.:: --:-- |l
+
?+
?
Dog objecf
6-:l :
:l.-- -l
--:-- +
?+
?







3 You chonge fhe Dog cIoss


:|.:: --:-- |l
+7i
4
You deserioIi;e o Dog objecf
using fhe chonged cIoss
Dog objecf
6-:l :
:l.-- -l
--:-- +?+?







:|.:: --:-- :
+
7i
5
SeroiIi;ofion foiIsll
The JVM soys, "you con'f
feoch on oId Dog new code".
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 461
Each iimc an ol|cci is sciializcu, ihc ol|cci incluuing
cvciy ol|cci in iis giah) is siamcu` wiih a vcision
ID numlci loi ihc ol|cci`s class. Thc ID is callcu
ihc sciialVcisionUID, anu ii`s comuicu lascu on
inloimaiion aloui ihc class siiuciuic. As an ol|cci is
lcing ucsciializcu, il ihc class has changcu sincc ihc
ol|cci was sciializcu, ihc class coulu havc a uillcicni
sciialVcisionUID, anu ucsciializaiion will lail! Bui you
can coniiol ihis.
f you think there is ANY possibility that
your class might evolve, put a serial version
D in your class.
Whcn ]ava iiics io ucsciializc an ol|cci, ii comaics
ihc sciializcu ol|cci`s sciialVcisionUID wiih ihai ol ihc
class ihc ]VM is using loi ucsciializing ihc ol|cci. Ioi
cxamlc, il a Dog insiancc was sciializcu wiih an ID ol,
say 2S in icaliiy a sciialVcisionUID is much longci),
whcn ihc ]VM ucsciializcs ihc Dog ol|cci ii will hisi
comaic ihc Dog ol|cci sciialVcisionUID wiih ihc
Dog class sciialVcisionUID. Il ihc iwo numlcis uon`i
maich, ihc ]VM assumcs ihc class is noi comaiillc
wiih ihc icviously-sciializcu ol|cci, anu you`ll gci an
cxcciion uuiing ucsciializaiion.
So, ihc soluiion is io ui a sciialVcisionUID
in youi class, anu ihcn as ihc class cvolvcs, ihc
sciialVcisionUID will icmain ihc samc anu ihc ]VM
will say, OK, cool, ihc class is comaiillc wiih ihis
sciializcu ol|cci." cvcn ihough ihc class has aciually
changcu.
This woiIs il you`ic caiclul wiih youi class
changcs! In oihci woius, aic iaIing icsonsililiiy
loi any issucs ihai comc u whcn an oluci ol|cci is
lioughi lacI io lilc wiih a ncwci class.
To gci a sciialVcisionUID loi a class, usc ihc sciialvci
iool ihai shis wiih youi ]ava ucvclomcni Iii.
0s|n] !hc scr|z|Vcrs|en0|P
File Edit Window Help serialKiller
% serialver Dog
Dog: static final long
serialVersionUID = -
5849794470654667210L;
public class Dog {
static nal long serialVersionUID =
-6849794470754667710L;
private String name;
private int size;
// method code here
}
File Edit Window Help serialKiller
% serialver Dog
Dog: static final long
serialVersionUID = -
5849794470654667210L;
1 Use fhe serioIver commond-Iine fooI
fo gef fhe version ID for your cIoss
2 Posfe fhe oufpuf info your cIoss
3 8e sure fhof when you moke chonges fo
fhe cIoss, you foke responsibiIify in your
code for fhe consequences of fhe chonges
you mode fo fhe cIossl For exompIe, be
sure fhof your new Dog cIoss con deoI wifh
on oId Dog being deserioIi;ed wifh defouIf
voIues for insfonce voriobIes odded fo fhe
cIoss offer fhe Dog wos serioIi;ed.
When you think your class
might evolve after someone has
serialized ob]ects from it...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
462 chapter 14
CaJe kit:hea
Iet's a|e the 5eat5ax save aaJ
:esta:e aa: Iava:ite atte:a
w-- ]-- :|: :--.|--|l',
l- :-----l .ll--- -||
- :.-
--:l---' |-.: l- :.-
.ll--- .: -, .- --:-l:
l- :-:--:
Code Kitchen
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
seriaIization and fiIe I/O
you are here 463
Rcmcmlci, in ihc BcaiBox, a uium aiicin is noihing moic ihan a lunch ol
chccIloxcs. Whcn ii`s iimc io lay ihc scqucncc, ihc couc walIs ihiough ihc
chccIloxcs io hguic oui which uiums sounus aic laying ai cach ol ihc 16
lcais. So io savc a aiicin, all wc nccu io uo is savc ihc siaic ol ihc chccIloxcs.
Wc can maIc a simlc loolcan aiiay, holuing ihc siaic ol cach ol ihc 26
chccIloxcs. An aiiay ol|cci is sciializallc as long as ihc ihings .r ihc aiiay aic
sciializallc, so wc`ll havc no iioullc saving an aiiay ol loolcans.
To loau a aiicin lacI in, wc icau ihc singlc loolcan aiiay ol|cci ucsciializc
ii), anu icsioic ihc chccIloxcs. Mosi ol ihc couc you`vc alicauy sccn, in ihc
Couc Kiichcn whcic wc luili ihc BcaiBox GUI, so in ihis chaici, wc looI ai
only ihc savc anu icsioic couc.
This CoucKiichcn gcis us icauy loi ihc ncxi chaici, whcic insicau ol wiiiing
ihc aiicin io a Ie, wc scnu ii ovci ihc rewo.I io ihc scivci. Anu insicau ol
loauing a aiicin .r liom a hlc, wc gci aiicins liom ihc e..e., cach iimc a
aiiiciani scnus onc io ihc scivci.
8erializing a pattern
8zv|n] z Bcz!Ber pz!!crn
public class MySendListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
boolean[] checkboxState = new boolean[256];
for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (check.isSelected()) {
checkboxState[i] = true;
}
}
try {
FileOutputStream leStream = new FileOutputStream(new File(Checkbox.ser));
ObjectOutputStream os = new ObjectOutputStream(leStream);
os.writeObject(checkboxState);
} catch(Exception ex) {
ex.printStackTrace();
}
} // close method
} // close inner class
|l .|| .--: --- l- -:-- :|:: l-
-ll-- .- l- A:l--!--l --:
1: : .- ---- :|.:: -:-
l- B-.lB- :--
M.- . --|-.- .--.] l- -| l- :l.l- - -.: :-:-
w.| l--- l- :-:-|:l |A--.]|:l - :-:--:`, .- -l l- :l.l- - -.: ---, .- . l l- l- --|-.- .--.]
1: .-l': . -:- - :.- )-:l --l-/:--.|-- l- --- --|-.- .--.]'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
464 chapter 14
This is iciiy much ihc savc in icvcisc... icau ihc loolcan aiiay anu usc ii
io icsioic ihc siaic ol ihc GUI chccIloxcs. Ii all hacns whcn ihc usci hiis
ihc icsioic" luiion.
Restoring a pattern
Kcs!er|n] z Bcz!Ber pz!!crn
public class MyReadInListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
boolean[] checkboxState = null;
try {
FileInputStream leIn = new FileInputStream(new File(Checkbox.ser));
ObjectInputStream is = new ObjectInputStream(leIn);
checkboxState = (boolean[]) is.readObject();

} catch(Exception ex) {ex.printStackTrace();}
for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (checkboxState[i]) {
check.setSelected(true);
} else {
check.setSelected(false);
}
}
sequencer.stop();
buildTrackAndStart();
} // close method
} // close inner class
1: : .--l-- ---- :|.::
-:- l- B-.lB- :|.::
-. l- :-|- --:l - l- |- |l-
--|-.- .--.]` .- :.:l l .: l- .
--|-.- .--.] |-------, --.6-:l|`
--l---: . ------:- - l]- 6-:l
N-- --:l--- l- :l.l- - -.: - l-
:-:--: - l- A--.]|:l - .:l-.|
)c-:B- --:l: |:-:-|:l`
N-- :l- -.l--- : :-----l|] |.]-,
.- ---| l- :----:- -:- l- ---
:l.l- - l- :-:--: - l- A--.]|:l
deseriaIizing the pattern
+,-+ :+ ,-+:.|
This version has a huge limitation! when you hit the "serialize|t button, it
serializes automatically, to a file named "Checkbox.ser (which gets created if it
doesn't exist). 8ut each time you save, you overwrite the previously-saved file.
|mprove the save and restore feature, by incorporating a 1PileChooser so that
you can name and save as many different patterns as you like, and load/restore
from of your previously-saved pattern files.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 465
which of these do you think are, or should be,
serializableI |f not, why notI Not meaningfulI
Security riskI Only works for the current
execution of the 1vMI Make your best guess,
without looking it up in the AP|.
(zn ([y ,zv]/
Ob]ect type 8erializable? f not, why not?
Object Yes / No ______________________________________
String Yes / No ______________________________________
File Yes / No ______________________________________
Date Yes / No ______________________________________
OutputStream Yes / No ______________________________________
JFrame Yes / No ______________________________________
nteger Yes / No ______________________________________
System Yes / No ______________________________________
N08l`8 l08lF
C|rc|e l|e code lrarerls
l|al Wou|d corp||e (assur|r
l|ey're W|l||r a |ea| c|ass).
FileReader leReader = new FileReader();
BufferedReader reader = new BufferedReader(leReader);
FileOutputStream f = new FileOutputStream(new File(Foo.ser));
ObjectOutputStream os = new ObjectOutputStream(f);
BufferedReader reader = new BufferedReader(new FileReader(le));
String line = null;
while ((line = reader.readLine()) != null) {
makeCard(line);
}

ObjectInputStream is = new ObjectInputStream(new FileOutputStream(Game.ser));
GameCharacter oneAgain = (GameCharacter) is.readObject();
+,-+ :+ ,-+:.|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
466 chapter 14

This chapter explored the wonerful world of


1ava |/O. our |ob is to decide whether each
of the following |/O-related statements is
true or false.
1. Sciializaiion is aioiiaic whcn saving uaia loi non-]ava iogiams io usc.
2. Ol|cci siaic can lc savcu only ly using sciializaiion.
S. Ol|cciOuiuiSiicam is a class uscu io savc sciializcu ol|ccis.
4. Chain siicams can lc uscu on ihcii own oi wiih conncciion siicams.
. A singlc call io wiiicOl|cci) can causc many ol|ccis io lc savcu.
6. All classcs aic sciializallc ly uclauli.
7. Thc iiansicni mouihci allows you io maIc insiancc vaiiallcs sciializallc.
S. Il a suciclass is noi sciializallc ihcn ihc sulclass can`i lc sciializallc.
9. Whcn ol|ccis aic ucsciializcu, ihcy aic icau lacI in lasi-in, hisi oui scqucncc.
10. Whcn an ol|cci is ucsciializcu, iis consiiucioi uocs noi iun.
11. Boih sciializaiion anu saving io a icxi hlc can ihiow cxcciions.
12. BullcicuWiiicis can lc chaincu io IilcWiiicis.
1S. Iilc ol|ccis icicscni hlcs, lui noi uiiccioiics.
14. You can`i loicc a lullci io scnu iis uaia lcloic ii`s lull.
1. Boih hlc icaucis anu hlc wiiicis can lc lullcicu.
16. Thc Siiing slii) mcihou incluucs scaiaiois as ioIcns in ihc icsuli aiiay.
17. changc io a class licaIs icviously sciializcu ol|ccis ol ihai class.
fs-s cs |s.ss
exercise: True or FaIse
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 467
This one's tricky, so we promoted it from an Lxercise to full Puzzle status.
Peconstruct the code snippets to make a working 1ava program that
produces the output listed belowI (ou might not need all of the magnets,
and you may reuse a magnet more than once.)
public static void main{String args| {
DungeonGame d = new DungeonGame{|,
int getX{| {
return x,
public int x = 3,
transient long y = 4,
private short z = 5,
File Edit Window Help Torture
% java DungeonTest
12
8
class DungeonTest {
CaJe Kagaets
long getY{| {
return y,
short getZ{| {
return z,
d = {DungeonGame| ois.readObect{|,
} catch {Exception e| {
ois.close{|,
class DungeonGame implements Serializable {
e.printStackTrace{|,
FileOutputStream fos = new
FileOutputStream{"dg.ser"|,
oos.close{|,
fos.writeObect{d|,
ObectOutputStream oos = new
ObectOutputStream{fos|,
ObectInputStream ois = new
ObectInputStream{ s|,
oos.writeObect{d|,
try {
System.out.println{d.getX{|+d.getY{|+d.getZ{||,
FileInputStream s = new
FileInputStream{"dg.ser"|,
import ava.io.*,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
468 chapter 14
]e;ejze o|ajoz
1. Sciializaiion is aioiiaic whcn saving uaia loi non-]ava iogiams io usc.
2. Ol|cci siaic can lc savcu only ly using sciializaiion.
S. Ol|cciOuiuiSiicam is a class uscu io savc sciializcu ol|ccis.
4. Chain siicams can lc uscuon ihcii own oi wiih conncciion siicams.
. A singlc call io wiiicOl|cci) can causc many ol|ccis io lc savcu.
6. All classcs aic sciializallc ly uclauli.
7. Thc iiansicni mouihci allows you io maIc insiancc vaiiallcs sciializallc.
S. Il a suciclass is noi sciializallc ihcn ihc sulclass can`i lc sciializallc.
9. Whcn ol|ccis aic ucsciializcu ihcy aic icau lacI in lasi-in, hisi oui scqucncc.
10. Whcn an ol|cci is ucsciializcu, iis consiiucioi uocs noi iun.
11. Boih sciializaiion anu saving io a icxi hlc can ihiow cxcciions.
12. BullcicuWiiicis can lc chaincu io IilcWiiicis.
1S. Iilc ol|ccis icicscni hlcs, lui noi uiiccioiics.
14. You can`i loicc a lullci io scnu iis uaia lcloic ii`s lull.
1. Boih hlc icaucis anu hlc wiiicis can oiionally lc lullcicu.
16. Thc Siiing slii) mcihou incluucs scaiaiois as ioIcns in ihc icsuli aiiay.
17. changc io a class licaIs icviously sciializcu ol|ccis ol ihai class.

exercise soIutions
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 469
File Edit Window Help Escape
% java DungeonTest
12
8
import ava.io.*,
class DungeonGame implements Serializable {
public int x = 3,
transient long y = 4,
private short z = 5,
int getX{| {
return x,
}
long getY{| {
return y,
}
short getZ{| {
return z,
}
}
class DungeonTest {
public static void main{String args| {
DungeonGame d = new DungeonGame{|,
System.out.println{d.getX{| + d.getY{| + d.getZ{||,
try {
FileOutputStream fos = new FileOutputStream{"dg.ser"|,
ObectOutputStream oos = new ObectOutputStream{fos|,
oos.writeObect{d|,
oos.close{|,
FileInputStream s = new FileInputStream{"dg.ser"|,
ObectInputStream ois = new ObectInputStream{s|,
d = {DungeonGame| ois.readObect{|,
ois.close{|,
} catch {Exception e| {
e.printStackTrace{|,
}
System.out.println{d.getX{| + d.getY{| + d.getZ{||,
}
}
0ood fhing we're
fnoIIy of fhe onswers.
I wos geffin' kind of
fired of fhis chopfer.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Make a Connection
15 networking and threads
Connect with the outside worId. our 1ava program can reach out and touch a
program on another machine. |t's easy. All the low-level networking details are taken care of by
classes in the |ava.net library. One of 1ava's big benefits is that sending and receiving data over
a network is |ust |/O with a slightly different connection stream at the end of the chain. |f you've
got a 8ufferedPeader, you can teoJ. And the 8ufferedPeader could care less if the data came
out of a file or flew down an ethernet cable. |n this chapter we'll connect to the outside world
with sockets. we'll make cl|ent sockets. we'll make setvet sockets. we'll make cl|ents and setvets.
And we'll make them talk to each other. 8efore the chapter's done, you'll have a fully-functional,
multithreaded chat client. Did we |ust say mult|thteoJeJI es, now you w|ll learn the secret of
how to talk to 8ob while simultaneously listening to Suzy.
this is a new chapter 471
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
472 chapter 15
sky|er4: fast and funky, good for sequence 12
evster2: ||ke sky|er2, but more 0akenfo|d|sh
sky|er5: you w|8h! Too perky
try th|s one... |t's better for
sequence 8
beat box chat
Kcz|-!|mc Bcz! Ber 0hz!
You`ic woiIing on a comuici gamc. You anu youi icam
aic uoing ihc sounu ucsign loi cach aii ol ihc gamc.
Using a chai` vcision ol ihc Bcai Box, youi icam can
collaloiaic-you can scnu a lcai aiicin along wiih
youi chai mcssagc, anu cvciylouy in ihc Bcai Box Chai
gcis ii. So you uon`i |usi gci io .enJ ihc oihci
aiiicianis` mcssagcs, you gci io loau anu
In, a lcai aiicin simly ly clicIing ihc
mcssagc in ihc incoming mcssagcs aica.
In ihis chaici wc`ic going io lcain whai ii
iaIcs io maIc a chai clicni liIc ihis. Wc`ic
cvcn going io lcain a liiilc aloui maIing a
chai e..e.. Wc`ll savc ihc lull Bcai Box Chai
loi ihc Couc Kiichcn, lui in ihis chaici you
w.II wiiic a Iuuiciously Simlc Chai Clicni anu
Vciy Simlc Chai Scivci ihai scnu anu icccivc
icxi mcssagcs.
:|:- -- . --:-- --::.-
|-.: l- .ll--- l.l ---l
-l l
1]- . --::.- .-
--:: l- :--|l -ll--
l- :-- ]--- --::.-
ANl ]--- :-----l -.l
.ll---
/-- :.- .- :--|-l-|]
.-l--l:, -l-||-:l-.||]
:l--|.l- :.l
:----:.l--: !--]
--::.- : :--l l- .||
.-l:.-l:
-- ]--- --::.- l- l- :----
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 473
Why am
here? Don't
expect ME to
answer that.
Why am
here? Don't
expect ME to
answer that.
Why am
here? Don't
expect ME to
answer that.
[[ (]jn( [z, ( [nw
za( ([ v.
[[ v [z, ( [nw
za( jjj ([ (]jn(,.
Chat Program Overview

CIienf connecfs fo fhe server

The server mokes o


connecfion ond odds fhe cIienf
fo fhe Iisf of porficiponfs

Anofher cIienf connecfs

CIienf A sends o messoge fo


fhe chof service
CIienf A
CIienf 8
CIienf C

fhere ore currenfIy


3 porficiponfs in
fhis chof session:
CIienf A, CIienf 8
ond CIienf C

CIienf A
----, |' |- l- :----:l
l- l- :.l :--:-
CIienf A
6r, ]--'-- -
Part|c|pants:
1. 6||ent A

Why am here?
Don't expect
ME to answer
that. So, why am
CIienf 8
Part|c|pants:
1. 6||ent A
2. 6||ent

Why am here?
Don't expect
ME to answer
that. So, why am
CIienf A
How it Works:
Hessage
rece|ved

The server disfribufes fhe


messoge fo ALL porficiponfs
(incIuding fhe originoI sender)
Why am here?
Don't expect
ME to answer
that. So, why am
CIienf A
Hessage
d|str|buted to
a|| part|c|pants
Why am here?
Don't expect
ME to answer
that. So, why am
CIienf 8
wa|t|ng for
c||ent requests
6r, ]--'-- -
----, |' |- l- :----:l
l- l- :.l :--:-
w- l-- l- |.. |.-
--- -] --- ----'
w- l-- l- |.. |.-
--- -] --- ----'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
socket connections
474 chapter 15
0enncr!|n], 8cn4|n], zn4 Kcrc| v|n]
Thc ihicc ihings wc havc io lcain io gci ihc clicni woiIing aic :
1) How io csiallish ihc iniiial conncction lciwccn ihc clicni anu scivci
2) How io scnd mcssagcs o ihc scivci
S) How io rcccivc mcssagcs .o ihc scivci
Thcic`s a loi ol low-lcvcl siull ihai has io hacn loi ihcsc ihings io woiI. Bui wc`ic
lucIy, lccausc ihc ]ava API nciwoiIing acIagc |ava.nci) maIcs ii a iccc ol caIc
loi iogiammcis. You`ll scc a loi moic GUI couc ihan nciwoiIing anu I/O couc.
Anu ihai`s noi all.
IuiIing wiihin ihc simlc chai clicni is a iollcm wc havcn`i laccu so lai in ihis
looI: uoing iwo ihings ai ihc samc iimc. Esiallishing a conncciion is a onc-iimc
ociaiion ihai ciihci woiIs oi lails). Bui alici ihai, a chai aiiiciani wanis io
erJ ouo.r ene anu simultancously .ee..e .ro.r ene liom ihc oihci
aiiicianis via ihc scivci). Hmmmm... ihai onc`s going io iaIc a liiilc ihoughi, lui
wc`ll gci ihcic in |usi a lcw agcs.
Connect

CIienf connecfs fo fhe server by


esfobIishing o Socket connecfion.
CIienf A
chat server at
19.14.1.103,
port 5000
M.- . :-:-l :----:l-- l-
||||+||o? .l --l -ooo
Server
8end

CIienf sends o messoge fo fhe server


CIienf A
8erver
mach|ne at
19.14.1.103
--l----l|-|.M-::.-`
Server
Receive

CIienf gets o messoge from fhe server


CIienf A
8erver
mach|ne at
19.14.1.103
l-- : = --.----.|--|`
Server
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 475
Mzkc z nc! werk 8erkc! renncr!|en
To conncci io anoihci machinc, wc nccu a SocIci conncciion.
A SocIci |ava.nci.SocIci class) is an ol|cci ihai icicscnis
a nciwoiI conncciion lciwccn iwo machincs. Whai`s a
conncciion. A .eIn.orL. lciwccn iwo machincs, whcic two
picccs oI soItwarc know about cach othcr. Mosi imoiianily,
ihosc iwo icccs ol soliwaic Inow how io our.ne wiih
cach oihci. In oihci woius, how io scnu b. io cach oihci.
Wc uon`i caic aloui ihc low-lcvcl uciails, ihanIlully, lccausc
ihcy`ic hanulcu ai a much lowci lacc in ihc nciwoiIing
siacI`. Il you uon`i Inow whai ihc nciwoiIing siacI` is, uon`i
woiiy aloui ii. Ii`s |usi a way ol looIing ai ihc laycis ihai
inloimaiion liis) musi iiavcl ihiough io gci liom a ]ava
iogiam iunning in a ]VM on somc OS, io hysical haiuwaic
cihcinci callcs, loi cxamlc), anu lacI again on somc oihci
machinc. SoeboJ, has io iaIc caic ol all ihc uiiiy uciails.
Bui noi you. Thai somclouy is a comlinaiion ol OS-sccihc
soliwaic anu ihc ]ava nciwoiIing API. Thc aii ihai you havc
io woiiy aloui is high-lcvcl-maIc ihai .e., high-lcvcl-anu
shocIingly simlc. Rcauy.
Socket chatSocket = new Socket(196.164.1.103, 5000);
|| .--:: -- l- :----
[ z[ z e[(
enne(jn, ya n]
( [nw (w ([jng,
za( ([ ,v w[
j( j,, zn] w[je[ (
j(', annjng n.
]n ([ w],,
]] z]],, zn] [(]
( na.
1
c| --l -----
-:-l :----:l-- l- --l -ooo
-- l- :---- .l ||||+
||o?
-:-l :----:l--
.: l- l- :|--l .l
||||+
||o
o
, --l
+
i
+
i
j e[( enne(jn zn, ([ (w ze[jn, [zv
jn|z(jn za( ze[ ([, jne]a]jng n(w[
]ez(jn (]] z]],,) zn] [(] (.
Server CIient
This cIienf is of
I9o.Io4.I.I00, porf 4Z4Z.
When I need fo foIk fo
him, fhof's where I'II send
fhe messoge.
The chof server is of
I9o.Io4.I.I03, porf b000.
When I need fo foIk fo him,
fhof's where I'II send
fhe messoge.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
476 chapter 15
I0| per! |s jes! z nem|cr.
15-|| ! nem|cr !hz! |4cn!|f|cs
z spcr|f|r pre]rzm en !hc scrvcr.
Youi inicinci wcl HTTP) scivci iuns on oii S0. Thai`s a
sianuaiu. Il you`vc goi a Tclnci scivci, iis iunning on oii
2S. ITP. 20. POPS mail scivci. 110. SMTP. 2. Thc Timc
scivci siis ai S7. ThinI ol oii numlcis as uniquc iucniihcis.
Thcy icicscni a logical conncciion io a aiiiculai iccc ol
soliwaic iunning on ihc scivci. Thai`s ii. You can`i sin youi
haiuwaic lox aiounu anu hnu a TCP oii. Ioi onc ihing,
you havc 6S6 ol ihcm on a scivci 0 - 6S). So ihcy
olviously uon`i icicscni a lacc io lug in hysical ucviccs.
Thcy`ic |usi a numlci icicscniing an alicaiion.
Wiihoui oii numlcis, ihc scivci woulu havc no way ol
Inowing which alicaiion a clicni wanicu io conncci io.
Anu sincc cach alicaiion mighi havc iis own uniquc
ioiocol, ihinI ol ihc iioullc you`u havc wiihoui ihcsc
iucniihcis. Whai il youi wcl liowsci, loi cxamlc, lanucu
ai ihc POPS mail scivci insicau ol ihc HTTP scivci. Thc
mail scivci won`i Inow how io aisc an HTTP icqucsi! Anu
cvcn il ii uiu, ihc POPS scivci uocsn`i Inow anyihing aloui
scivicing ihc HTTP icqucsi.
Whcn you wiiic a scivci iogiam, you`ll incluuc couc ihai
iclls ihc iogiam which oii numlci you wani ii io iun on
you`ll scc how io uo ihis in ]ava a liiilc laici in ihis chaici).
In ihc Chai iogiam wc`ic wiiiing in ihis chaici, wc icIcu
000. ]usi lccausc wc wanicu io. Anu lccausc ii mci ihc
ciiiciia ihai ii lc a numlci lciwccn 1024 anu 6S. Why
1024. Bccausc 0 ihiough 102S aic icscivcu loi ihc wcll-
Inown sciviccs liIc ihc oncs wc |usi ialIcu aloui.
Anu il you`ic wiiiing sciviccs scivci iogiams) io iun on
a comany nciwoiI, you shoulu chccI wiih ihc sys-aumins
io hnu oui which oiis aic alicauy iaIcn. Youi sys-aumins
mighi icll you, loi cxamlc, ihai you can`i usc any oii
numlci lclow, say, S000. In any casc, il you valuc youi limls,
you won`i assign oii numlcis wiih alanuon. Unlcss ii`s
youi Loe nciwoiI. In which casc you |usi havc io chccI wiih
youi I.J.
i? io i-
?7
||o
|1
|
1-|--l
|6|?
M
1
|
1--
o
++?
+
1
1
| +11|

WeII-known TCP porf numbers


for common server oppIicofions
[[ [(] (
na, | e ( Je|
z ,v] | w]]-
[nwn ,vje,. ]n'(
a, ([ | ya wn
,v gz,[*
[[ e[z( ,v w'
wj(jng a,, (
5eee. y ja,( je[] z
na (wn Je|
zn] 555|5.
*Well, you be able to use one of
these, but the sys-admin where you
work will probably kill you.
A :---- :.- .- - l- |--?|
----l :---- .: -----,
--- -- --l
weII-known ports
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 477
IP oddress is Iike specifying o
porficuIor shopping moII, soy,
"FIofirons MorkefpIoce"
Porf number is Iike noming
o specifc sfore, soy,
"8ob's CD Shop"
|| .--:: : l- -.||
|--l ----- : l- :-::
:l--- - l- -.||
Server
CIient
c.l :----
---.-

8f8l 88f00ll
OK, you got a Socket connection. The client and the
server know the |P address and TCP port number for
each other. Now whatI How do you communicate
over that connectionI |n other words, how do you
move bits from one to the otherI |magine the kinds of
messages your chat client needs to send and receive.
+-- - l-:- l--
.:l-.||] l.| l-
-.: -l--
(-,- a,- |
oa|| qa--(:|-

How do you know the port
number of the server program you
want to taIk to!

That depends on whether the
program is one of the well-known
services. |f you're trying to connect
to a well-known service, like the ones
on the opposite page (HTTP, SMTP,
PTP, etc.) you can look these up on
the internet (Google "well-Known
TCP Port). Or ask your friendly
neighborhood sys-admin.
8ut if the program isn't one of the
well-known services, you need to
find out from whoever is deploying
the service. Ask him. Or her. Typically,
if someone writes a network service
and wants others to write clients for
it, they'll publish the |P address, port
number, and protocol for the service.
Por example, if you want to write a
client for a GO game server, you can
visit one of the GO server sites and
find information about how to write a
client for that particular server.

Can there ever be more than
one program running on a singIe
port! In other words, can two
appIications on the same server have
the same port number!

No! |f you try to bind a program
to a port that is already in use, you'll
get a 8indLxception. To a program
to a port |ust means starting up a
server application and telling it to run
on a particular port. Again, you'll learn
more about this when we get to the
server part of this chapter.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
478 chapter 15
To communicaic ovci a SocIci conncciion, you usc siicams.
Rcgulai olu I/O siicams, |usi liIc wc uscu in ihc lasi chaici. Onc
ol ihc coolcsi lcaiuics in ]ava is ihai mosi ol youi I/O woiI won`i
caic whai youi high-lcvcl chain siicam is aciually connccicu io. In
oihci woius, you can usc a BullcicuRcauci |usi liIc you uiu whcn
you wcic wiiiing io a hlc, ihc uillcicncc is ihai ihc unucilying
conncciion siicam is connccicu io a SoIe iaihci ihan a E.Ie
Ie rcz4 4z!z frem z 8erkc!, esc z
Beffcrc4Kcz4cr
Socket chatSocket = new Socket(127.0.0.1, 5000);
|i7oo| : l- || .--:: -- |-:.|-:l', -
-l-- ---:, l- --- l: :-- : ----- -- /--
:.- -:- l: --- ]--'-- l-:l- ]--- :|--l .-
:---- -- . :-|-, :l.-~.|--- -.:--

Muke u Socket connection to the server


BufferedReader reader = new BufferedReader(stream);
String message = reader.readLine();

Muke u ufferedPeuder und reud|


c.- l- B-----.-- l- l-
|--ll--.--.--|-: -.: :.-- l- l- |--~
|--| :----:l-- :l--.- -- -l --- l- -:-l`
1- --l -----, -: ]-- ---
-:.-:- -- 16|l ]-- l.l -ooo :
l- --l ----- -- --- :.l :----
InputStreamReader stream = new InputStreamReader(chatSocket.getInputStream());

Muke un InputStreumPeuder chuined to the Socket's


Iow-IeveI {connection} input streum
|--ll--.--.-- : . '--' -l---- . |--~
|--| ]l- :l--.- ||- l- --- :--- --- l-
-:-l` .- . ~|--| :.-.:l-- :l--.- ||-
l- B-----.-- --'-- .l-- .: --- l- -
l- :.- :l--.-`
CIient
Sockef's inpuf sfreom
(we don'f need fo know
fhe ocfuoI cIoss)
0II0I00II
byfes from server
:---:-
choined fo
A|| -- .- l- - : Ar l- :-:-l -- .- --l :l--.-' |l': . |--~|--| :----:l-- :l--.-, -l --'-- -:l ---. :.- l l- :---l- ---- l-l~---|]
Dofo on fhe
server chorocfers
-:l-.l--
InpufSfreomPeoder
choined fo
buffered
chorocfers
8ufferedPeoder
converfed fo chorocfers buffered chorocfers
Server
--l .- --l-l :l--.-:
l- .- --- l- -:-l
:----:l--:
reading from a socket
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 479
Wc uiun`i usc PiiniWiiici in ihc lasi chaici, wc uscu BullcicuWiiici. Wc havc
a choicc hcic, lui whcn you`ic wiiiing onc Siiing ai a iimc, PiiniWiiici is ihc
sianuaiu choicc. Anu you`ll iccognizc ihc iwo Icy mcihous in PiiniWiiici,
iini) anu iiniln)! ]usi liIc goou ol` Sysicm.oui.
Ie wr| !c 4z!z !e z 8erkc!, esc z
|r|n!Wr| !cr
Socket chatSocket = new Socket(127.0.0.1, 5000);

Muke u Socket connection to the server


writer.println(message to send);
writer.print(another message);

Write {print} something


--l|-|` .: . --- |-- .l l- -- - -.l l :--:
--l|` --:-'l . l- --- |--
l: .-l': l- :.-- .: l -.: -- l-
--:l- .- ~~ l- --l- l- l-
:----, -- :l|| .- l- :----:l l- l
PrintWriter writer = new PrintWriter(chatSocket.getOutputStream());

Muke u PrintWriter chuined to the Socket's Iow-IeveI


{connection} output streum
|--lw-l-- .:l: .: l: --- -- -l----
:.-.:l-- .l. .- l- ]l-: l -l: --- l-
-:-l': |--~|--| --l-l :l--.- B] :.-- .
|--lw-l-- l- l- -:-l': --l-l :l--.-, --
:.- --l- l--: l- l- -:-l :----:l--
CIient
Sockef's oufpuf
sfreom (we don'f need
fo know fhe ocfuoI cIoss)
0II0I00II
byfes fo server
-:l-.l--
choined fo
1- -:-l -: -: . |--~|--| :----:l-- :l--.- .- -- :.- l l- l- |--lw-l-- ] - l l- l- |--lw-l-- :--:l--:l--
Chof server
progrom
:---:-
"messoge..."
PrinfWrifer
chorocfers
Server
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
480 chapter 15
Bcloic wc siaii luiluing ihc Chai a,
lci`s siaii wiih somcihing a liiilc smallci.
Thc Auvicc Guy is a scivci iogiam ihai
ollcis u iaciical, insiiaiional iis
io gci you ihiough ihosc long uays ol
couing.
Wc`ic luiluing a clicni loi Thc Auvicc
Guy iogiam, which ulls a mcssagc
liom ihc scivci cach iimc ii connccis.
Whai aic you waiiing loi. Who
whai ooiiuniiics you`vc misscu
wiihoui ihis a.
Ihc Pz||y4v|rc0||cn!
Treof yourseIf fo
o coId onel You
deserve ifl
TeII your boss
fhe reporf wiII
hove fo woif. There's
powder of Aspenl
Thof shode of
green isn'f reoIIy
workin' for you...
[[ j]vje (ay
Connect

CIienf connecfs fo fhe server ond gefs on


inpuf sfreom from if
CIienf
adv|ce server
at 190.15.1.103,
port 4242
M.- . :-:-l :----:l-- l-
|o||-||o? .l --l +i+i

Read

CIienf reods o messoge from fhe server


CIienf A
adv|ce server
composes
adv|ce and
sends |t
.:- = --.----.|--|`

:-:-l-l|--ll--.-|`
writing a cIient
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 481
import java.io.*;
import java.net.*;
public class DailyAdviceClient {
public void go() {
try {
Socket s = new Socket(127.0.0.1, 4242);
InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
String advice = reader.readLine();
System.out.println(Today you should: + advice);
reader.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
DailyAdviceClient client = new DailyAdviceClient();
client.go();
}
}
Pz||y4v|rc0||cn! re4c
:|.:: -:-l : - ..--l
-.- . -:-l :----:l-- l- -.l--- :
----- -- --l +i+i, -- l- :.-- -:l
l: :-- : ----- -- |1- '|-:.|-:l'`
. |-l :.- - ---- ---
:.- . B-----.-- l-
.- |--ll--.--.-- l-
l- --l :l--.- --- l-
-:-l
l: --.|--|` : !xAc1|/
l- :.-- .: ]-- ---- -:- .
B-----.-- :.-- l- . |||!
|- -l-- ---:, ] l- l-- ]--
:.|| . B----w-l-- --l-, l-
--l-- --:-'l --- -- :.-- ----
l- :.-.:l--: :.-- ---
l: :|-:-: A|| l- :l--.-:
This progrom mokes o Sockef, mokes o 8ufferedPeoder (wifh fhe
heIp of ofher sfreoms), ond reods o singIe Iine from fhe server
oppIicofion (whofever is running of porf 4Z4Z).
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
socket connections
482 chapter 15
+,-+ :+ ,-+:.|
Test your memory of the streams/classes for reading and writing from a
Socket. Try not to look at the opposite page!
CIient
Server
To text from a Socket:
:---:-
--l-/-.- - l- :.- - :l--.-: l- :|--l
-:-: l- --. --- l- :----
CIient
Server
To text to a Socket:
-:l-.l--
--l-/-.- - l- :.- - :l--.-: l- :|--l
-:-: l- :-- :---l- l- l- :----
+,-+ :+ ,-+:.|
what two pieces of information does the client need in order to make a
Socket connection with a serverI
FiII in the bIanks:
which TCP port numbers are reserved for 'well-known services' like HTTP and PTPI
TPUL or PALSL: The range of valid TCP port numbers can be represented
by a short primitiveI
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 483
Wr| !|n] z s|mp|c scrvcr
So whai`s ii iaIc io wiiic a scivci alicaiion. ]usi a
coulc ol SocIcis. Ycs, a coulc as in . A ScivciSocIci,
which waiis loi clicni icqucsis whcn a clicni maIcs a
ncw SocIci)) anu a lain olu SocIci socIci io usc loi
communicaiion wiih ihc clicni.
-----:-l

Server oppIicofion mokes o ServerSockef, on o specifc porf


How it Works:
ServerSocket serverSock = new ServerSocket(4242);

-----:-l

CIienf mokes o Sockef connecfion fo fhe server oppIicofion


Socket sock = new Socket(190.165.1.103, 4242);

-:-l
-----:-l |-.l-
-- l- --l :|--l`

Server mokes o new Sockef fo communicofe wifh fhis cIienf


Socket sock = serverSock.accept();

-:-l
-:-l
This sforfs fhe server oppIicofion Iisfening
for cIienf requesfs coming in for porf 4Z4Z.
CIienf knows fhe IP oddress ond porf number
(pubIished or given fo him by whomever
confgures fhe server opp fo be on fhof porf)
The occepf() mefhod bIocks (jusf sifs fhere) whiIe
if's woifing for o cIienf Sockef connecfion. When o
cIienf fnoIIy fries fo connecf, fhe mefhod refurns
o pIoin oId Sockef (on o differenf porf) fhof knows
how fo communicofe wifh fhe cIienf (i.e., knows fhe
cIienf's IP oddress ond porf number). The Sockef is on
o differenf porf fhon fhe ServerSockef, so fhof fhe
ServerSockef con go bock fo woifing for ofher cIienfs.

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
484 chapter 15
import java.io.*;
import java.net.*;
public class DailyAdviceServer {
String[] adviceList = {Take smaller bites, Go for the tight jeans. No they do NOT
make you look fat., One word: inappropriate, Just for today, be honest. Tell your
boss what you *really* think, You might want to rethink that haircut.};
public void go() {
try {
ServerSocket serverSock = new ServerSocket(4242);

while(true) {
Socket sock = serverSock.accept();

PrintWriter writer = new PrintWriter(sock.getOutputStream());
String advice = getAdvice();
writer.println(advice);
writer.close();
System.out.println(advice);
}
} catch(IOException ex) {
ex.printStackTrace();
}
} // close go
private String getAdvice() {
int random = (int) (Math.random() * adviceList.length);
return adviceList[random];
}

public static void main(String[] args) {
DailyAdviceServer server = new DailyAdviceServer();
server.go();
}
}
Pz||y4v|rc8crvcr re4c
This iogiam maIcs a ScivciSocIci anu waiis loi clicni icqucsis. Whcn ii gcis
a clicni icqucsi i.c. clicni saiu ncw SocIci) loi ihis alicaiion), ihc scivci
maIcs a ncw SocIci conncciion io ihai clicni. Thc scivci maIcs a PiiniWiiici
using ihc SocIci`s ouiui siicam) anu scnus a mcssagc io ihc clicni.
------- l- ---l:
.|] .:- :---: --- l: .--.]
-----:-l -.-: l: :----
.|:.l-- '|:l--' -- :|--l ----:l:
-- --l +i+i -- l- -.:-- l:
:-- : ----- --
1- :---- --: -l- . ---.---l |--,
-.l- -- |.- :--:-` :|--l ----:l:
l- .::-l --l- |-:: |-:l :l: l---` --l| .
----:l :---: -, .- l-- l- --l- --l---: .
-:-l |-- :--- .---]---: --l` -- :-----:.l-
-l l- :|--l
--- -- -:- l- -:-l :----:l-- l- l- :|--l l-
-.- . |--lw-l-- .- :-- l |--l|-|`` . l--
.:- --::.- 1-- -- :|-:- l- -:-l -:.-:-
--'-- --- -l l: :|--l
writing a server
|-------, l-:- l--:
---- ---~--.- ]
l- :-- -l-- N---
l --l--- - l- -|-
- . l--'`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 485
8ll P0lk5
C||erl ard server app||cal|ors corrur|cale over a 3oc|el
correcl|or.
A 3oc|el represerls a correcl|or oelWeer lWo app||cal|ors
W||c| ray (or ray rol) oe rurr|r or lWo d|llererl p|ys|ca|
rac||res.
A c||erl rusl |roW l|e lP address (or dora|r rare) ard
TCP porl ruroer ol l|e server app||cal|or.
A TCP porl |s a 1-o|l urs|red ruroer ass|red lo a
spec|l|c server app||cal|or. TCP porl ruroers a||oW d|llererl
c||erls lo correcl lo l|e sare rac||re oul corrur|cale
W|l| d|llererl app||cal|ors rurr|r or l|al rac||re.
T|e porl ruroers lror 0 l|rou| 1023 are reserved lor
'We||-|roWr serv|ces' |rc|ud|r lTTP, FTP, 3VTP, elc.
A c||erl correcls lo a server oy ra||r a 3erver soc|el
Socket s = new Socket(127.0.0.1, 4200);
0rce correcled, a c||erl car el |rpul ard oulpul slrears
lror l|e soc|el. T|ese are |oW-|eve| 'correcl|or' slrears.
sock.getInputStream();
To read lexl dala lror l|e server, creale a 8ulleredReader,
c|a|red lo ar lrpul3lrearReader, W||c| |s c|a|red lo l|e
|rpul slrear lror l|e 3oc|el.
lrpul3lrearReader |s a 'or|de' slrear l|al la|es |r
oyles ard corverls l|er lo lexl (c|aracler) dala. ll's used
pr|rar||y lo acl as l|e r|dd|e c|a|r oelWeer l|e |||-|eve|
8ulleredReader ard l|e |oW-|eve| 3oc|el |rpul slrear.
To Wr|le lexl dala lo l|e server, creale a Pr|rlwr|ler c|a|red
d|recl|y lo l|e 3oc|el's oulpul slrear. Ca|| l|e pr|rl() or
pr|rl|r() rel|ods lo serd 3lr|rs lo l|e server.
3ervers use a 3erver3oc|el l|al Wa|ls lor c||erl requesls or
a parl|cu|ar porl ruroer.
w|er a 3erver3oc|el els a requesl, |l 'accepls' l|e requesl
oy ra||r a 3oc|el correcl|or W|l| l|e c||erl.
H
a
S
se
in
H
w
S
S
ca
cl
H
S
B
M
2
It
h
sa

8f8l 88f00ll
Rew Jees rhe server knew hew re
cemmunicnre wirh rhe clienr?
The client knows the |P address and port
number of the server, but how is the server
able to make a Socket connection with the
client (and make input and output streams)I
Think about how / when / where the server
gets knowledge about the client.
(-,- a,- |
oa|| qa--(:|-

7he advice server code on the opposite


page has a VRY serious Iimitation-it Iooks
Iike it can handIe onIy one cIient at a timel

es, that's right. |t can't accept a request


from a client until it has finished with the
current client and started the next iteration of
the infinite loop (where it sits at the accept()
call until a request comes in, at which time it
makes a Socket with the new client and starts
the process over again).

Let me rephrase the probIem: how can


you make a server that can handIe muItipIe
cIients concurrentIy!!! 7his wouId never
work for a chat server, for instance.

Ah, that's simple, really. Use separate


threads, and give each new client Socket to a
new thread. we're |ust about to learn how to
do that!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
486 chapter 15
Wr| !|n] z 0hz! 0||cn!
Wc`ll wiiic ihc Chai clicni alicaiion in iwo siagcs. Iiisi wc`ll
maIc a scnu-only vcision ihai scnus mcssagcs io ihc scivci lui
uocsn`i gci io icau any ol ihc mcssagcs liom oihci aiiicianis
an cxciiing anu mysiciious iwisi io ihc wholc chai ioom
concci).
Thcn wc`ll go loi ihc lull chai moniy anu maIc onc ihai loih
scnus icccivcs chai mcssagcs.
Version One: send-only
public class SimpleChatClientA {

JTextField outgoing;
PrintWriter writer;
Socket sock;
public void go() {
// make gui and register a listener with the send button
// call the setUpNetworking() method
}
private void setUpNetworking() {
// make a Socket, then make a PrintWriter
// assign the PrintWriter to writer instance variable
}
public class SendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
// get the text from the text eld and
// send it to the server using the writer (a PrintWriter)
}
} // close SendButtonListener inner class
} // close outer class
Code outline
1]- . --::.-, l-- --:: '--'
l- :-- l l- l- :---- w-
---'l -l .-] --::.-: |6M l-
:---- - l: --:--, :- l---':
-- ::--||- l-l .--.
a simpIe chat cIient
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 487
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleChatClientA {

JTextField outgoing;
PrintWriter writer;
Socket sock;
public void go() {
JFrame frame = new JFrame(Ludicrously Simple Chat Client);
JPanel mainPanel = new JPanel();
outgoing = new JTextField(20);
JButton sendButton = new JButton(Send);
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(outgoing);
mainPanel.add(sendButton);
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
setUpNetworking();
frame.setSize(400,500);
frame.setVisible(true);
} // close go
private void setUpNetworking() {
try {
sock = new Socket(127.0.0.1, 5000);
writer = new PrintWriter(sock.getOutputStream());
System.out.println(networking established);
} catch(IOException ex) {
ex.printStackTrace();
}
} // close setUpNetworking
public class SendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
writer.println(outgoing.getText());
writer.ush();

} catch(Exception ex) {
ex.printStackTrace();
}
outgoing.setText();
outgoing.requestFocus();
}
} // close SendButtonListener inner class
public static void main(String[] args) {
new SimpleChatClientA().go();
}
} // close outer class
---l: -- l- :l--.-: |..-`,
-:-l |..--l` .- l- 6c|
:l-
-| l- 6c|, --l- ---
---, .- --l- --|.l- l-
--l---- -- |/6
1: : ---- -- -.- l- -:-l
.- l- |--lw-l-- |l': :.||-
--- l- -|` --l- -l ----
:|.]- l- . 6c|`
N-- -- .:l-.||] - l- --l-
------, l- --l-- : :.-- l-
l- --l :l--.- --- l- -:-l, :-
------ -- - . --l|-|`, l --:
--- l- --l--- l- l- :----'
--'-- -:- |-:.|-:l :-
]-- :.- l-:l l- :|--l
.- :---- -- --- -.:--
f you want to try this now, type in
the Ready-bake chat server code
listed at the end of this chapter .
First, start the server in one terminal.
Next, use another terminal to start
this client.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
488 chapter 15
Version Two: send
and receive
1- ---- :--: . --::.- l- .||
:|--l .-l:.-l:, .: :--- .: l-
--::.- : --:-- ] l- :----
w-- . :|--l :--: . --::.-, l
--:-'l .-.- - l- -:---
--::.- :|.] .--. --l| l-
:---- :--: l l- ---]---
--l-- --::.-
-:---
--::.-:
Big Ouestion: HOW do you get messages from the server?
Shoulu lc casy, whcn you sci u ihc nciwoiIing maIc an inui siicam as wcll
iolally a BullcicuRcauci). Thcn icau mcssagcs using icauIinc).
Bigger Ouestion: WHEN do you get messages from the server?
ThinI aloui ihai. Whai aic ihc oiions.
Wcll, ii`s uo-allc
How uocs ihc scivci Inow whai you`vc sccn anu whai you havcn`i. Thc scivci
woulu havc io sioic ihc mcssagcs, iaihci ihan |usi uoing a uisiiiluic-anu-loigci cach iimc
ii gcis onc. Anu why 20 scconus. A uclay liIc ihis allccis usaliliiy, lui as you icuucc ihc
uclay, you iisI hiiiing youi scivci ncculcssly. Inclhcicni.
1 Option One: Poll the server every 20 seconds
2 Option Two: Read something in from the server each time the user
sends a message.
Do-allc, vciy casy
Cons: Siuiu. Why choosc such an ailiiiaiy iimc io chccI loi mcssagcs. Whai il a usci is
a luiIci anu uocsn`i scnu anyihing.

Option Three: Read messages as soon as they're sent from the server
Mosi clhcicni, lcsi usaliliiy
Cons: How uo you uo you uo iwo ihings ai ihc samc iimc. Whcic woulu you ui ihis couc.
You`u nccu a loo somcwhcic ihai was always waiiing io icau liom ihc scivci. Bui whcic
woulu ihai go. Oncc you launch ihc GUI, noihing hacns uniil an cvcni is hicu ly a GUI
comoncni.
improving the chat cIient
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 489
You know by now that we're
going with option three.
]n ]zvz ya z]]y (j
wz][ zn] e[w ga z(
([ ,z (j.
Wc wani somcihing io iun coniinuously,
chccIing loi mcssagcs liom ihc scivci,
lui w.Lou .re..u.r Le ue.` nb.I., o
.re.n w.L Le CUI So whilc ihc usci is
haily iying ncw mcssagcs oi sciolling
ihiough ihc incoming mcssagcs, wc
wani somcihing beL.rJ Le ere io Icc
icauing in ncw inui liom ihc scivci.
Thai mcans wc hnally nccu a ncw ihicau.
A ncw, scaiaic siacI
Wc wani cvciyihing wc uiu in ihc Scnu-
Only vcision vcision onc) io woiI ihc
samc way, whilc a ncw .oe iuns along
siuc ihai icaus inloimaiion liom ihc
scivci anu uislays ii in ihc incoming icxi
aica.
Wcll, noi quiic. Unlcss you havc muliilc
ioccssois on youi comuici, cach ncw
]ava ihicau is noi aciually a scaiaic
ioccss iunning on ihc OS. Bui ii almosi
eeI as ihough ii is.
Multithreading in Java
]ava has muliilc ihicauing luili iighi
inio ihc laliic ol ihc languagc. Anu ii`s a
sna io maIc a ncw ihicau ol cxccuiion:
Thread t = new Thread();
t.start();
Thai`s ii. By cicaiing a ncw Thicau obe,
you`vc launchcu a scaiaic L.enJ o
e:eu.or, wiih iis vciy own call siacI.
Except [or one probIem.
Thai ihicau uocsn`i aciually Jo anyihing,
so ihc ihicau uics" viiiually ihc insiani
ii`s loin. Whcn a ihicau uics, iis ncw
siacI uisacais again. Enu ol sioiy.
So wc`ic missing onc Icy comoncni-
ihc ihicau`s ob. In oihci woius, wc nccu
ihc couc ihai you wani io havc iun ly a
scaiaic ihicau.
Muliilc ihicauing in ]ava mcans wc
havc io looI ai loih ihc L.enJ anu ihc ob
ihai`s .ur ly ihc ihicau. Anu wc`ll also
havc io looI ai ihc Thicau In in ihc
|ava.lang acIagc. Rcmcmlci, |ava.lang
is ihc acIagc you gci imoiicu loi
licc, imliciily, anu ii`s whcic ihc classcs
mosi lunuamcnial io ihc languagc livc,
incluuing Siiing anu Sysicm.)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
490 chapter 15
1zvz hzs me| !|p|c !hrcz4s |e! en|y
enc Ihrcz4 r|zss
Wc can ialI aloui L.enJ wiih a lowci-casc i` anu
wiih a caiial T`. Whcn you scc L.enJ, wc`ic ialIing
aloui a scaiaic ihicau ol cxccuiion. In oihci woius,
a scaiaic call siacI. Whcn you scc , ihinI ol
ihc ]ava naming convcniion. Whai, in ]ava, siaiis wiih a
caiial lciici. Classcs anu inicilaccs. In ihis casc,
is a class in ihc |ava.lang acIagc. A ol|cci
icicscnis a L.enJ o e:eu.or, you`ll cicaic an insiancc ol
class cach iimc you wani io siaii u a ncw L.enJ
ol cxccuiion.
thread
run{ }
doStuff{ }
go{ }
doMore{ }
Thread

vo|d jo|r()
vo|d slarl()
slal|c vo|d s|eep()
A ihicau lowci-casc i`) is a scaiaic ihicau ol cxccuiion.
Thai mcans a scaiaic call siacI. Evciy ]ava alicaiion
siaiis u a main ihicau-ihc ihicau ihai uis ihc
main) mcihou on ihc loiiom ol ihc siacI. Thc ]VM
is icsonsillc loi siaiiing ihc main ihicau anu oihci
ihicaus, as ii chooscs, incluuing ihc gailagc collcciion
ihicau). As a iogiammci, you can wiiic couc io siaii
oihci ihicaus ol youi own.
muin{ }
,foo{ }
y,bur{ }
,buz{ }
main thread another thread
started by the code
Thicau caiial T`) is a class ihai
icicscnis a ihicau ol cxccuiion.
Ii has mcihous loi siaiiing a
ihicau, |oining onc ihicau wiih
anoihci, anu uiiing a ihicau io
slcc. Ii has moic mcihous, ihcsc
aic |usi ihc ciucial oncs wc nccu
io usc now).
]ava.lang.Thread
class
j ([z] j, z ,zz(
'([z] | yea(jn'.
]n ([ w],, z
,zz( ez]] ,(ze[.
j [[z] j, z ]zvz
e]z,, ([z( ,n(,
z ([z].
[ z[ z ([z],
z[ z [[z].
threads and Thread
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 491
Whz! 4ecs | ! mczn !e hzvc merc !hzn
enc rz|| s!zrk!
Wiih moic ihan onc call siacI, you gci ihc nen.nre ol having
muliilc ihings hacn ai ihc samc iimc. In icaliiy, only a iiuc
muliiioccssoi sysicm can aciually uo moic ihan onc ihing ai a
iimc, lui wiih ]ava ihicaus, ii can nen. ihai you`ic uoing scvcial
ihings simuliancously. In oihci woius, cxccuiion can movc lacI
anu loiih lciwccn siacIs so iaiuly ihai you lccl as ihough all siacIs
aic cxccuiing ai ihc samc iimc. Rcmcmlci, ]ava is |usi a ioccss
iunning on youi unucilying OS. So hisi, ]ava .eI has io lc ihc
cuiicnily cxccuiing ioccss` on ihc OS. Bui oncc ]ava gcis iis
iuin io cxccuic, cxacily wLn uocs ihc ]VM .ur. Which lyiccoucs
cxccuic. Whaicvci is on ihc io ol ihc cuiicnily-iunning siacI!
Anu in 100 milliscconus, ihc cuiicnily cxccuiing couc mighi swiich
io a J.e.er mcihou on a J.e.er siacI.
Onc ol ihc ihings a ihicau musi uo is Icc iiacI ol which siaicmcni
ol which mcihou) is cuiicnily cxccuiing on ihc ihicau`s siacI.
Ii mighi looI somcihing liIc ihis:
public static void main(String[] args) {
...
}

The JVM cuIIs the muin{} method,


muin{}
Runnable r = new MyThreadJob();
Thread t = new Thread(r);
t.start();
Dog d = new Dog();

muin{} sturts u new threud, The muin


threud is temporuriIy frozen whiIe the new
threud sturts running,

The JVM switches between the new


threud {user threud A} und the originuI
muin threud untiI both threuds compIete,
main thread
main thread
run{}
user thread A
muin{}
t,sturt{}
l- .:l- l--.
. --- l--. :l.-l:
.- -:---: l- .:l-
l--.
main thread
muin{}
Dog{}
user thread A
run{}
,go{}
]--'|| |-.-- -.l
l: --.-: - -:l
. -----l
l- .:l- l--. ..-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
492 chapter 15
Make a Runnable ob]ect {the thread's ]ob}
Runnable threadJob = new MyRunnable();
How to launch a new thread:
PunnobIe is on inferfoce you'II Ieorn obouf on fhe nexf poge.
You'II wrife o cIoss fhof impIemenfs fhe PunnobIe inferfoce,
ond fhof cIoss is where you'II defne fhe work fhof o fhreod
wiII perform. In ofher words, fhe mefhod fhof wiII be run
from fhe fhreod's new coII sfock.
Make a Thread ob]ect {the worker} and
give it a Runnable {the ]ob}

Thread myThread = new Thread(threadJob);


Poss fhe new PunnobIe objecf fo fhe Threod consfrucfor.
This feIIs fhe new Threod objecf which mefhod fo puf on
fhe boffom of fhe new sfock-fhe PunnobIe's run() mefhod.
8tart the Thread
myThread.start();
Mofhing hoppens unfiI you coII fhe Threod's
sforf() mefhod. Thof's when you go from
hoving jusf o Threod insfonce fo hoving o new
fhreod of execufion. When fhe new fhreod
sforfs up, if fokes fhe PunnobIe objecf's
run() mefhod ond pufs if on fhe boffom of
fhe new fhreod's sfock.
P
u
n
n
o
bIe
o
b
j
e
c
f

T
h
r
e
o
d o
b
j
e
c
f

T
h
r
e
o
d o
b
j
e
c
f

P
u
n
n
o
bIe

o
b
j
e
c
f

run()
Iaunching a thread
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 493
Ivcry Ihrcz4 ncc4s z je| !e 4e.
mc!he4 !e pe! en !hc ncw !hrcz4 s!zrk.
A Thicau ol|cci nccus a |ol. A |ol ihc ihicau will iun whcn ihc
ihicau is siaiicu. Thai |ol is aciually ihc hisi mcihou ihai gocs on
ihc ncw ihicau`s siacI, anu ii musi always lc a mcihou ihai looIs
liIc ihis:
public void run() {
// code that will be run by the new thread
}
How uocs ihc ihicau Inow which mcihou io ui ai ihc loiiom ol
ihc siacI. Bccausc Runnallc uchncs a coniiaci. Bccausc Runnallc
is an inicilacc. A ihicau`s |ol can lc uchncu in any class ihai
imlcmcnis ihc Runnallc inicilacc. Thc ihicau caics only ihai you
ass ihc Thicau consiiucioi an ol|cci ol a class ihai imlcmcnis
Runnallc.
Whcn you ass a Runnallc io a Thicau consiiucioi, you`ic ically
|usi giving ihc Thicau a way io gci io a iun) mcihou. You`ic giving
ihc Thicau iis |ol io uo.
annz] j, ( z
[[z] w[z( z j j, (
z w[. j annz]
j, ([ j z ([z] j,
,a,] ( an.
j annz] []], ([
([] ([z( g, n
([ (( | ([ nw
([z]', ,(ze[ an().
1--.
AII I need is o reoI job.
Jusf give me o PunnobIe
ond I'II gef fo workl
1
-
---.|- -l--.:- ---: --|] ---
-
-l-, -|: - ---|` |
--
--
--, l': .-
-l--.:- :- l- -
-l- : -|: --.-|-::
- -
-l-- ]-- l]- l - l.l -
.]`

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
494 chapter 15
run{}
go{}
doMore{}
Ie mzkc z je| fer yeer !hrcz4,
|mp|cmcn! !hc Kennz||c |n!crfzrc
public class MyRunnable implements Runnable {
public void run() {
go();
}
public void go() {
doMore();
}
public void doMore() {
System.out.println(top o' the stack);
}
}
---.|- : - l- ..|.- .:.-,
:- ]-- --'l --- l- ---l l
---.|- .: --|] --- --l- l-
-|----l -|: - ---|` |-l --
.-----l:` 1: : ---- ]-- -l l-
)6B l- l--. : :--:- l- --- 1:
: l- --l- l.l --: .l l- -ll--
- l- --- :l.:
class ThreadTester {
public static void main (String[] args) {
Runnable threadJob = new MyRunnable();
Thread myThread = new Thread(threadJob);
myThread .start();
System.out.println(back in main);
}
}
|.:: l- --- ---.|- -:l.-:- -l- l- ---
1--. :--:l--:l-- 1: l-||: l- l--.
-.l --l- l- -l -- l- -ll-- - l- ---
:l.: |- -l-- ---:, l- -:l --l- l.l
l- --- l--. -|| ---
/-- ---'l -l . --- l--. - --:-l-- --l| ]--
:.|| :l.-l|` -- l- 1--. -:l.-:- A l--. :
--l --.||] . l--. --l| ]-- :l.-l l B---- l.l,
l': -:l . 1--. -:l.-:-, |- .-] -l-- --:l,
-l l ---'l .- .-] --.| 'l--.--::'
main thread
muin{}
myThreud,sturt{}

new thread

8f8l 88f00ll
What do you think the output will be if you run the
ThreadTester class? (we'll fnd out in a few pages)
RunnabIe interface
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 495
The three states of a new thread
A Thicau insiancc has lccn
cicaicu lui noi siaiicu.
In oihci woius, ihcic is a
Thicau ol|cci, lui no ihicau
ol cxccuiion.
NEW RUNNABLE
Thread t = new Thread(r);
Whcn you siaii ihc ihicau, ii
movcs inio ihc iunnallc siaic.
This mcans ihc ihicau is icauy
io iun anu |usi waiiing loi iis
Big Chancc io lc sclccicu loi
cxccuiion. Ai ihis oini, ihcic is
a ncw call siacI loi ihis ihicau.
t.start();
RUNNNG
t.start();
SeIecfed fo run
This is ihc siaic all ihicaus lusi
alici! To lc Thc Choscn Onc.
Thc Cuiicnily Running Thicau.
Only ihc ]VM ihicau schcuulci
can maIc ihai uccision. You
can somciimcs inuucncc ihai
uccision, lui you cannoi loicc a
ihicau io movc liom iunnallc
io iunning. In ihc iunning
siaic, a ihicau anu ONIY ihis
ihicau) has an aciivc call siacI,
anu ihc mcihou on ihc io ol
ihc siacI is cxccuiing.
Thread t = new Thread(r);
l: : ---- . l--.
-.-l: l- -'
But there's more. Once the thread becomes
runnable, it can move back and forth between
runnable, running, and an additional state:
temporarily not runnable {also known as blocked'}.
|'- -- l- - ''
c.- |
:---:--
l.l --
]--'
|'- -.l- l-
-l :l.-l-'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
496 chapter 15
RUNNABLE RUNNNG
SeIecfed fo run
Typical runnable/running loop
Senf bock fo runnobIe
so onofher fhreod con
hove o chonce
Tyically, a ihicau movcs lacI anu
loiih lciwccn iunnallc anu iunning,
as ihc ]VM ihicau schcuulci sclccis a
ihicau io iun anu ihcn IicIs ii lacI
oui so anoihci ihicau gcis a chancc.
A thread can be made
temporarily not-runnable
Thc ihicau schcuulci can movc a
iunning ihicau inio a llocIcu siaic,
loi a vaiiciy ol icasons. Ioi cxamlc,
ihc ihicau mighi lc cxccuiing couc
io icau liom a SocIci inui siicam,
lui ihcic isn`i any uaia io icau. Thc
schcuulci will movc ihc ihicau oui
ol ihc iunning siaic uniil somcihing
lccomcs availallc. Oi ihc cxccuiing
couc mighi havc iolu ihc ihicau io
ui iiscll io slcc slcc)). Oi ihc
ihicau mighi lc waiiing lccausc ii
iiicu io call a mcihou on an ol|cci,
anu ihai ol|cci was locIcu`. In ihai
casc, ihc ihicau can`i coniinuc uniil
ihc ol|cci`s locI is liccu ly ihc ihicau
ihai has ii.
All ol ihosc conuiiions anu moic)
causc a ihicau io lccomc icmoiaiily
noi-iunnallc.
RUNNABLE RUNNNG
BLOCKED
S
e
n
f

f
o

o

f
e
m
p
o
r
o
r
y

n
o
n
-
r
u
n
n
o
b
I
e

s
f
o
f
e

u
n
f
i
I

i
f

c
o
n

b
e
c
o
m
e

r
u
n
n
o
b
I
e

o
g
o
i
n
.
:|---, -.l- -- .--l-- l--. l- -:,
-.l- -- .l. l- - ..|.|- -- l- :l--.-,
-.l- -- .- --:l': |-:
thread states
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 497
Ihc Ihrcz4 8rhc4e|cr
Mumber four, you've hod
enough fime. 8ock fo runnobIe.
Mumber fwo, Iooks Iike you're upl
Oh, now if Iooks Iike you're gonno hove
fo sIeep. Mumber fve, come foke his
pIoce. Mumber fwo, you're sfiII
sIeeping...
[[ ([z]
,e[]a] z[, z]]
([ ]ej,jn, za(
w[ an, zn] w[
],n'(. q a,az]]y
z[, ([ ([z], (z[
(an,, nje]y. @a(
([', n gazzn(
za( ([z(. q jg[(
]( n ([z] an
( j(, [z(', en(n(
w[j] ([ ([
([z], ',(zv'.
Thc ihicau schcuulci maIcs all ihc uccisions aloui
who movcs liom iunnallc io iunning, anu aloui whcn
anu unuci whai ciicumsianccs) a ihicau lcavcs ihc
iunning siaic. Thc schcuulci ucciucs who iuns, anu loi
how long, anu whcic ihc ihicaus go whcn ihc schcuulci
ucciucs io IicI ihcm oui ol ihc cuiicnily-iunning siaic.
You can`i coniiol ihc schcuulci. Thcic is no API loi
calling mcihous on ihc schcuulci. Mosi imoiianily,
ihcic aic no guaianiccs aloui schcuuling! Thcic aic a
lcw nIo-guaianiccs, lui cvcn ihosc aic a liiilc luzzy.)
Thc loiiom linc is ihis: do not bose your progrom`s
correctness on the scheduIer worhing in o porticuIor woy:
Thc schcuulci imlcmcniaiions aic uillcicni loi
uillcicni ]VM`s, anu cvcn iunning ihc samc iogiam
on ihc samc machinc can givc you uillcicni icsulis.
Onc ol ihc woisi misiaIcs ncw ]ava iogiammcis
maIc is io icsi ihcii mulii-ihicaucu iogiam on a
singlc machinc, anu assumc ihc ihicau schcuulci will
always woiI ihai way, icgaiulcss ol whcic ihc iogiam
iuns.
So whai uocs ihis mcan loi wiiic-oncc-iun-anywhcic.
Ii mcans ihai io wiiic lailoim-inuccnucni ]ava couc,
youi mulii-ihicaucu iogiam musi woiI no maiici Low
ihc ihicau schcuulci lchavcs. Thai mcans ihai you can`i
lc uccnucni on, loi cxamlc, ihc schcuulci maIing
suic all ihc ihicaus iaIc nicc, cilccily laii anu cqual
iuins ai ihc iunning siaic. Alihough highly unliIcly
iouay, youi iogiam mighi cnu u iunning on a ]VM
wiih a schcuulci ihai says, OK ihicau hvc, you`ic u,
anu as lai as I`m conccincu, you can siay hcic uniil
you`ic uonc, whcn youi iun) mcihou comlcics."
Thc sccici io almosi cvciyihing is Iee. Thai`s
iighi, Iee. Puiiing a ihicau io slcc, cvcn loi a lcw
milliscconus, loiccs ihc cuiicnily-iunning ihicau io
lcavc ihc iunning siaic, ihus giving anoihci ihicau a
chancc io iun. Thc ihicau`s slcc) mcihou uocs comc
wiih ore guaianicc: a slccing ihicau will ro lccomc
ihc cuiicnily-iunning ihicau lcloic ihc ihc lcngih ol
iis slcc iimc has cxiicu. Ioi cxamlc, il you icll youi
ihicau io slcc loi iwo scconus 2,000 milliscconus),
ihai ihicau can ncvci lccomc ihc iunning ihicau again
uniil somciimc ne. ihc iwo scconus havc asscu.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
498 chapter 15
public class MyRunnable implements Runnable {
public void run() {
go();
}
public void go() {
doMore();
}
public void doMore() {
System.out.println(top o' the stack);
}
}
class ThreadTestDrive {
public static void main (String[] args) {
Runnable threadJob = new MyRunnable();
Thread myThread = new Thread(threadJob);
myThread.start();
System.out.println(back in main);
}
}
An example of how unpredictable the
scheduler can be...
Running this code on one machine: Produced this output:
File Edit Window Help PickMe
% java ThreadTestDrive
back in main
top o' the stack
% java ThreadTestDrive
top o' the stack
back in main
% java ThreadTestDrive
top o' the stack
back in main
% java ThreadTestDrive
top o' the stack
back in main
% java ThreadTestDrive
top o' the stack
back in main
% java ThreadTestDrive
top o' the stack
back in main
% java ThreadTestDrive
back in main
top o' the stack
N-l:- -- l- ---- :.--:
-.---|] ---l--: l- --- l--.
-:-: -:l, .- :---l--: l- -.-
l--. -:-: -:l
thread scheduIing
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 499
run{}
go{}
doMore{}
main thread
muin{}
myThreud,sturt{}
new thread
muin{}
myThreud,sturt{}
main thread
muin{}
ra|r() slarls l|e
reW l|read
T|e sc|edu|er serds
l|e ra|r l|read oul
ol rurr|r ard oac|
lo rurrao|e, so l|al
l|e reW l|read car
rur.
T|e sc|edu|er |els
l|e reW l|read
rur lo corp|el|or,
pr|rl|r oul 'lop o'
l|e slac|
T|e reW l|read oes
aWay, oecause |ls rur()
corp|eled. T|e ra|r
l|read orce aa|r
oecores l|e rurr|r
l|read, ard pr|rls 'oac|
|r ra|r
main thread

main thread
muin{}
myThreud,sturt{}
new thread
muin{}
myThreud,sturt{}
main thread
muin{}
ra|r() slarls l|e
reW l|read
T|e sc|edu|er serds
l|e ra|r l|read oul
ol rurr|r ard oac|
lo rurrao|e, so l|al
l|e reW l|read car
rur.
T|e sc|edu|er |els l|e
reW l|read rur lor a
||ll|e W|||e, rol |or
erou| lor l|e rur()
rel|od lo corp|ele.
main thread

run{}
go{}
run{}
go{}
new thread
T|e sc|edu|er
serds l|e reW
l|read oac| lo
rurrao|e.
T|e sc|edu|er
se|ecls l|e ra|r
l|read lo oe l|e
rurr|r l|read
aa|r. Va|r pr|rls
oul 'oac| |r ra|r
run{}
go{}
doMore{}
new thread
T|e reW l|read relurrs
lo l|e rurr|r slale
ard pr|rls oul 'lop o'
l|e slac|.
How did we end up with different results?
8ometimes it runs like this:
And sometimes it runs like this:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
socket connections
500 chapter 15
8ll P0lk5
A l|read W|l| a |oWer-case 'l' |s a separale l|read ol
execul|or |r Java.
Every l|read |r Java |as |ls oWr ca|| slac|.
A T|read W|l| a cap|la| 'T' |s l|e java.|ar.T|read
c|ass. A T|read oojecl represerls a l|read ol
execul|or.
A T|read reeds a joo lo do. A T|read's joo |s ar
|rslarce ol sorel||r l|al |rp|ererls l|e Rurrao|e
|rlerlace.
T|e Rurrao|e |rlerlace |as jusl a s|r|e rel|od, rur().
T||s |s l|e rel|od l|al oes or l|e oollor ol l|e reW
ca|| slac|. lr ol|er Words, |l |s l|e l|rsl rel|od lo rur |r
l|e reW l|read.
To |aurc| a reW l|read, you reed a Rurrao|e lo pass
lo l|e T|read's corslruclor.
A l|read |s |r l|e NEw slale W|er you |ave
|rslarl|aled a T|read oojecl oul |ave rol yel ca||ed
slarl().
w|er you slarl a l|read (oy ca|||r l|e T|read oojecl's
slarl() rel|od), a reW slac| |s crealed, W|l| l|e
Rurrao|e's rur() rel|od or l|e oollor ol l|e slac|.
T|e l|read |s roW |r l|e RuNNA8LE slale, Wa|l|r lo
oe c|oser lo rur.
A l|read |s sa|d lo oe RuNNlN0 W|er l|e JvV's
l|read sc|edu|er |as se|ecled |l lo oe l|e currerl|y-
rurr|r l|read. 0r a s|r|e-processor rac||re, l|ere
car oe or|y ore currerl|y-rurr|r l|read.
3orel|res a l|read car oe roved lror l|e RuNNlN0
slale lo a 8L0CKE0 (lerporar||y ror-rurrao|e) slale.
A l|read r||l oe o|oc|ed oecause |l's Wa|l|r lor dala
lror a slrear, or oecause |l |as ore lo s|eep, or
oecause |l |s Wa|l|r lor ar oojecl's |oc|.
T|read sc|edu||r |s rol uararleed lo Wor| |r ary
parl|cu|ar Way, so you carrol oe cerla|r l|al l|reads
W||| la|e lurrs r|ce|y. You car |e|p |rl|uerce lurr-la||r
oy pull|r your l|reads lo s|eep per|od|ca||y.
(-,- a,- |
oa|| qa--(:|-

I've seen exampIes that don't use a separate
RunnabIe impIementation, but instead just make a
subcIass of 7hread and override the 7hread's run()
method. 7hat way, you caII the 7hread's no-arg
constructor when you make the new thread,
7hread t = new 7hread(), // no RunnabIe

es, that |s another way of making your own
thread, but think about it from an OO perspective.
what's the purpose of subclassingI Pemember that
we're talking about two different things herethe
7hteoJ and the thread's joo. Prom an OO view, those
two are very separate activities, and belong in separate
classes. The only time you want to subclass/extend
the Thread class, is if you are making a new and more
specific type of Thread. |n other words, if you think of
the Thread as the worker, don't extend the Thread class
unless you need more specific wotlet behaviors. 8ut if
all you need is a new joo to be run by a Thread/worker,
then implement Punnable in a separate, joo-specific
(not wotlet-specific) class.
This is a design issue and not a performance or
language issue. |t's perfectly legal to subclass Thread
and override the run() method, but it's rarely a good
idea.

Can you reuse a 7hread object! Can you give it
a new job to do and then restart it by caIIing start()
again!

No. Once a thread's run() method has completed,
the thread can never be restarted. |n fact, at that
point the thread moves into a state we haven't talked
about. |n the dead state, the thread has
finished its run() method and can never be restarted.
The Thread ob|ect might still be on the heap, as a
living ob|ect that you can call other methods on (if
appropriate), but the Thread ob|ect has permanently
lost its 'threadness'. |n other words, there is no longer a
separate call stack, and the Thread ob|ect is no longer
a thteoJ. |t's |ust an ob|ect, at that point, like all other
ob|ects.
8ut, there are design patterns for making a pool of
threads that you can keep using to perform different
|obs. 8ut you don't do it by restarting() a dead thread.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 501
|e!!|n] z !hrcz4 !e s|ccp
Onc ol ihc lcsi ways io hcl youi ihicaus iaIc iuins is
io ui ihcm io slcc ciiouically. All you nccu io uo
is call ihc siaiic slcc) mcihou, assing ii ihc slcc
uuiaiion, in milliscconus.
Ioi cxamlc:
Thread.sleep(2000);
will InocI a ihicau oui ol ihc iunning siaic, anu
Icc ii oui ol ihc iunnallc siaic loi iwo scconus.
Thc ihicau nr` lccomc ihc iunning ihicau
again uniil alici ai lcasi iwo scconus havc asscu.
A lii unloiiunaicly, ihc slcc mcihou ihiows an
IniciiuicuExcciion, a chccIcu cxcciion, so all
calls io slcc musi lc wiacu in a iiy/caich oi
ucclaicu). So a slcc call ically looIs liIc ihis:
try {
Thread.sleep(2000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
Youi ihicau will iolally re.e. lc iniciiuicu liom
slcc, ihc cxcciion is in ihc API io suoii a ihicau
communicaiion mcchanism ihai almosi nolouy uscs in
ihc Rcal Woilu. Bui, you siill havc io olcy ihc hanulc
oi ucclaic law, so you nccu io gci uscu io wiaing youi
slcc) calls in a iiy/caich.
Now you Inow ihai youi ihicau won`i waIc u beo.e ihc
sccihcu uuiaiion, lui is ii ossillc ihai ii will waIc u
somc iimc ne. ihc iimci` has cxiicu. Ycs anu no. Ii
uocsn`i maiici, ically, lccausc whcn ihc ihicau waIcs
u, it oIwoys goes boch to the runnobIe stote: Thc ihicau
won`i auiomaiically waIc u ai ihc ucsignaicu iimc anu
lccomc ihc cuiicnily-iunning ihicau. Whcn a ihicau
waIcs u, ihc ihicau is oncc again ai ihc mcicy ol
ihc ihicau schcuulci. Now, loi alicaiions ihai uon`i
icquiic cilcci iiming, anu ihai havc only a lcw ihicaus,
ii mighi acai as ihough ihc ihicau waIcs u anu
icsumcs iunning iighi on schcuulc say, alici ihc 2000
milliscconus). Bui uon`i lci youi iogiam on ii.
]a( ya ([z] ( ,]
j| ya wzn( ( ,a
([z( ([ ([z], g( z
e[zne ( an.
y[n ([ ([z] wz[,
a, j( z]wzy, g, ze[
( ([ annz] ,(z(
zn] wzj(, | ([ ([z]
,e[]a] ( e[, j(
( an zgzjn.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
502 chapter 15
0s|n] s|ccp !e mzkc eer pre]rzm
merc prc4|r!z||c.
Rcmcmlci oui cailici cxamlc ihai Ici giving us uillcicni
icsulis cach iimc wc ian ii. IooI lacI anu siuuy ihc couc
anu ihc samlc ouiui. Somciimcs main hau io waii uniil ihc
ncw ihicau hnishcu anu iinicu io o` ihc siacI"), whilc
oihci iimcs ihc ncw ihicau woulu lc scni lacI io iunnallc
lcloic ii was hnishcu, allowing ihc main ihicau io comc lacI
in anu iini oui lacI in main". How can wc hx ihai. Sio
loi a momcni anu answci ihis qucsiion: Whcic can you ui
a slcc) call, io maIc suic ihai lacI in main" always iinis
lcloic io o` ihc siacI".
Wc`ll waii whilc you woiI oui an answci ihcic`s moic ihan
onc answci ihai woulu woiI).
Iiguic ii oui.
public class MyRunnable implements Runnable {
public void run() {
go();
}
public void go() {
try {
Thread.sleep(2000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}

doMore();
}
public void doMore() {
System.out.println(top o' the stack);
}
}
class ThreadTestDrive {
public static void main (String[] args) {
Runnable theJob = new MyRunnable();
Thread t = new Thread(theJob);
t.start();
System.out.println(back in main);
}
}
c.||- :|-- --- -|| --:- l- ---
l--. l- |-.- l- :-----l|]~-----
:l.l-'
1- -.- l--. -|| -:--- l-
:-----l|]~----- l--. ..-, .- --l
--l .: - -.-' 1-- l--- -|| - .
.-:- |-- .--l l-- :-:--:` ---- --
-l l- l: |--, -: :.||: -M---|` .-
--l: --l l- -' l- :l.:'
File Edit Window Help SnoozeButton
% java ThreadTestDrive
back in main
top o' the stack
% java ThreadTestDrive
back in main
top o' the stack
% java ThreadTestDrive
back in main
top o' the stack
% java ThreadTestDrive
back in main
top o' the stack
% java ThreadTestDrive
back in main
top o' the stack
1: : -.l -- -.-l-. :--::l--l ----
- --l :l.l----l:
using Thread.sIeep()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 503
Mzk|n] zn4 s!zr!|n] ! we !hrcz4s
Thicaus havc namcs. You can givc youi ihicaus a namc ol
youi choosing, oi you can accci ihcii uclauli namcs. Bui ihc
cool ihing aloui namcs is ihai you can usc ihcm io icll which
ihicau is iunning. Thc lollowing cxamlc siaiis iwo ihicaus.
Each ihicau has ihc samc |ol: iun in a loo, iiniing ihc
cuiicnily-iunning ihicau`s namc wiih cach iiciaiion.
public class RunThreads implements Runnable {
public static void main(String[] args) {
RunThreads runner = new RunThreads();
Thread alpha = new Thread(runner);
Thread beta = new Thread(runner);
alpha.setName(Alpha thread);
beta.setName(Beta thread);
alpha.start();
beta.start();
}
public void run() {
for (int i = 0; i < 25; i++) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + is running);
}
}
}
M
.- --- ---.|- -:l.-:-
M.- l-- l--.:, -l l- :.-- ---.|- |l-
:.-- -~~--'|| l.| ---- .--l l- l-- l--.:
.- --- ---.|-' - . -- .-:`
N.-- l- l--.:
l.-l l- l--.:
!.: l--. -|| --- l--- l: |--,
--l- l: -.-- -.: l--
Whz! w||| hzppcn!
Will ihc ihicaus iaIc iuins. Will you scc ihc ihicau namcs
alicinaiing. How olicn will ihcy swiich. Wiih cach iiciaiion.
Alici hvc iiciaiions.
You alicauy Inow ihc answci: we Jor` Irow Ii`s u io ihc
schcuulci. Anu on youi OS, wiih youi aiiiculai ]VM, on
youi CPU, you mighi gci vciy uillcicni icsulis.
Running unuci OS X 10.2 ]aguai), wiih hvc oi lcwci
iiciaiions, ihc Alha ihicau iuns io comlciion, ihcn
ihc Bcia ihicau iuns io comlciion. Vciy consisicni. Noi
guaianiccu, lui vciy consisicni.
Bui whcn you u ihc loo io 2 oi moic iiciaiions, ihings
siaii io wolllc. Thc Alha ihicau mighi noi gci io comlcic
all 2 iiciaiions lcloic ihc schcuulci scnus ii lacI io
iunnallc io lci ihc Bcia ihicau havc a chancc.
File Edit Window Help Centauri
Alpha thread is running
Alpha thread is running
Alpha thread is running
Beta thread is running
Alpha thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Alpha thread is running
|.-l - l- --l-l ---
l- |-- l--.l-: i-
l--:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
504 chapter 15
0m, ycs. Ihcrc |8 z 4zrk s|4c.
Ihrcz4s rzn |cz4 !e renrerrcnry '|ssecs.
Concuiicncy issucs lcau io iacc conuiiions. Racc conuiiions
lcau io uaia coiiuiion. Daia coiiuiion lcaus io lcai... you
Inow ihc icsi.
Ii all comcs uown io onc oicniially ucauly sccnaiio: iwo oi
moic ihicaus havc acccss io a singlc ol|cci`s . In oihci
woius, mcihous cxccuiing on iwo uillcicni siacIs aic loih
calling, say, gciicis oi sciicis on a singlc ol|cci on ihc hca.
Ii`s a wholc lcli-hanu-uocsn`i-Inow-whai-ihc-iighi-hanu-
is-uoing` ihing. Two ihicaus, wiihoui a caic in ihc woilu,
humming along cxccuiing ihcii mcihous, cach ihicau
ihinIing ihai hc is ihc Onc Tiuc Thicau. Thc only onc
ihai maiicis. Alici all, whcn a ihicau is noi iunning, anu in
iunnallc oi llocIcu) ii`s csscniially InocIcu unconscious.
Whcn ii lccomcs ihc cuiicnily-iunning ihicau again, ii uocsn`i
Inow ihai ii cvci siocu.
Wowl Threods ore
fhe greofesf fhing since fhe
MIMI Cooperl I con'f fhink
of o singIe downside fo using
fhreods, con you7
aren't threads wonderfuI?
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 505
Marriage in TroubIe.
Can this coupIe be saved?
Next, on a very special Dr.Steve Show
[Transcript from episode #42]
WeIcome Lo LLe Dr. BLeve sLow.
We've oL a sLory Loday LLaL's cenLered around LLe Lop Lwo reasons wLy
coupIes spIIL up-Bnances and sIeep.
Today's LroubIed paIr, Fyan and MonIca, sLare a bed and a
bank accounL. EuL noL Ior Ion II we can'L Bnd a soIuLIon. TLe
probIem? TLe cIassIc "Lwo peopIe-one bank accounL" LLIn.
Here's Low MonIca descrIbed IL Lo me:
"Fyan and I areed LLaL neILLer oI us wIII overdraw LLe cLeckIn accounL.
Bo LLe procedure Is, wLoever wanLs Lo wILLdraw money musL cLeck LLe
baIance In LLe accounL beIore makIn LLe wILLdrawaI. IL aII seemed so
sImpIe. EuL suddenIy we're bouncIn cLecks and eLLIn LIL wILL overdraIL
Iees!
I LLouLL IL wasn'L possIbIe, I LLouLL our procedure was saIe. EuL LLen
LLIs Lappened:
Fyan needed $S0, so Le cLecked LLe baIance In LLe accounL,
and saw LLaL IL was $100. No probIem. Bo, Le pIans Lo
wILLdraw LLe money. But Brst he taIIs asIeep!
And LLaL's wLere I come In, wLIIe Fyan's sLIII asIeep, and
now I wanL Lo wILLdraw $100. I cLeck LLe baIance, and
IL's $100 (because Fyan's sLIII asIeep and Lasn'L yeL made
LIs wILLdrawaI}, so I LLInk, no probIem. Bo I make LLe
wILLdrawaI, and aaIn no probIem. EuL LLen Fyan wakes up,
compIeLes LIs wILLdrawaI, and we're suddenIy overdrawn! He dIdn'L
even know LLaL Le IeII asIeep, so Le jusL wenL aLead and compIeLed LIs
LransacLIon wILLouL cLeckIn LLe baIance aaIn. You've oL Lo LeIp us Dr.
BLeve!"
Is LLere a soIuLIon? Are LLey doomed? We can'L sLop Fyan Irom IaIIIn
asIeep, buL can we make sure LLaL MonIca can'L eL Ler Lands on LLe bank
accounL unLII aILer Le wakes up?
Take a momenL and LLInk abouL LLaL wLIIe we o Lo a commercIaI break.
].- .||: .:|-- .l--
- :-:: l- .|.-:-
-l ---- - -.-: l-
-l-.-.| w-- - -.-:
-, - ---.l-|] -.-:
l- -l-.-| -l--l
:-:- l- .|.-:- ..-
].- .- M--:. :l-:
- l- l-- --|-, ---
.::---l' --|--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
506 chapter 15
Ihc Kyzn zn4 Men|rz pre||cm, |n re4c
Thc lollowing cxamlc shows whai can hacn whcn wo
ihicaus Ryan anu Monica) shaic a .rIe ol|cci ihc lanI
accouni).
Thc couc has iwo classcs, BanIAccouni, anu
MonicaAnuRyan]ol. Thc MonicaAnuRyan]ol class
imlcmcnis Runnallc, anu icicscnis ihc lchavioi ihai Ryan
anu Monica loih havc-chccIing ihc lalancc anu maIing
wiihuiawals. Bui ol couisc, cach ihicau lalls aslcc .r beweer
chccIing ihc lalancc anu aciually maIing ihc wiihuiawal.
Thc MonicaAnuRyan]ol class has an insiancc vaiiallc ol iyc
BanIAccouni., ihai icicscnis ihcii shaicu accouni.
Thc couc woiIs liIc ihis:
1 Muke one instunce of PyunAndMonicuJob,
The PyonAndMonicoJob cIoss is fhe PunnobIe (fhe job fo do),
ond since bofh Monico ond Pyon do fhe some fhing (check
boIonce ond wifhdrow money), we need onIy one insfonce.
ankAccount
|rl oa|arce
el8a|arce()
W|l|draW()
RyanAndHon|caJob
8ar|Accourl accourl
rur()
ra|ew|l|draWa|()

2 Muke two threuds with the sume PunnubIe


(fhe PyonAndMonicoJob insfonce)
RyanAndMonicaJob theJob = new RyanAndMonicaJob();
Thread one = new Thread(theJob);
Thread two = new Thread(theJob);
3 Nume und sturt the threuds
one.setName(Ryan);
two.setName(Monica);
one.start();
two.start();
4 Wutch both threuds eecute the run{} method
(check fhe boIonce ond moke o wifhdrowoI)
One fhreod represenfs Pyon, fhe ofher represenfs Monico.
8ofh fhreods confinuoIIy check fhe boIonce ond fhen moke o
wifhdrowoI, buf onIy if if's sofel
n the run{} method, do
exactly what Ryan and
Monica would do-check
the balance and, if
there's enough money,
make the withdrawal.
This should protect
against overdrawing the
account.
Except... Ryan and
Monica always fall
asleep after they
check the balance but
before they hnish the
withdrawal.
if (account.getBalance() >= amount) {
try {
Thread.sleep(500);
} catch(InterruptedException ex) {ex.printStackTrace(); }
}
Ryan and Monica code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 507
class BankAccount {
private int balance = 100;

public int getBalance() {
return balance;
}
public void withdraw(int amount) {
balance = balance - amount;
}
}
public class RyanAndMonicaJob implements Runnable {
private BankAccount account = new BankAccount();
public static void main (String [] args) {
RyanAndMonicaJob theJob = new RyanAndMonicaJob();
Thread one = new Thread(theJob);
Thread two = new Thread(theJob);
one.setName(Ryan);
two.setName(Monica);
one.start();
two.start();
}
public void run() {
for (int x = 0; x < 10; x++) {
makeWithdrawl(10);
if (account.getBalance() < 0) {
System.out.println(Overdrawn!);
}
}
}
private void makeWithdrawal(int amount) {
if (account.getBalance() >= amount) {
System.out.println(Thread.currentThread().getName() + is about to withdraw);
try {
System.out.println(Thread.currentThread().getName() + is going to sleep);
Thread.sleep(500);
} catch(InterruptedException ex) {ex.printStackTrace(); }
System.out.println(Thread.currentThread().getName() + woke up.);
account.withdraw(amount);
System.out.println(Thread.currentThread().getName() + completes the withdrawl);
}
else {
System.out.println(Sorry, not enough for + Thread.currentThread().getName());
}
}
}
Ihc Kyzn zn4 Men|rz crzmp|c
1- .::---l :l.-l: -l .
.|.-:- - i|oo
1--- -|| - --|] 6N! -:l.-:- - l-
].-A-M--:.)-1.l --.-: --|]
6N! -:l.-:- - l- .- .::---l B-l
l--.: -|| .::-:: l: --- .::---l
|-:l.-l.l- l- ---.|- |-`
M.- l-- l--.:, - -.: l--. l- :.-- ---.|-
- 1.l --.-: -l l--.: -|| - .::-::- l- ---
.::---l -:l.-:- .-.|- - l- ---.|- :|.::
|- l- ---| ` --l-, . l--. |--: l--- .- l--:
l- -.- . -l-.-.| -l -.: l--.l-- Al-- l-
-l-.-.|, l :-:: l- .|.-:- --:- ..- l- :--
l- .::---l : ----.--
c-: l- .::---l .|.-:-, .- l---': --l
---- ----], -- -:l --l . --::.- | l--- |
----, -- - l- :|--, l-- -.- - .- :--|-l-
l- -l-.-.|, -:l |- ].-
w- -l - . --: - --l :l.l----l: :- -- :.- :-- -.l': .--- .: l ---:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
508 chapter 15
File Edit Window Help Visa
Ryan is about to withdraw
Ryan is going to sleep
Monica woke up.
Monica completes the withdrawl
Monica is about to withdraw
Monica is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is about to withdraw
Ryan is going to sleep
Monica woke up.
Monica completes the withdrawl
Monica is about to withdraw
Monica is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is about to withdraw
Ryan is going to sleep
Monica woke up.
Monica completes the withdrawl
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Ryan woke up.
Ryan completes the withdrawl
Overdrawn!
Sorry, not enough for Ryan
Overdrawn!
Sorry, not enough for Ryan
Overdrawn!
Sorry, not enough for Ryan
Overdrawn!
The makeWithdrawal{} method
always checks the balance
before making a withdrawal,
but still we overdraw the
account.
Here's one scenario:
Ryan checks the balance, sees that
there's enough money, and then falls
asleep.
Meanwhile, Monica comes in and checks
the balance. She, too, sees that there's
enough money. She has no idea that
Ryan is going to wake up and complete a
withdrawal.
Monica falls asleep.
Ryan wakes up and completes his
withdrawal.
Monica wakes up and completes her
withdrawal. Big Problem! n between the
time when she checked the balance and
made the withdrawal, Ryan woke up and
pulled money from the account.
Monica's check of the account was
not vaIid, because Ryan had aIready
checked and was stiII in the middIe of
making a withdrawaI.
Monica must be stopped from getting
into the account until Ryan wakes up and
fnishes his transaction. And vice-versa.
+-- l:
.--
Ryan and Monica output
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 509
The lock works like this:
They need a lock for account accessl
1 There's o Iock ossociofed wifh fhe bonk
occounf fronsocfion (checking fhe boIonce
ond wifhdrowing money). There's onIy
one key, ond if sfoys wifh fhe Iock unfiI
somebody wonfs fo occess fhe occounf.
2 When Pyon wonfs fo occess fhe bonk
occounf (fo check fhe boIonce ond wifhdrow
money), he Iocks fhe Iock ond pufs fhe key
in his pockef. Mow nobody eIse con occess
fhe occounf, since fhe key is gone.
3 Pyun keeps the key in his pocket untiI he
hnishes the trunsuction, He hos fhe onIy
key, so Monico con'f occess fhe occounf
(or fhe checkbook) unfiI Pyon unIocks fhe
occounf ond refurns fhe key.
Mow, even if Pyon foIIs osIeep offer he
checks fhe boIonce, he hos o guoronfee
fhof fhe boIonce wiII be fhe some when he
wokes up, becouse he kepf fhe key whiIe he
wos osIeepl
The bank account
transaction is
unlocked when
nobody is using
the account.
When Ryan
wants to access
the account, he
secures the lock
and takes the key.
When Ryan is
hnished, he
unlocks the lock
and returns the
key. Now the key
is available for
Monica {or Ryan
again} to access
the account.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
510 chapter 15
Wc ncc4 !hc mzkcW| !h4rzwz| | I mc!he4
!e ren zs enc z!em|r !h|n].
private synchronized void makeWithdrawal(int amount) {
if (account.getBalance() >= amount) {
System.out.println(Thread.currentThread().getName() + is about to withdraw);
try {
System.out.println(Thread.currentThread().getName() + is going to sleep);
Thread.sleep(500);
} catch(InterruptedException ex) {ex.printStackTrace(); }
System.out.println(Thread.currentThread().getName() + woke up.);
account.withdraw(amount);
System.out.println(Thread.currentThread().getName() + completes the withdrawl);
} else {
System.out.println(Sorry, not enough for + Thread.currentThread().getName());
}
}
The synchronized
keyword means that
a thread needs a key
in order to access the
synchronized code.
To protect your data
{like the bank account},
synchronize the
methods that act on
that data.
Wc nccu io maIc suic ihai oncc a ihicau cnicis ihc
maIcWiihuiawal) mcihou, . u be nIIoweJ o r.L Le eLoJ
lcloic any oihci ihicau can cnici.
In oihci woius, wc nccu io maIc suic ihai oncc a ihicau has
chccIcu ihc accouni lalancc, ihai ihicau has a guaianicc ihai ii can
waIc u anu hnish ihc wiihuiawal beo.e nr, oLe. L.enJ nr LeI Le
nour bnInre
Usc ihc synchronized Icywoiu io mouily a mcihou so ihai only
onc ihicau ai a iimc can acccss ii.
Thai`s how you ioicci ihc lanI accouni! You uon`i ui a locI on
ihc lanI accouni iiscll, you locI ihc mcihou ihai uocs ihc lanIing
iiansaciion. Thai way, onc ihicau gcis io comlcic ihc wholc
iiansaciion, siaii io hnish, cvcn il ihai ihicau lalls aslcc in ihc
miuulc ol ihc mcihou!
So il you uon`i locI ihc lacI accouni, ihcn whai cxacily . locIcu. Is
ii ihc mcihou. Thc Runnallc ol|cci. Thc ihicau iiscll.
Wc`ll looI ai ihai on ihc ncxi agc. In couc, ihough, ii`s quiic
simlc-|usi auu ihc synchionizcu mouihci io youi mcihou
ucclaiaiion:
|N-l- -- ]-- ]:::~:.] --.--: ]-:, l- :----l-- - -:- l- --- '.l--:' --- --: --l --|-:l
l- --|- :-.l--: .-:l:|- l- 1- N--l--, --l !-:l--, --- ]-- -.- l- --- '.l--:' - l-
:--l-l - l--.: -- l-.-:.:l--: +-], l': --l 6c :----l-- | w! ---- - :.--, --' .|]
+-:----': c-:--l.-l] |--:|- l- --ll] --: ---]l- --|.l- l- l--.:`
using synchronized
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 511
0s|n] zn e|jcr!s |erk
Evciy ol|cci has a locI. Mosi ol ihc iimc, ihc
locI is unlocIcu, anu you can imaginc a viiiual
Icy siiiing wiih ii. Ol|cci locIs comc inio lay
only whcn ihcic aic synchionizcu mcihous.
Whcn an ol|cci has onc oi moic synchionizcu
mcihous, o threod con enter o synchronized
method onIy i[ the threod con get the hey to the
object`s Ioch:
Thc locIs aic noi ci eLoJ, ihcy
aic ci obe. Il an ol|cci has iwo
synchionizcu mcihous, ii uocs noi
simly mcan ihai you can`i havc iwo
ihicaus cniciing ihc samc mcihou. Ii
mcans you can`i havc iwo ihicaus cniciing
nr, ol ihc synchionizcu mcihous.
ThinI aloui ii. Il you havc muliilc
mcihous ihai can oicniially aci on an
ol|cci`s insiancc vaiiallcs, all ihosc mcihous
nccu io lc ioiccicu wiih synchionizcu.
Thc goal ol synchionizaiion is io ioicci
ciiiical uaia. Bui icmcmlci, you uon`i locI ihc
uaia iiscll, you synchionizc ihc mcihous ihai
ne ihai uaia.
So whai hacns whcn a ihicau is cianIing
ihiough iis call siacI siaiiing wiih ihc iun)
mcihou) anu ii suuucnly hiis a synchionizcu
mcihou. Thc ihicau iccognizcs ihai ii nccus
a Icy loi ihai ol|cci lcloic ii can cnici ihc
mcihou. Ii looIs loi ihc Icy ihis is all hanulcu
ly ihc ]VM, ihcic`s no API in ]ava loi acccssing
ol|cci locIs), anu il ihc Icy is availallc, ihc
ihicau gials ihc Icy anu cnicis ihc mcihou.
Iiom ihai oini loiwaiu, ihc ihicau hangs on
io ihai Icy liIc ihc ihicau`s lilc uccnus on
ii. Thc ihicau won`i givc u ihc Icy uniil ii
comlcics ihc synchionizcu mcihou. So whilc
ihai ihicau is holuing ihc Icy, no oihci ihicaus
can cnici nr, ol ihai ol|cci`s synchionizcu
mcihous, lccausc ihc onc Icy loi ihai ol|cci
won`i lc availallc.
[vy ]zvz je( [z, z ]e[.
j ]e[ [z, n]y n [y.
p,( | ([ (j, ([ ]e[ j,
an]e[] zn] n]y ez,.
@a( j| zn je( [z,
,yne[njz] ([],, z
([z] ezn n( n | ([
,yne[njz] ([], 0j(
j| ([ [y | ([ je(', ]e[
j, zvzj]z]. ]n ([ w],,
n]y j| zn([ ([z] [z,n'(
z]z]y gz] ([ n [y.
Hey, fhis objecf's
fokeMoney() mefhod is
synchroni;ed. I need fo gef
fhis objecf's key before I
con go in...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
512 chapter 15
Ihc 4rcz4c4 Ies! 0p4z!c pre||cm
Hcic`s anoihci classic concuiicncy iollcm, ihai comcs liom ihc uaialasc woilu. Ii`s
closcly iclaicu io ihc Ryan anu Monica sioiy, lui wc`ll usc ihis cxamlc io illusiiaic a lcw
moic oinis.
Thc losi uuaic icvolvcs aiounu onc ioccss:
Sic 1: Gci ihc lalancc in ihc accouni
int i = balance;
Sic 2: Auu 1 io ihai lalancc
balance = i + 1;
Thc iiicI io showing ihis is io loicc ihc comuici io iaIc iwo sics io comlcic ihc changc
io ihc lalancc. In ihc ical woilu, you`u uo ihis aiiiculai movc in a singlc siaicmcni:
balance++;
Bui ly loicing ii inio sics, ihc iollcm wiih a non-aiomic ioccss will lccomc clcai.
So imaginc ihai iaihci ihan ihc iiivial gci ihc lalancc anu ihcn auu 1 io ihc cuiicni
lalancc" sics, ihc iwo oi moic) sics in ihis mcihou aic much moic comlcx, anu
coulun`i lc uonc in onc siaicmcni.
In ihc Iosi Uuaic" iollcm, wc havc iwo ihicaus, loih iiying io incicmcni ihc lalancc.
class TestSync implements Runnable {
private int balance;
public void run() {
for(int i = 0; i < 50; i++) {
increment();
System.out.println(balance is + balance);
}
}
public void increment() {
int i = balance;
balance = i + 1;
}
}
public class TestSyncTest {
public static void main (String[] args) {
TestSync job = new TestSync();
Thread a = new Thread(job);
Thread b = new Thread(job);
a.start();
b.start();
}
}
-.: l--. ---: -o
l-
-:,
-:---
--l- l- .|.-:- --
-.: l--.l--
+---': l- :--:.| .-l' w- -:-----l l- .|.-:- ]
.- | l- -.l--- l- .|-- - .|.-:- -.: A1 1+!
1|M! w! !Al |1 |-.l-- l.- .- | l- -.l---
l- cc!N1.|-- :`
synchronization matters
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 513
Ic!s ren !h|s re4c...
A
B
1 Threod A runs for owhiIe
Put the value of balance into variable i.
Balance is 0, so i is now 0.
Set the value of balance to the result of i + 1.
Now balance is 1.
Put the value of balance into variable i.
Balance is 1, so i is now 1.
Set the value of balance to the result of i + 1.
Now balance is 2.
B
2 Threod 8 runs for owhiIe
Put the value of balance into variable i.
Balance is 2, so i is now 2.
Set the value of balance to the result of i + 1.
Now balance is 3.
Put the value of balance into variable i.
Balance is 3, so i is now 3.
[now thread B is sent back to runnable,
it sets the value of balance to 4]
A
3 Threod A runs ogoin, picking up where if Ieff off
Put the value of balance into variable i.
Balance is 3, so i is now 3.
Set the value of balance to the result of i + 1.
Now balance is 4.
Put the value of balance into variable i.
Balance is 4, so i is now 4.
Set the value of balance to the result of i + 1.
Now balance is 5.
B
4 Threod 8 runs ogoin, ond picks up exocfIy where if Ieff offl
Set the value of balance to the result of i + 1.
Now baIance is 4.
/

-:''
We lost the last updates
that Thread A madel
Thread B had previously
done a read' of the value
of balance, and when B
woke up, it ]ust kept going
as if it never missed a beat.
1--. A -.l- l l- -, -l
--- B :.-- .: .- :l--
-- l- - l- -.l- A -.-,
.: A': -.l- ---- .---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
514 chapter 15
Mzkc !hc |nrrcmcn!|I mc!he4 z!em|r.
8ynrhren|zc | !|
Synchionizing ihc incicmcni) mcihou solvcs ihc Iosi
Uuaic" iollcm, lccausc ii Iccs ihc iwo sics in ihc mcihou
as onc unlicaIallc unii.
public synchronized void increment() {
int i = balance;
balance = i + 1;
}
Once a thread enters
the method, we have
to make sure that all
the steps in the method
complete {as one
atomic process} before
any other thread can
enter the method.
B
(-,- a,- |
oa|| qa--(:|-

Sounds Iike it's a good idea to synchronize
everything, just to be thread-safe.

Nope, it's not a good idea. Synchronization doesn't
come for free. Pirst, a synchronized method has a certain
amount of overhead. |n other words, when code hits a
synchronized method, there's going to be a performance hit
(although typically, you'd never notice it) while the matter of
"is the key availableI is resolved.
Second, a synchronized method can slow your program
down because synchronization restricts concurrency. |n
other words, a synchronized method forces other threads to
get in line and wait their turn. This might not be a problem
in your code, but you have to consider it.
Third, and most frightening, synchronized methods can lead
to deadlock! (See page 5l6.)
A good rule of thumb is to synchronize only the bare
minimum that should be synchronized. And in fact, you
can synchronize at a granularity that's even smaller than
a method. we don't use it in the book, but you can use the
synchronized keyword to synchronize at the more fine-
grained level of one or more statements, rather than at the
whole-method level.


-l-|` --:-'l --- l-
- :]-:-----, :- -- --'l
:]-:----- l- --|- --l-
N--, --|] l-:- l-- --l- :.||: .-- ----
-l- --- .l--: --l w-- ]-- -:- l- :]-:----- -]--- w|1+|N . --l-,
-.l-- l.- - . --l- -:|.-.l--, ]--
.- l- --- .- .-----l l.l : l-
--:l --:- -] l- l--. ---: l- -l
A|l-- l--- .-- -l-- -.]: l- - l, ]--
-|| .|--:l .|-.]: :]-:----- -- l- :-----l
--:l |l:` 1.l': l- :.-- --:l ]--'
|-: l- --|- --l- ---- :]-:-----
public void go() {
doStuff();
synchronized(this) {
criticalStuff();
moreCriticalStuff();
}
}
synchronizing methods
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 515

1 Threod A runs for owhiIe


Attempt to enter the increment() method.
The method is synchronized, so get the key for this object
Put the value of balance into variable i.
Balance is 0, so i is now 0.
Set the value of balance to the result of i + 1.
Now balance is 1.
Return the key (it completed the increment() method).
Re-enter the increment() method and get the key.
Put the value of balance into variable i.
Balance is 1, so i is now 1.
[now thread A is sent back to runnable, but since it has not
completed the synchronized method, Thread A keeps the key]

2 Threod 8 is seIecfed fo run


Attempt to enter the increment() method. The method is
synchronized, so we need to get the key.
The key is not avaiIabIe.
[now thread B is sent into a 'object lock not available lounge]

3 Threod A runs ogoin, picking up where if Ieff off


(remember, if sfiII hos fhe key)
Set the value of balance to the result of i + 1.
Now balance is 2.
Return the key.
[now thread A is sent back to runnable, but since it
has completed the increment() method, the thread
does NOT hold on to the key]

4 Threod 8 is seIecfed fo run


Attempt to enter the increment() method. The method is
synchronized, so we need to get the key.
This time, the key S available, get the key.
Put the value of balance into variable i.
[continues to run...]
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
516 chapter 15
Ihc 4cz4|y s|4c ef synrhren|zz!|en
Bc caiclul whcn you usc synchionizcu couc, lccausc noihing
will liing youi iogiam io iis Inccs liIc ihicau ucaulocI.
Thicau ucaulocI hacns whcn you havc iwo ihicaus, loih ol
which aic holuing a Icy ihc oihci ihicau wanis. Thcic`s no way
oui ol ihis sccnaiio, so ihc iwo ihicaus will simly sii anu waii.
Anu waii. Anu waii.
Il you`ic lamiliai wiih uaialascs oi oihci alicaiion scivcis,
you mighi iccognizc ihc iollcm, uaialascs olicn havc a
locIing mcchanism somcwhai liIc synchionizaiion. Bui a
ical iiansaciion managcmcni sysicm can somciimcs ucal wiih
ucaulocI. Ii mighi assumc, loi cxamlc, ihai ucaulocI mighi
havc occuiicu whcn iwo iiansaciions aic iaIing ioo long io
comlcic. Bui unliIc ]ava, ihc alicaiion scivci can uo a
iiansaciion iolllacI" ihai iciuins ihc siaic ol ihc iollcu-lacI
iiansaciion io whcic ii was lcloic ihc iiansaciion ihc aiomic
aii) lcgan.
]ava has no mcchanism io hanulc ucaulocI. Ii won`i cvcn
ucaulocI occuiicu. So ii`s u io you io ucsign caiclully. Il you
hnu youiscll wiiiing much muliiihicaucu couc, you mighi
wani io siuuy ]ava Thicaus" ly Scoii OaIs anu Hcniy Wong
loi ucsign iis on avoiuing ucaulocI. Onc ol ihc mosi common
iis is io ay aiicniion io ihc oiuci in which youi ihicaus aic
siaiicu.
A simple deadlock scenario:
A
Thread A enters a
synchronized method
of object , and gets
the key.
Thread A goes to
sleep, holding the
key.
B
Thread B enters a
synchronized method
of object , and gets
the key.
Thread B tries to enter
a synchronized method
of object , but can't
get key (because
A has it). B goes
to the waiting lounge,
until the key is
available. B keeps the
key.
1 2
A
B
foo
bar
foo
bar
A
Thread A wakes up (still
holding the key)
and tries to enter a
synchronized method on
object , but can't get
key because B has
it. A goes to the waiting
lounge, until the key is
available (it never will be!)
Thread A can't run until
it can get the key,
but B is holding the
key and B can't run until it
gets the key that A is
holding and...
3
A
B A
All it takes for
deadlock are two
ob]ects and two
threads.
foo
bar
foo
thread deadIock
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 517
8ll P0lk5
T|e slal|c T|read.s|eep() rel|od lorces a l|read lo |eave l|e
rurr|r slale lor al |easl l|e dural|or passed lo l|e s|eep rel|od.
T|read.s|eep(200) puls a l|read lo s|eep lor 200 r||||secords.
T|e s|eep() rel|od l|roWs a c|ec|ed excepl|or (lrlerrupledExcepl|or),
so a|| ca||s lo s|eep() rusl oe Wrapped |r a lry/calc|, or dec|ared.
You car use s|eep() lo |e|p ra|e sure a|| l|reads el a c|arce lo rur,
a|l|ou| l|ere's ro uararlee l|al W|er a l|read Wa|es up |l'|| o lo l|e
erd ol l|e rurrao|e ||re. ll r||l, lor exarp|e, o r||l oac| lo l|e lrorl.
lr rosl cases, appropr|ale|y-l|red s|eep() ca||s are a|| you reed lo |eep
your l|reads sW|lc||r r|ce|y.
You car rare a l|read us|r l|e (yel arol|er surpr|se) selNare()
rel|od. A|| l|reads el a delau|l rare, oul |v|r l|er ar exp||c|l rare
car |e|p you |eep lrac| ol l|reads, espec|a||y |l you're deou|r W|l|
pr|rl slalererls.
You car |ave ser|ous proo|ers W|l| l|reads |l lWo or rore l|reads |ave
access lo l|e sare oojecl or l|e |eap.
TWo or rore l|reads access|r l|e sare oojecl car |ead lo dala
corrupl|or |l ore l|read, lor exarp|e, |eaves l|e rurr|r slale W|||e sl|||
|r l|e r|dd|e ol rar|pu|al|r ar oojecl's cr|l|ca| slale.
To ra|e your oojecls l|read-sale, dec|de W||c| slalererls s|ou|d oe
lrealed as ore alor|c process. lr ol|er Words, dec|de W||c| rel|ods
rusl rur lo corp|el|or oelore arol|er l|read erlers l|e sare rel|od
or l|e sare oojecl.
use l|e |eyWord synchronized lo rod|ly a rel|od dec|aral|or,
W|er you Warl lo preverl lWo l|reads lror erler|r l|al rel|od.
Every oojecl |as a s|r|e |oc|, W|l| a s|r|e |ey lor l|al |oc|. Vosl ol l|e
l|re We dor'l care aooul l|al |oc|, |oc|s core |rlo p|ay or|y W|er ar
oojecl |as syrc|ror|zed rel|ods.
w|er a l|read allerpls lo erler a syrc|ror|zed rel|od, l|e l|read
rusl el l|e |ey lor l|e oojecl (l|e oojecl W|ose rel|od l|e l|read
|s lry|r lo rur). ll l|e |ey |s rol ava||ao|e (oecause arol|er l|read
a|ready |as |l), l|e l|read oes |rlo a ||rd ol Wa|l|r |oure, url|| l|e |ey
oecores ava||ao|e.
Ever |l ar oojecl |as rore l|ar ore syrc|ror|zed rel|od, l|ere |s sl|||
or|y ore |ey. 0rce ary l|read |as erlered a syrc|ror|zed rel|od or
l|al oojecl, ro l|read car erler ary ol|er syrc|ror|zed rel|od or l|e
sare oojecl. T||s reslr|cl|or |els you prolecl your dala oy syrc|ror|z|r
ary rel|od l|al rar|pu|ales l|e dala.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
518 chapter 15
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleChatClient {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public static void main(String[] args) {
SimpleChatClient client = new SimpleChatClient();
client.go();
}
public void go() {
JFrame frame = new JFrame(Ludicrously Simple Chat Client);
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(20);
JButton sendButton = new JButton(Send);
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setUpNetworking();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();

frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(400,500);
frame.setVisible(true);

}
hcw zn4 |mprevc4 8|mp|c0hz!0||cn!
Way lacI ncai ihc lcginning ol ihis chaici, wc luili ihc SimlcChaiClicni ihai coulu erJ
ouigoing mcssagcs io ihc scivci lui coulun`i icccivc anyihing. Rcmcmlci. Thai`s how wc
goi onio ihis wholc ihicau ioic in ihc hisi lacc, lccausc wc nccucu a way io uo iwo ihings
ai oncc: scnu mcssagcs o ihc scivci iniciaciing wiih ihc GUI) whilc simuliancously icauing
incoming mcssagcs .o ihc scivci, uislaying ihcm in ihc sciolling icxi aica.
finaI chat cIient
1: : --:l|] 6c| :-- ]--'- :---
---- N-l- :-:.| -:-l l-
|l- .-l ---- -- :l.-l l-
--- '--.--' l--.
w-'-- :l.-l- . --- l--.,
-:- . --- ---- :|.:: .:
l- ---.|- |-` -- l-
l--. 1- l--.': - :
l- --. --- l- :----':
:-:-l :l--.-, :|.]-
.-] -:--- --::.-: - l-
::--||- l-l .--.
/-:, l--- --.||] | .-
-- l- l: :.l--
B-l --l ]-l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 519
private void setUpNetworking() {

try {
sock = new Socket(127.0.0.1, 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println(networking established);
} catch(IOException ex) {
ex.printStackTrace();
}
} // close setUpNetworking
public class SendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
writer.println(outgoing.getText());
writer.ush();

} catch(Exception ex) {
ex.printStackTrace();
}
outgoing.setText();
outgoing.requestFocus();
}
} // close inner class
public class IncomingReader implements Runnable {
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println(read + message);
incoming.append(message + \n);

} // close while
} catch(Exception ex) {ex.printStackTrace();}
} // close run
} // close inner class

} // close outer class
w-'-- -:- l- :-:-l l- -l l- --l
.- --l-l :l--.-: w- ---- .|--.] -:-
l- --l-l :l--.- l- :-- l- l- :----,
-l --- --'-- -:- l- --l :l--.- :-
l.l l- --- '--.--' l--. :.- -l
--::.-: --- l- :----
N-l- --- --- w-- l- -:-- :|::
l- :-- -ll--, l: --l- :--: l-
:--l--l: - l- l-l -| l- l- :----
1: : -.l l- l--. --:''
|- l- ---|` --l-, l :l.]: - .
|-- |.: |-- .: -.l l -l: ---
l- :---- : --l --||`, --.- .
|-- .l . l-- .- .- -.: |--
l- l- ::--||- l-l .--. |.|--
-l . --- |-- :.-.:l--`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
520 chapter 15
Ihc rcz||y rcz||y s|mp|c 0hz! 8crvcr
You can usc ihis scivci couc loi loih vcisions ol ihc Chai Clicni. Evciy ossillc
uisclaimci cvci uisclaimcu is in cllcci hcic. To Icc ihc couc siiicu uown io ihc
laic csscniials, wc iooI oui a loi ol aiis ihai you`u nccu io maIc ihis a ical scivci.
In oihci woius, ii woiIs, lui ihcic aic ai lcasi a hunuicu ways io licaI ii. Il you
wani a Rcally Goou Shaicn Youi Pcncil loi alici you`vc hnishcu ihis looI, comc
lacI anu maIc ihis scivci couc moic iolusi.
Anoihci ossillc Shaicn Youi Pcncil, ihai you coulu uo iighi now, is io annoiaic
ihis couc youiscll. You`ll unucisianu ii much lciici il you woiI oui whai`s
hacning ihan il wc cxlaincu ii io you . Thcn again, ihis is Rcauy-laIc couc,
so you ically uon`i havc io unucisianu ii ai all. Ii`s hcic |usi io suoii ihc iwo
vcisions ol ihc Chai Clicni.
0zsJj-hskz
0aJz
chat server code
import java.io.*;
import java.net.*;
import java.util.*;
public class VerySimpleChatServer {
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;

public ClientHandler(Socket clientSocket) {
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);

} catch(Exception ex) {ex.printStackTrace();}
} // close constructor
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println(read + message);
tellEveryone(message);

} // close while
} catch(Exception ex) {ex.printStackTrace();}
} // close run
} // close inner class
To run the chat client, you need two
terminals. First, launch this server
from one terminal, then launch the
client from another terminal
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 521

public static void main (String[] args) {
new VerySimpleChatServer().go();
}
public void go() {
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(5000);
while(true) {
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println(got a connection);
}

} catch(Exception ex) {
ex.printStackTrace();
}
} // close go
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.ush();
} catch(Exception ex) {
ex.printStackTrace();
}

} // end while

} // close tellEveryone
} // close class

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
522 chapter 15
(-,- a,- |
oa|| qa--(:|-

What about protecting static
variabIe state! If you have static
methods that change the static variabIe
state, can you stiII use synchronization!

es! Pemember that static
methods run against the class and not
against an individual instance of the class.
So you might wonder whose ob|ect's lock
would be used on a static methodI After
all, there might not even oe any instances
of that class. Portunately, |ust as each
ooject has its own lock, each loaded closs
has a lock. That means that if you have
three Dog ob|ects on your heap, you have
a total of four Dog-related locks. Three
belonging to the three Dog instances,
and one belonging to the Dog class itself.
when you synchronize a static method,
1ava uses the lock of the class itself. So if
you synchronize two static methods in a
single class, a thread will need the class
lock to enter e|thet of the methods.

What are thread priorities! I've
heard that's a way you can controI
scheduIing.

Thread priorities m|ht help
you influence the scheduler, but they
still don't offer any guarantee. Thread
priorities are numerical values that tell
the scheduler (if it cares) how important a
thread is to you. |n general, the scheduler
will kick a lower priority thread out of the
running state if a higher priority thread
suddenly becomes runnable. 8ut... one
more time, say it with me now, "there
is no guarantee. we recommend that
you use priorities only if you want to
influence etlotmonce, but never, ever
rely on them for program correctness.

Why don't you just synchronize
aII the getters and setters from the
cIass with the data you're trying to
protect! Like, why couIdn't we have
synchronized just the checkaIance()
and withdraw() methods from cIass
ankAccount, instead of synchronizing
the makeWithdrawaI() method from
the RunnabIe's cIass!

Actually, we shoulJ have
synchronized those methods, to prevent
other threads from accessing those
methods in other ways. we didn't bother,
because our example didn't have any
other code accessing the account.
8ut synchronizing the getters
and setters (or in this case the
check8alance() and withdraw()) isn't
enough. Pemember, the point of
synchronization is to make a specific
section of code work ATOM|CALL. |n
other words, it's not |ust the individual
methods we care about, it's methods
that require mere rhnn ene sre re
cemlere! Think about it. |f we had not
synchronized the makewithdrawal()
method, Pyan would have checked the
balance (by calling the synchronized
check8alance()), and then immediately
exited the method and returned the key!
Of course he would grab the key again,
after he wakes up, so that he can call
the synchronized withdraw() method,
but this still leaves us with the same
problem we had before synchronization!
Pyan can check the balance, go to sleep,
and Monica can come in and also check
the balance before Pyan has a chance to
wakes up and completes his withdrawal.
So synchronizing all the access methods
is probably a good idea, to prevent
other threads from getting in, but you
still need to synchronize the methods
that have statements that must execute
as one atomic unit.
synchronization questions
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 523
CaJe kit:hea
This is the |ast ve:siaa aI the 5eat5ax!
!t :aaae:ts ta a si|e Kasi:Se:ve: sa that yaa :aa
seaJ aaJ :e:eive leat atte:as vith athe: :|ieats.
The :aJe is :ea||y |aag, sa the :a|ete |istiag is
a:taa||y ia AeaJix A.
]--- --::.- -l: :--l l-
l- -l-- |.]--:, .|--
-l ]--- :-----l -.l
.ll---, --- ]-- l
:--|l'
Andy: groove #2
6hr|s: groove2 rev|sed
N|ge|: dance beat
dance beat
-:--- --::.-: --- |.]--: c|: --- l- |-.
l- .ll--- l.l --: -l l, .- l-- :|: 'l.-l' l- |.] l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
524 chapter 15
A working 1ava program is scrambled up on the fridge. Can
you add the code snippets on the next page to the empty
classes below, to make a working 1ava program that pro-
duces the output listedI 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!
File Edit Window Help Sewing
% java TestThreads
one 98098
two 98099

CaJe Kagaets
class ThreadOne
class Accum {
class ThreadTwo
public class TestThreads {
onus uestion: why do you think we used the
modifiers we did in the Accum classI
exercise: Code Magnets
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 525
try {
Thread.sleep{50|,
Thread.sleep{50|,
CaJe Kagaets, :aatiaaeJ..
counter += add,
return a,
implements Runnable {
public void run{| {
return counter,
one.start{|,
a.updateCounter{l000|,
Thread one = new Thread{tl|,
try {
public static void main{String args| {
for{int x=0, x < 99, x++| {
} catch{InterruptedException ex| { }
private static Accum a = new Accum{|,
} catch{InterruptedException ex| { }
implements Runnable {
Accum a = Accum.getAccum{|,
Accum a = Accum.getAccum{|,
public void run{| {
for{int x=0, x < 98, x++| {
two.start{|,
ThreadOne tl = new ThreadOne{|,
ThreadTwo t2 = new ThreadTwo{|,
public void updateCounter{int add| {
private Accum{| { }
public int getCount{| {
System.out.println{"two "+a.getCount{||,
System.out.println{"one "+a.getCount{||,
public static Accum getAccum{| {
private int counter = 0,
a.updateCounter{l|,
Thread two = new Thread{t2|,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
526 chapter 15
]e;ejze o|ajoz
public class TestThreads {
public static void main{String args| {
ThreadOne tl = new ThreadOne{|,
ThreadTwo t2 = new ThreadTwo{|,
Thread one = new Thread{tl|,
Thread two = new Thread{t2|,
one.start{|,
two.start{|,
}
}
class Accum {
private static Accum a = new Accum{|,
private int counter = 0,
private Accum{| { }
public static Accum getAccum{| {
return a,
}
public void updateCounter{int add| {
counter += add,
}
public int getCount{| {
return counter,
}
}
class ThreadOne implements Runnable {
Accum a = Accum.getAccum{|,
public void run{| {
for{int x=0, x < 98, x++| {
a.updateCounter{l000|,
try {
Thread.sleep{50|,
} catch{InterruptedException ex| { }
}
System.out.println{"one "+a.getCount{||,
}
}
class ThreadTwo implements Runnable {
Accum a = Accum.getAccum{|,
public void run{| {
for{int x=0, x < 99, x++| {
a.updateCounter{l|,
try {
Thread.sleep{50|,
} catch{InterruptedException ex| { }
}
System.out.println{"two "+a.getCount{||,
}
}
Threods from fwo differenf cIosses ore updofing
fhe some objecf in o fhird cIoss, becouse bofh
fhreods ore occessing o singIe insfonce of Accum.
The Iine of code:
private static Accum a new Accum( ), creofes o
sfofic insfonce of Accum (remember sfofic meons
one per cIoss), ond fhe privofe consfrucfor in
Accum meons fhof no one eIse con moke on Accum
objecf. These fwo fechniques (privofe consfrucfor
ond sfofic geffer mefhod) used fogefher, creofe
whof's known os o 'SingIefon' - on OO poffern fo
resfricf fhe number of insfonces of on objecf
fhof con exisf in on oppIicofion. (UsuoIIy, fhere's
jusf o singIe insfonce of o SingIefon-hence fhe
nome), buf you con use fhe poffern fo resfricf fhe
insfonce creofion in whofever woy you choose.)
:--.l- . :l.l: -:l.-:-
- :|.:: A::--
A -.l- :--:l--:l--
exercise soIutions
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 527
As Sarah joined the on-board development team`s design review meeting , she gazed out
the portal at sunrise over the Indian Ocean. Even though the ship`s conIerence room was
incredibly claustrophobic, the sight oI the growing blue and white crescent overtaking night on
the planet below flled Sarah with awe and appreciation.
This morning`s meeting was Iocused on the control systems Ior the orbiter`s airlocks.
As the fnal construction phases were nearing their end, the number oI spacewalks was
scheduled to increase dramatically, and traIfc was high both in and out oI the ship`s
airlocks. 'Good morning Sarah, said Tom, 'Your timing is perIect, we`re just starting
the detailed design review.
'As you all know, said Tom, 'Each airlock is outftted with space-hardened GUI
terminals, both inside and out. Whenever spacewalkers are entering or exiting the orbiter
they will use these terminals to initiate the airlock sequences. Sarah nodded, 'Tom can
you tell us what the method sequences are Ior entry and exit? Tom rose, and foated to the
whiteboard, 'First, here`s the exit sequence method`s pseudocode, Tom quickly wrote on the
board.
orbiterAirlockExitSequence()
verifyPortalStatus();
pressurizeAirlock();
openInnerHatch();
conhrmAirlockOccupied();
closeInnerHatch();
decompressAirlock();
openOuterHatch();
conhrmAirlockVacated();
closeOuterHatch();
'To ensure that the sequence is not interrupted, we have synchronized all oI the
methods called by the orbiterAirlockExitSequence() method, Tom explained. 'We`d hate to
see a returning spacewalker inadvertently catch a buddy with his space pants down!
Everyone chuckled as Tom erased the whiteboard, but something didn`t Ieel right
to Sarah and it fnally clicked as Tom began to write the entry sequence pseudocode on the
whiteboard. 'Wait a minute Tom!, cried Sarah, 'I think we`ve got a big faw in the exit
sequence design, let`s go back and revisit it, it could be critical!
Why aia Sarah stop the meeting? What aia she suspect?
]Jc_Jna[c
_s[ci
Near-miss at the Airlock
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
528 chapter 15
What did Sarah knov?
Saiah icalizcu ihai in oiuci io cnsuic ihai ihc cniiic cxii
scqucncc woulu iun wiihoui iniciiuiion ihc
orbiterAirlockExitSequence ) mcihou nccucu io
lc synchionizcu. As ihc ucsign sioou, ii woulu lc ossillc
loi a iciuining saccwalIci io iniciiui ihc Exii Scqucncc!
Thc Exii Scqucncc ihicau coulun`i lc iniciiuicu in ihc
miuulc ol any ol ihc lowci lcvcl mcihou calls, lui ii ouIJ lc
iniciiuicu in beweer ihosc calls. Saiah Incw ihai ihc cniiic
scqucncc shoulu lc iun as onc aiomic unii, anu il ihc orbit
erAirlockExitSequence( ) mcihou was synchionizcu, ii
coulu noi lc iniciiuicu ai any oini.
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 529
Sorting is a snap in Java. ou have all the tools for collecting and manipulating
your data without having to write your own sort algorithms (unless you're reading this right
now sitting in your Computer Science l0l class, in which case, trust usyou are SO going to be
writing sort code while the rest of us |ust call a method in the 1ava AP|). The 1ava Collections
Pramework has a data structure that should work for virtually anything you'll ever need to do.
want to keep a list that you can easily keep adding toI want to find something by nameI want
to create a list that automatically takes out all the duplicatesI Sort your co-workers by the
number of times they've stabbed you in the backI Sort your pets by number of tricks learnedI
|t's all here...

16 coIIections and generics


Sheesh... ond oII
fhis fime I couId hove jusf Ief
Jovo puf fhings in oIphobeficoI
order7 Third grode reoIIy
sucks. We never Ieorn
onyfhing usefuI...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
530 chapter 16
You havc a lisi ol songs in a hlc, whcic cach linc
icicscnis onc song, anu ihc iiilc anu aiiisi aic
scaiaicu wiih a loiwaiu slash. So ii shoulu lc simlc
io aisc ihc linc, anu ui all ihc songs in an AiiayIisi.
Youi loss caics only aloui ihc song iiilcs, so loi now
you can simly maIc a lisi ihai |usi has ihc song iiilcs.
Bui you can scc ihai ihc lisi is noi in alhalciical
oiuci... whai can you uo.
You Inow ihai wiih an AiiayIisi, ihc clcmcnis aic
Ici in ihc oiuci in which ihcy wcic insciicu inio ihc
lisi, so uiiing ihcm in an AiiayIisi won`i iaIc caic ol
alhalciizing ihcm, unlcss... maylc ihcic`s a soii)
mcihou in ihc AiiayIisi class.
Congiaiulaiions on youi ncw |ol-managing ihc auiomaicu
|uIclox sysicm ai Iou`s Dinci. Thcic`s no ]ava insiuc ihc
|uIclox iiscll, lui cach iimc somconc lays a song, ihc
song uaia is acnucu io a simlc icxi hlc.
Youi |ol is io managc ihc uaia io iiacI song oulaiiiy,
gcnciaic icoiis, anu maniulaic ihc laylisis. You`ic noi
wiiiing ihc cniiic a-somc ol ihc oihci soliwaic ucvcloci/
waiicis aic involvcu as wcll, lui you`ic icsonsillc loi managing
anu soiiing ihc uaia insiuc ihc ]ava a. Anu sincc Iou has a ihing
againsi uaialascs, ihis is siiicily an in-mcmoiy uaia collcciion. All
you gci is ihc hlc ihc |uIclox Iccs auuing io. Youi |ol is io iaIc ii
liom ihcic.
You`vc alicauy hguicu oui how io icau anu aisc ihc hlc, anu so lai
you`vc lccn sioiing ihc uaia in an AiiayIisi.
Irzrk|n] sen] pepe|zr| !y en yeer jekc|er
sorting a Iist
Challenge #1
8ort the songs in alphabetical order
SongList,tt
Pink Moon/Nick Drake
Somersault/Zero 7
Shiva Moon/Prem Joshua
Circles/BT
Deep Channel/Afro Celts
Passenger/Headmix
Listen/Tahiti 80
1: : l- |- l- --- -:-
--l-: /--- :-- --:l --. l- |-,
l-- -.--|.l- l- :-- .l.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 531
Hcrcs whz! yee hzvc se fzr, w| !hee! !hc ser!:
import java.util.*;
import java.io.*;
public class Jukebox1 {

ArrayList<String> songList = new ArrayList<String>();

public static void main(String[] args) {
new Jukebox1().go();
}

public void go() {
getSongs();
System.out.println(songList);
}

void getSongs() {
try {
File hle = new File(SongList.txt);
BufferedReader reader = new BufferedReader(new FileReader(hle));
String line = null;
while ((line= reader.readLine()) != null) {
addSong(line);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}

void addSong(String lineToParse) {
String[] tokens = lineToParse.split(/);
songList.add(tokens[0]);
}

}
w-'|| :l--- l- :-- ll|-: -
.- A--.]|:l - l--:
N-l- :-:.| --- -:l --. l- |- .-
:.|| l- .--|` --l- -- -.: |--
1- .-- --l- ---: -:l |- l- 6--~
c.- - l- |/6 :.l--~~]-- --. l- |--
|l.l .: -l l- ll|- .- .-l:l` -l- l--
-:-: |l---:` -:- l- :|l|` --l-
w- --|] -.-l l- :-- ll|-, :-
. --|] l- -:l l--- l- l-
--|:l |l- A--.]|:l`
1- --l- l.l :l.-l: |-.- l-
|- .- l-- --l: l- :--l--l: -
l- :--|:l A--.]|:l
File Edit Window Help Dance
%java Jukebox1
[Pink Moon, Somersault,
Shiva Moon, Circles,
Deep Channel, Passenger,
Listen]
1- :--|:l --l: --l -l l-
:--: - l- ---- - -: l-]
---- .- l- l- A--.]|:l |-:
: l- :.-- ---- l- :--: .-- -
-l- l- ---.| l-l |-`
1: : --l-|] N61 .|.-l:.| '
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
532 chapter 16

Be! !hc rrzyI|s! r|zss 4ecs h0I hzvc z ser!|I mc!he4|
Whcn you looI in AiiayIisi, ihcic uocsn`i sccm io lc any mcihou iclaicu io soiiing.
WalIing u ihc inhciiiancc hiciaichy uiun`i hcl ciihci-ii`s clcai ihai you con`t coII o sort
method on the ArroyList.
A--.]|:l .: . |-l - --l-:,
-l l---': --l- --- l.l
|--: |- l ---| :--l
ArrayList API
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 533
I do see o coIIecfion cIoss
coIIed TreeSef... ond fhe docs
soy fhof if keeps your dofo
sorfed. I wonder if I shouId be
using o TreeSef insfeod of on
ArroyLisf...
rrzyI|s! |s ne! !hc en|y re||cr!|en
Alihough AiiayIisi is ihc onc you`ll usc mosi olicn,
ihcic aic oihcis loi sccial occasions. Somc ol ihc Icy
collcciion classcs incluuc:

Tree8et
Keeps l|e e|ererls sorled ard preverls dup||cales.

hashHap
Lel's you slore ard access e|ererls as rare/va|ue pa|rs.

L|nkedL|st
0es|red lo |ve oeller perlorrarce W|er you |rserl or de|ele
e|ererls lror l|e r|dd|e ol l|e co||ecl|or. (lr pracl|ce, ar
ArrayL|sl |s sl||| usua||y W|al you Warl.)

hash8et
Preverls dup||cales |r l|e co||ecl|or, ard |ver ar e|ererl, car
l|rd l|al e|ererl |r l|e co||ecl|or qu|c||y.

L|nkedhashHap
L||e a reu|ar las|Vap, excepl |l car rereroer l|e order |r
W||c| e|ererls (rare/va|ue pa|rs) Were |rserled, or |l car oe
corl|ured lo rereroer l|e order |r W||c| e|ererls Were |asl
accessed.
l--'l ----] .--l l-]-
l- |-.-- l-:- -l-- ---:
-l --- w-'|| - -l-
---- -l.|: . |ll|- |.l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
534 chapter 16
Il you ui all ihc Siiings ihc song iiilcs) inio a insicau ol
an AiiayIisi, ihc Siiings woulu auiomaiically lanu in ihc iighi lacc,
alhalciically soiicu. Whcncvci you iinicu ihc lisi, ihc clcmcnis woulu
always comc oui in alhalciical oiuci.
Anu ihai`s gicai whcn you nccu a wc`ll
ialI aloui scis in a lcw minuics) oi whcn
you Inow ihai ihc lisi musi siay
soiicu alhalciically.
On ihc oihci hanu, il you uon`i nccu ihc
lisi io siay soiicu, TiccSci mighi lc moic
cxcnsivc ihan you nccu-every time you
insert into o TreeSet, the TreeSet hos to tohe
the time to fgure out where in the tree the new
eIement must go. Wiih AiiayIisi, insciis can
lc llinuingly lasi lccausc ihc ncw clcmcni
|usi gocs in ai ihc cnu.
Yee ree|4 esc z Ircc8c!...
0r yee ree|4 esc !hc 0e||cr!|ens.ser!|I mc!he4
CoIIections.sort()
puo||c slal|c vo|d copy(L|sl desl|ral|or, L|sl source)
puo||c slal|c L|sl emptyL|st()
puo||c slal|c vo|d f|||(L|sl ||slToF|||, 0ojecl oojToF|||llw|l|)
puo||c slal|c |rl frequency(Co||ecl|or c, 0ojecl o)
puo||c slal|c vo|d reverse(L|sl ||sl)
puo||c slal|c vo|d rotate(L|sl ||sl, |rl d|slarce)
puo||c slal|c vo|d shuff|e(L|sl ||sl)
puo||c slal|c vo|d sort(L|sl ||sl)
puo||c slal|c ooo|ear rep|aceA||(L|sl ||sl, 0ojecl o|dva|, 0ojecl reWva|)
// rary rore rel|ods...
java.ut||.6o||ect|ons

ut you CAN add something to an


ArrayList at a specic index instead of just at
the end-there's an overIoaded add() method
that takes an int aIong with the eIement to add.
So wouIdn't it be sIower than inserting at the end!

es, it's slower to insert something in an ArrayList
somewhere othet than at the end. So using the overloaded
add(index, element) method doesn't work as quickly as calling
the add(element)which puts the added element at the end.
8ut most of the time you use ArrayLists, you won't need to put
something at a specific index.

I see there's a LinkedList cIass, so wouIdn't be better for


doing inserts somewhere in the middIe! At Ieast if I remember my Data
Structures cIass from coIIege...

es, good spot. The LinkedList con be quicker when you insert or
remove something from the middle, but for most applications, the difference
between middle inserts into a LinkedList and ArrayList is usually not enough
to care about unless you're dealing with a hue number of elements. we'll
look more at LinkedList in a few minutes.
+--- l--- | . :--l|` --l-
- l- c-||-:l--: :|.:: |l l.-:
. |:l, .- :-:- A--.]|:l
-|----l: l- |:l -l--.:-,
A--.]|:l |~A |:l 1.-:
l- -|]---:-, ]-- :.- .:: .-
A--.]|:l l- . --l- -:|.--
l- l.- |:l
N-l- l: : N61 l- --.| c-||-:l--:
:|.:: A||. -- :-|- l --- ] |-.-
--l l- ----: l]- ----.l-- |-:
]--'|| :-- - . -- .-:`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 535
[[ (]]e(jn,.,(()
([] ,(, z ]j,( |
(jng, z][z(jez]]y.
44|n] 0e||cr!|ens.ser!|I !e !hc 1ekc|er re4c
File Edit Window Help Chill
%java Jukebox1
[Pink Moon, Somersault, Shiva Moon, Circles, Deep
Channel, Passenger, Listen]
[Circles, Deep Channel, Listen, Passenger, Pink
Moon, Shiva Moon, Somersault]
import java.util.*;
import java.io.*;
public class Jukebox1 {

ArrayList<String> songList = new ArrayList<String>();

public static void main(String[] args) {
new Jukebox1().go();
}

public void go() {
getSongs();
System.out.println(songList);
Collections.sort(songList);
System.out.println(songList);
}

void getSongs() {
try {
File hle = new File(SongList.txt);
BufferedReader reader = new BufferedReader(new FileReader(hle));
String line = null;
while ((line= reader.readLine()) != null) {
addSong(line);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}

void addSong(String lineToParse) {
String[] tokens = lineToParse.split(/);
songList.add(tokens[0]);
}
}
c.|| l- :l.l: c-||-:l--:
:--l|` --l-, l-- --l l-
|:l ..- 1- :-:-- --l --l
: - .|.-l:.| ----'
B---- :.||- :--l|`
Al-- :.||- :--l|`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
536 chapter 16
Be! new yee ncc4 8en] e|jcr!s,
ne! jes! s|mp|c 8!r|n]s.
Now youi loss wanis aciual Song class insianccs in ihc lisi, noi |usi
Siiings, so ihai cach Song can havc moic uaia. Thc ncw |uIclox
ucvicc ouiuis moic inloimaiion, so ihis iimc ihc hlc will havc
icccs ioIcns) insicau ol |usi iwo.
Thc Song class is ically simlc, wiih only onc inicicsiing lcaiuic-
ihc ovciiiuucn ioSiiing) mcihou. Rcmcmlci, ihc ioSiiing)
mcihou is uchncu in class Ol|cci, so cvciy class in ]ava inhciiis ihc
mcihou. Anu sincc ihc ioSiiing) mcihou is callcu on an ol|cci
whcn ii`s iinicu Sysicm.oui.iinilnanOl|cci)), you shoulu
ovciiiuc ii io iini somcihing moic icauallc ihan ihc uclauli
uniquc iucniihci couc. Whcn you iini a lisi, ihc ioSiiing)
mcihou will lc callcu on cach ol|cci.
SongListMore,tt
Pink Moon/Nick Drake/5/80
Somersault/Zero 7/4/84
Shiva Moon/Prem Joshua/6/120
Circles/BT/5/110
Deep Channel/Afro Celts/4/120
Passenger/Headmix/4/100
Listen/Tahiti 80/5/90
class Song {
String title;
String artist;
String rating;
String bpm;

Song(String t, String a, String r, String b) {
title = t;
artist = a;
rating = r;
bpm = b;
}

public String getTitle() {
return title;
}

public String getArtist() {
return artist;
}

public String getRating() {
return rating;
}

public String getBpm() {
return bpm;
}

public String toString() {
return title;
}
}
|--- -:l.-:- .-.|-: -- l-
--- :-- .ll--l-: - l- |-
1- --- :-- |- -|: ---
.ll--l-: -:l-. - -:l l--
A- -- -.-l A|| - l-- - ---
|:l, :- -- --- l- -.- . --
:|.:: -l -:l.-:- .-.|-: -- .||
--- :-- .ll--l-:
1- .-.|-: .-- .|| :-l -
l- :--:l--:l-- --- l-
--- -- : :--.l-
1- -ll-- --l-: --
l- --- .ll--l-:
w- ----- l-l--|`, -:.-:- --- ]-- - . ]:l--
--l--l|-|.--6-:l`, -- -.-l l- :-- l- ll|-
w-- ]-- - . ]:l----l--l|-|.|:l6--:`, l :.||:
l- l-l--|` --l- - !Ac+ -|----l - l- |:l
sorting your own objects
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 537
import java.util.*;
import java.io.*;
public class Jukebox3 {
ArrayList<Song> songList = new ArrayList<Song>();
public static void main(String[] args) {
new Jukebox3().go();
}
public void go() {
getSongs();
System.out.println(songList);
Collections.sort(songList);
System.out.println(songList);
}
void getSongs() {
try {
File hle = new File(SongList.txt);
BufferedReader reader = new BufferedReader(new FileReader(hle));
String line = null;
while ((line= reader.readLine()) != null) {
addSong(line);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
void addSong(String lineToParse) {
String[] tokens = lineToParse.split(/);
Song nextSong = new Song(tokens[0], tokens[1], tokens[2], tokens[3]);
songList.add(nextSong);
}
}
c.-- l- .- A--.]|:l - --
--:l: -:l-. - l--
c--.l- . --- -- --:l -:- l- --- l---:
|-: --.-: l- --- -:-: - -- - l- :-- |-
-- l: |--`, l-- . l- -- l- l- |:l
0hzn]|n] !hc 1ekc|er re4c !e esc 8en]s
|ns!cz4 ef 8!r|n]s
Youi couc changcs only a liiilc-ihc hlc I/O couc is ihc samc,
anu ihc aising is ihc samc Siiing.slii)), cxcci ihis iimc
ihcic will lc ioIcns loi cach song/linc, anu all loui will lc
uscu io cicaic a ncw Song ol|cci. Anu ol couisc ihc AiiayIisi
will lc ol iyc Song> insicau ol Siiing>.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
538 chapter 16
|! wen! remp||c|
Somcihing`s wiong... ihc Collcciions class clcaily shows ihcic`s a
soii) mcihou, ihai iaIcs a Iisi.
AiiayIisi is-a Iisi, lccausc AiiayIisi imlcmcnis ihc Iisi inicilacc,
so... ii LouIJ woiI.
But it doesn`t:
Thc comilci says ii can`i hnu a soii mcihou ihai iaIcs an
AiiayIisiSong>, so maylc ii uocsn`i liIc an AiiayIisi ol Song
ol|ccis. Ii uiun`i minu an AiiayIisiSiiing>, so whai`s ihc
imoiiani uillcicncc lciwccn Song anu Siiing. Whai`s ihc
uillcicncc ihai`s maIing ihc comilci lail.
File Edit Window Help Bummer
%javac Jukebox3.java
Jukebox3.java:15: cannot nd symbol
symbol : method sort(java.util.ArrayList<Song>)
location: class java.util.Collections
Collections.sort(songList);
^
1 error
Anu ol couisc you iolally alicauy asIcu youiscll, Whai woulu ii
lc soiiing or." How woulu ihc soii mcihou cvcn Irow whai mauc
onc Song gicaici oi lcss ihan anoihci Song. Olviously il you wani
ihc song`s .Ie io lc ihc valuc ihai ucicimincs how ihc songs aic
soiicu, you`ll nccu somc way io icll ihc soii mcihou ihai ii nccus
io usc ihc iiilc anu noi, say, ihc lcais ci minuic.
Wc`ll gci inio all ihai a lcw agcs liom now, lui hisi, lci`s hnu oui
why ihc comilci won`i cvcn lci us ass a Song AiiayIisi io ihc
soii) mcihou.
CoIIections.sort()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 539
Ihc ser!|I mc!he4 4cr|zrz!|en
Iiom ihc API uocs looIing u ihc |ava.uiil.Collcciions class, anu sciolling io ihc soii)
mcihou), ii looIs liIc ihc soii) mcihou is ucclaicu... .nreI,. Oi ai lcasi uillcicni liom
anyihing wc`vc sccn so lai.
Thai`s lccausc ihc soii) mcihou along wiih oihci ihings in ihc wholc collcciion liamcwoiI in
]ava) maIcs hcavy usc ol ere... Anyiimc you scc somcihing wiih anglc liacIcis in ]ava souicc
couc oi uocumcniaiion, ii mcans gcnciics-a lcaiuic auucu io ]ava .0. So ii looIs liIc wc`ll
havc io lcain how io iniciici ihc uocumcniaiion lcloic wc can hguic oui why wc wcic allc io
soii Siiing ol|ccis in an AiiayIisi, lui noi an AiiayIisi ol Song ol|ccis.
WTF7 I hove no ideo how fo
reod fhe mefhod decIorofion
on fhis. If soys fhof sorf()
fokes o LisfT, buf whof is
T7 And whof is fhof big fhing
before fhe refurn fype7
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
540 chapter 16
0cncr|rs mczns merc !ypc-szfc!y
Wc`ll |usi say ii iighi hcic-...unII, nII o Le oJe ,ou w..e Ln JenI
w.L ere.. w.II be oIIe.or-.eIneJ oJe. Alihough gcnciics can lc uscu
in oihci ways, ihc main oini ol gcnciics is io lci you wiiic iyc-salc
collcciions. In oihci woius, couc ihai maIcs ihc comilci sio you
liom uiiing a Dog inio a lisi ol DucIs.
Bcloic gcnciics which mcans lcloic ]ava .0), ihc comilci coulu
noi caic lcss whai you ui inio a collcciion, lccausc all collcciion
imlcmcniaiions wcic ucclaicu io holu iyc Ol|cci. You coulu ui
nr,L.r in any AiiayIisi, ii was liIc all AiiayIisis wcic ucclaicu as
AiiayIisiOl|cci>.
yj([ gnje,, ya ezn
ez( (y-,z| e]]e(jn,
w[ ], z
ezag[( z( ej]-(j
jn,(z] | an(j.
yj([a( gnje,, ([
ej] wa]] [zj]y ](
ya a( z ]a[jn jn( zn
jzyjj,( ([z( wz, ,a,]
( []] n]y (z( je(,.
WTHOUT generics
ArrayList
Ob]ect Ob]ect Ob]ect Ob]ect
0bjects go |N as a reference to
8occera||, F|sh, Cu|tar, and
6ar objects
And come 0UT as a reference of type 0bject
WTH generics
0bjects go |N as a reference to
on|y F|sh objects
And come out as a reference of type F|sh
ArrayList<Fish>
B---- ----::, l--- -.: --
-.] l- -:|.-- l- l]- - .-
A--.]|:l, :- l: .|` --l-
l-- l]- 6-:l
N-- -l ----::, ]-- :.- -l --|] |:
--:l: - l- A--.]|:l|:, :- l-
--:l: :--- --l .: |: ------:-:
/-- --'l .- l- ----] .--l :------
:l:- . /-|:-.-- - l---, -- l.l
-.l ]-- -l --l ---'l --.||] - :.:l~
.|- l- . |: ------:-
generic types
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 541
1 6reat|ng |nstances of gener|f|ed clesses (||ke ArrayL|st}
Whcn you maIc an AiiayIisi, you havc io icll ii ihc iyc
ol ol|ccis you`ll allow in ihc lisi, |usi as you uo wiih lain
olu aiiays.
3 0ec|ar|ng (and |nvok|ng} methods that take gener|c types
Il you havc a mcihou ihai iaIcs as a aiamcici, say, an
AiiayIisi ol Animal ol|ccis, whai uocs ihai ically mcan.
Can you also ass ii an AiiayIisi ol Dog ol|ccis. Wc`ll
looI ai somc sulilc anu iiicIy olymoihism issucs ihai
aic vciy uillcicni liom ihc way you wiiic mcihous ihai
iaIc lain olu aiiays.
This is aciually ihc samc oini as #2, lui ihai shows you
how imoiiani wc ihinI ii is.)
2 0ec|ar|ng and ass|gn|ng veriebles of gener|c types
How uocs olymoihism ically woiI wiih gcnciic
iycs. Il you havc an AiiayIisiAnimal> iclcicncc
vaiiallc, can you assign an AiiayIisiDog> io ii. Whai
aloui a IisiAnimal> iclcicncc. Can you assign an
AiiayIisiAnimal> io ii. You`ll scc...
Iczrn|n] ]cncr|rs
Ol ihc uozcns ol ihings you coulu lcain aloui gcnciics, ihcic aic
ically only ihicc ihai maiici io mosi iogiammcis:
new ArrayList<Song>()
List<Song> songList =
new ArrayList<Song>()
void foo(List<Song> list)
x.foo(songList)

ut don't I aIso need to Iearn how to create my DWN generic


cIasses! What if I want to make a cIass type that Iets peopIe
instantiating the cIass decide the type of things that cIass wiII use!

ou probably won't do much of that. Think about itthe AP|
designers made an entire library of collections classes covering most of
the data structures you'd need, and virtually the only type of classes that
really need to be generic are collection classes. |n other words, classes
designed to hold other elements, and you want programmers using it to
specify what type those elements are when they declare and instantiate
the collection class.
es, it is possible that you might want to generic classes, but that's
the exception, so we won't cover it here. (8ut you'll figure it out from the
things we cover, anyway.)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
542 chapter 16
0s|n] ]cncr|r 0I88I8
Sincc AiiayIisi is oui mosi-uscu gcnciihcu iyc, wc`ll
siaii ly looIing ai iis uocumcniaiion. Thcy iwo Icy aicas
io looI ai in a gcnciihcu class aic:
1) Thc In ucclaiaiion
S) Thc eLoJ ucclaiaiions ihai lci you auu clcmcnis
public boolean add(E o)
// more code
public class ArrayList<E> extends AbstractList<E> implements List<E> ... {

}

Understanding ArrayList documentation
{Or, what's the true meaning of E?}
[[jn[ | [ z, z ,(zn]-jn |
([ (y | ]n( ya wzn(
([j, e]]e(jn ( []] zn]
(an. ([ j, | []n(.)
1- !' : . |.:--|-- -- l-
!A| l]- ]-- -:- --- ]--
-:|.-- .- :--.l- .- A--.]|:l
A--.]|:l : . :-:|.:: - A:l-.:l|:l,
:- -.l--- l]- ]-- :-:] -- l-
A--.]|:l : .-l--.l:.||] -:- -- l-
l]- - l- A:l-.:l|:l
1- l]- |l- .|-- - !`
-:---: l- l]- - l- |:l
-l--.:- .: --||
+---': l- ---l.-l .-l' w.l--- !' :
-l-----: -.l - - l-: ]--'-- .||---
l- . l- l- A--.]|:l
Thc E" icicscnis ihc iyc uscu io cicaic an insiancc
ol AiiayIisi. Whcn you scc an E" in ihc AiiayIisi
uocumcniaiion, you can uo a mcnial hnu/iclacc io
cxchangc ii loi whaicvci iyc> you usc io insianiiaic
AiiayIisi.
So, ncw AiiayIisiSong> mcans ihai E" lccomcs Song",
in any mcihou oi vaiiallc ucclaiaiion ihai uscs E".
generic cIasses
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 543
public boolean add(E o)
// more code
public class ArrayList<E> extends AbstractList<E> ... {

}

0s|n] !ypc pzrzmc!crs w| !h rrzyI|s!
TH8 code:
Means ArrayList:
ArrayList<String> thisList = new ArrayList<String>
public boolean add(String o)
// more code
}

s treated by the compiler as:
public class ArrayList<String> extends AbstractList<String>... {

exte
In oihci woius, ihc E" is iclaccu ly ihc .enI iyc also callcu ihc ,e n.nee.)
ihai you usc whcn you cicaic ihc AiiayIisi. Anu ihai`s why ihc auu) mcihou
loi AiiayIisi won`i lci you auu anyihing cxcci ol|ccis ol a iclcicncc iyc ihai`s
comaiillc wiih ihc iyc ol E". So il you maIc an AiiayIisi<String>, ihc auu)
mcihou suuucnly lccomcs add(String o). Il you maIc ihc AiiayIisi ol iyc Dog,
suuucnly ihc auu) mcihou lccomcs add(Dog o).

Is "" the onIy thing you can put there! ecause the docs for sort used "7"....

ou can use anything that's a legal 1ava identifier. That means anything that you
could use for a method or variable name will work as a type parameter. 8ut the conven-
tion is to use a single letter (so that's what you should use), and a further convention is to
use "T unless you're specifically writing a collection class, where you'd use "L to repre-
sent the "type of the Llement the collection will hold.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
544 chapter 16
0s|n] ]cncr|r MIIH0P8
A gcnciic In mcans ihai ihc In JeIn.n.or incluucs a iyc
aiamcici. A gcnciic eLoJ mcans ihai ihc mcihou ucclaiaiion
uscs a iyc aiamcici in iis signaiuic.
You can usc iyc aiamcicis in a mcihou in scvcial uillcicni ways:
1 Us|ng a type parameter def|ned |n the c|ass dec|arat|on
Whcn you ucclaic a iyc aiamcici loi ihc class, you
can simly usc ihai iyc any lacc ihai you`u usc a
.enI class oi inicilacc iyc. Thc iyc ucclaicu in ihc
mcihou aigumcni is csscniially iclaccu wiih ihc iyc
you usc whcn you insianiiaic ihc class.
2 Us|ng a type parameter that was N0T def|ned |n the c|ass dec|arat|on
Il ihc class iiscll uocsn`i usc a iyc aiamcici, you can siill
sccily onc loi a mcihou, ly ucclaiing ii in a ically unusual
lui availallc) sacc-beo.e Le .eu.r ,e. This mcihou says
ihai T can lc any iyc ol Animal".
public boolean add(E o)
public class ArrayList<E> extends AbstractList<E> ... {
/-- :.- -:- l- !' --- 6N|/ -:.-:- l':
.|--.] --- --- .: .-l - l- :|.::
public <T extends Animal> void takeThing(ArrayList<T> list)
+--- -- :.- -:- 1 -:.-:- -- -:|.--
1' -.-|-- - l- --l- -:|.-.l--
generic methods
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 545
Woif... fhof con'f be righf. If you con
foke o Iisf of AnimoI, why don'f you
jusf SAY fhof7 Whof's wrong wifh jusf
tukeThing{ArruyList-AnimuI> Iist}7
Hcrcs whcrc | ! ]c!s wc|r4...
This:
public <T extends Animal> void takeThing(ArrayList<T> list)
Is NOT the some os this:
public void takeThing(ArrayList<Animal> list)
Boih aic lcgal, lui ihcy`ic J.e.er!
Thc hisi onc, whcic <T cxtcnds Animal> is aii ol ihc mcihou
ucclaiaiion, mcans ihai any AiiayIisi ucclaicu ol a iyc ihai is
Animal, oi onc ol Animal`s suliycs liIc Dog oi Cai), is lcgal.
So you coulu invoIc ihc io mcihou using an AiiayIisiDog>,
AiiayIisiCai>, oi AiiayIisiAnimal>.
Bui... ihc onc on ihc loiiom, whcic ihc mcihou aigumcni is
AiiayIisiAnimal> lisi) mcans ihai orI, an AiiayIisiAnimal>
is lcgal. In oihci woius, whilc ihc hisi vcision iaIcs an AiiayIisi
ol any iyc ihai is a iyc ol Animal Animal, Dog, Cai, cic.),
ihc scconu vcision iaIcs orI, an AiiayIisi ol iyc Animal. Noi
AiiayIisiDog>, oi AiiayIisiCai> lui only AiiayIisiAnimal>.
Anu ycs, ii uocs acai io violaic ihc oini ol olymoihism.
lui ii will lccomc clcai whcn wc icvisii ihis in uciail ai ihc cnu
ol ihc chaici. Ioi now, icmcmlci ihai wc`ic only looIing ai
ihis lccausc wc`ic siill iiying io hguic oui how io soii) ihai
SongIisi, anu ihai lcu us inio looIing ai ihc API loi ihc soii)
mcihou, which hau ihis siiangc gcnciic iyc ucclaiaiion.
For now, oII you need to hnow is thot the syntox o[ the top version
is IegoI, ond thot it meons you con poss in o ArroyList object
instontioted os AnimoI or ony AnimoI subtype.
Anu now lacI io oui soii) mcihou...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
546 chapter 16
import java.util.*;
import java.io.*;
public class Jukebox3 {
ArrayList<Song> songList = new ArrayList<Song>();
public static void main(String[] args) {
new Jukebox3().go();
}
public void go() {
getSongs();
System.out.println(songList);
Collections.sort(songList);
System.out.println(songList);
}
void getSongs() {
try {
File hle = new File(SongList.txt);
BufferedReader reader = new BufferedReader(new FileReader(hle));
String line = null;
while ((line= reader.readLine()) != null) {
addSong(line);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
void addSong(String lineToParse) {
String[] tokens = lineToParse.split(/);
Song nextSong = new Song(tokens[0], tokens[1], tokens[2], tokens[3]);
songList.add(nextSong);
}
}
This sfiII doesn'f
expIoin why fhe sorf mefhod
foiIed on on ArroyLisf of Songs
buf worked for on ArroyLisf of
Sfrings...
Remember where we were...
1: : ---- l --.:' |l ---- -- ---
.::- - .- A--.]|:ll--, -l .: :--- .: --
l-- l- :--l .- A--.]|:l--, l .|-
File Edit Window Help Bummer
%javac Jukebox3.java
Jukebox3.java:15: cannot nd symbol
symbol : method sort(java.util.ArrayList<Song>)
location: class java.util.Collections
Collections.sort(songList);
^
1 error
sorting a Song
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 547
public static <T extends Comparable<? super T>> void sort(List<T> list)
The sort{} method can take only lists
of Comparable ob]ects.
8ong is NOT a subtype of
Comparable, so you cannot sort{}
the list of 8ongs.
At least not yet...
1: :.]: w.l--- '1' : --:l
- - l]- c--.-.|-'
||---- l: .-l -- --- B-l
]-- :.-'l, l -:l --.-:
l.l l- l]- .-.--l-- --
c--.-.|- --:l - - l]- 1
-- --- - 1': :---l]-:`
/-- :.- .:: - --|] . |:l |--
:-l]- - |:l, |- A--.]|:l`
l.l -:-: . .-.--l---- l]-
l.l -l--: c--.-.|-'
So hcic wc aic, iiying io icau ihc soii) mcihou uocs io h nu
oui why ii was OK io soii a lisi ol Siiings, lui noi a
lisi ol Song ol|ccis. Anu ii looIs liIc ihc answci is...
Kcv|s| !|n] !hc ser!| I mc!he4
Um... I jusf checked fhe docs for
Sfring, ond Sfring doesn'f EXTEMD
ComporobIe--if IMPLEMEMTS if.
CompurubIe is un interfuce. So if's nonsense
fo soy T etends ComporobIe.
public nal class String extends Object implements Serializable,
Comparable<String>, CharSequence
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
548 chapter 16
Thc ]ava cnginccis hau io givc you a way io ui a consiiaini
on a aiamciciizcu iyc, so ihai you can icsiiici ii io, say, only
sulclasscs ol Animal. Bui you also nccu io consiiain a iyc io
allow only classcs ihai imlcmcni a aiiiculai inicilacc. So
hcic`s a siiuaiion whcic wc nccu onc Iinu ol syniax io woiI
loi loih siiuaiions-inhciiiancc anu imlcmcniaiion. In oihci
woius, ihai woiIs loi loih e:erJ anu .Ieer.
Anu ihc winning woiu was... e:erJ. Bui ii ically mcans is-a",
anu woiIs icgaiulcss ol whcihci ihc iyc on ihc iighi is an
inicilacc oi a class.
|n ]cncr|rs, cr!cn4s mczns
cr!cn4s er |mp|cmcn!s
public static <T extends Comparable<? super T>> void sort(List<T> list)
c--.-.|- : .- -l--.:-, :- l:
!A||/ --.:, 1 --:l - . l]- l.l
-|----l: l- c--.-.|- -l--.:-'
|l --:-'l -.ll-- --l-- l- l- -- l- -l :
. :|.:: -- -l--.:- ]-- :l|| :.] -l--:'
]n gnje,, ([ [yw]
y(n], z]]y zn, j,-z,
zn] w[, | @0[q e]z,,,
zn] jn(|ze,.

Why didn't they just make a new keyword,"is"!



Adding a new keyword to the language is a PLALL big deal because
it risks breaking 1ava code you wrote in an earlier version. Think about
ityou might be using a variable "is (which we do use in this book to repre-
sent input streams). And since you're not allowed to use keywords as identi-
fiers in your code, that means any earlier code that used the keyword oelote
it was a reserved word, would break. So whenever there's a chance for the
Sun engineers to reuse an existing keyword, as they did here with "extends,
they'll usually choose that. 8ut sometimes they don't have a choice...
A few (very few) new keywords hove been added to the language, such
as in 1ava l.4 and in 1ava 5.0 (we look at enum in the appen-
dix). And this does break people's code, however you sometimes have the
option of compiling and running a newet version of 1ava so that it behaves
as though it were an older one. ou do this by passing a special flag to the
compiler or 1vM at the command-line, that says, "eah, yeah, | KNOw this is
1ava l.4, but please pretend it's really l.3, because |'m using a variable in my
code named ossett that | wrote back when you guys said it would OK!#$%.
( To see if you have a flag available, type jovoc (for the compiler) or jovo (for
the 1vM) at the command-line, without anything else after it, and you should
see a list of available options. ou'll learn more about these flags in the chap-
ter on deployment.)
the sort() method
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 549
I|nz||y wc knew whz!s wren]...
Ihc 8en] r|zss ncc4s !e |mp|cmcn! 0empzrz||c
Wc can ass ihc AiiayIisiSong> io ihc soii) mcihou only il ihc
Song class imlcmcnis Comaiallc, sincc ihai`s ihc way ihc soii)
mcihou was ucclaicu. A quicI chccI ol ihc API uocs shows ihc
Comaiallc inicilacc is ically simlc, wiih only onc mcihou io
imlcmcni:
public interface Comparable<T> {
int compareTo(T o);
}
java.|ang.6omparab|e
Anu ihc mcihou uocumcniaiion loi comaicTo) says
The big question is: what
makes one song less than,
equal to, or greater than
another song?
You can't implement the
Comparable interface until you
make that decision.
Returns:
a negative integer, zero, or a
positive integer as this object
is less than, equal to, or greater
than the speci ed object.
Ii looIs liIc ihc comaicTo) mcihou will lc callcu on onc
Song ol|cci, assing ihai Song a iclcicncc io a uillcicni
Song. Thc Song iunning ihc comaicTo) mcihou has io
hguic oui il ihc Song ii was asscu shoulu lc soiicu highci,
lowci, oi ihc samc in ihc lisi.
Youi lig |ol now is io ucciuc whai maIcs onc song gicaici
ihan anoihci, anu ihcn imlcmcni ihc comaicTo) mcihou
io icucci ihai. A ncgaiivc numlci any ncgaiivc numlci)
mcans ihc Song you wcic asscu is gicaici ihan ihc Song
iunning ihc mcihou. Rciuining a osiiivc numlci says
ihai ihc Song iunning ihc mcihou is gicaici ihan ihc Song
asscu io ihc comaicTo) mcihou. Rciuining zcio mcans
ihc Songs aic cqual ai lcasi loi ihc uiosc ol soiiing... ii
uocsn`i ncccssaiily mcan ihcy`ic ihc samc ol|cci). You mighi,
loi cxamlc, havc iwo Songs wiih ihc samc iiilc.
Which liings u a wholc uillcicni can ol woims wc`ll looI
ai laici...)
+,-+ :+ ,-+:.|
write in your idea and pseudo code (or
better, PLAL code) for implementing the
compareTo() method in a way that will
sort() the Song ob|ects by title.
Hint: if you're on the right track, it should
take less than 3 lines of code!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
550 chapter 16
Ihc ncw, |mprevc4, rempzrz||c 8en] r|zss
Wc ucciucu wc wani io soii ly iiilc, so wc imlcmcni ihc comaicTo)
mcihou io comaic ihc iiilc ol ihc Song asscu io ihc mcihou againsi
ihc iiilc ol ihc song on which ihc comaicTo) mcihou was invoIcu.
In oihci woius, ihc song iunning ihc mcihou has io ucciuc how iis
iiilc comaics io ihc iiilc ol ihc mcihou aiamcici.
Hmmm... wc Inow ihai ihc Siiing class musi Inow aloui alhalciical
oiuci, lccausc ihc soii) mcihou woiIcu on a lisi ol Siiings. Wc Inow
Siiing has a comaicTo) mcihou, so why noi |usi call ii. Thai way, wc
can simly lci onc iiilc Siiing comaic iiscll io anoihci, anu wc uon`i
havc io wiiic ihc comaiing/alhalciizing algoiiihm!
class Song implements Comparable<Song> {
String title;
String artist;
String rating;
String bpm;

public int compareTo(Song s) {
return title.compareTo(s.getTitle());
}
Song(String t, String a, String r, String b) {
title = t;
artist = a;
rating = r;
bpm = b;
}
public String getTitle() {
return title;
}
public String getArtist() {
return artist;
}
public String getRating() {
return rating;
}
public String getBpm() {
return bpm;
}

public String toString() {
return title;
}
}
c:-.||] l-:- -.l:--'-- :-:]- l- l]- l.l
l- -|----l- :|.:: :.- - :--.-- ..-:l
1: --.-: l.l -- --:l: :.- - :--.-- l-
-l-- -- --:l:, -- l- ---:- - :--l-
-|-' w- -:l .:: l- ---
-- l- l- ll|- l-- --:l:,
:-:- -- --- l--: .- .
:--.--1-|` --l-
1- :--l|` --l- :--: . -- l- :--.--1-|`
l- :-- -- l.l -- :--.--: l- l- -- --
-: l- --l- -.: ---
File Edit Window Help Ambient
%java Jukebox3
[Pink Moon, Somersault, Shiva Moon, Circles, Deep
Channel, Passenger, Listen]
[Circles, Deep Channel, Listen, Passenger, Pink
Moon, Shiva Moon, Somersault]
1: l-- l ---- |l --l: l- |:l, l-- :.||: :--l
-: -l: l- --: - .|.-l:.| ---- ] ll|-
the ComparabIe interface
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 551
Wc rzn ser! !hc ||s!, |e!...
Look at the Collections class AP again. There's a
second sort{} method-and it takes a Comparator.
Thcic`s a ncw iollcm-Iou wanis iwo uillcicni vicws ol ihc song lisi,
onc ly song iiilc anu onc ly aiiisi!
Bui whcn you maIc a collcciion clcmcni comaiallc ly having ii
imlcmcni Comaiallc), you gci only onc chancc io imlcmcni ihc
comaicTo) mcihou. So whai can you uo.
Thc hoiiillc way woulu lc io usc a uag vaiiallc in ihc Song class,
anu ihcn uo an icsi in comaicTo) anu givc a uillcicni icsuli
uccnuing on whcihci ihc uag is sci io usc iiilc oi aiiisi loi ihc
comaiison.
Bui ihai`s an awlul anu liiiilc soluiion, anu ihcic`s somcihing much
lciici. Somcihing luili inio ihc API loi |usi ihis uiosc-whcn you
wani io soii ihc samc ihing in moic ihan onc way.
1- :--l|` --l- : ---|-.- l-
l.- :---l- :.||- . c--.-.l--
N-l- l- :-| --- --l -- l-
-l /-.- . c--.-.l-- l.l :.-
:--.-- .- ---- l- :--: ]
.-l:l -:l-. - ll|-
Thof's nof good enough.
Somefimes I wonf if fo sorf
by orfisf insfeod of fifIe.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
552 chapter 16
0s|n] z res!em 0empzrz!er
An clcmcni in a lisi can comaic io anoihci ol
iis own iyc in only onc way, using iis comaicTo)
mcihou. Bui a Comaiaioi is cxicinal io ihc clcmcni
iyc you`ic comaiing-ii`s a scaiaic class. So you can
maIc as many ol ihcsc as you liIc! Wani io comaic
songs ly aiiisi. MaIc an AiiisiComaiaioi. Soii ly lcais
ci minuic. MaIc a BPMComaiaioi.
Thcn all you nccu io uo is call ihc ovciloaucu soii)
mcihou ihai iaIcs ihc Iisi anu ihc Comaiaioi ihai will
hcl ihc soii) mcihou ui ihings in oiuci.
Thc soii) mcihou ihai iaIcs a Comaiaioi will usc ihc
Comaiaioi insicau ol ihc clcmcni`s own comaicTo)
mcihou, whcn ii uis ihc clcmcnis in oiuci. In oihci
woius, il youi soii) mcihou gcis a Comaiaioi, ii won`i
cvcn ihc comaicTo) mcihou ol ihc clcmcnis
in ihc lisi. Thc soii) mcihou will insicau invoIc ihc
comparc() mcihou on ihc Comaiaioi.
So, ihc iulcs aic:
public interface Comparator<T> {
int compare(T o1, T o2);
}
java.ut||.6omparator
]| ya z,, z (zz( ( ([
,(() ([], ([ ,( ] j,
](jn] y ([ (zz(
z([ ([zn ([ ]n(', wn
ez[() ([].
|nvok|ng the one-argument sort(L|st o} method
means the ||st e|ement's compareTo(} method
determ|nes the order. 8o the e|ements |n the ||st
HU8T |mp|ement the 6omparab|e |nterface.
|nvok|ng sort(L|st o, 6omparator c} means the
||st e|ement's compareTo(} method w||| N0T be
ca||ed, and the 6omparator's compare(} method
w||| be used |nstead. That means the e|ements
|n the ||st do N0T need to |mp|ement the
6omparab|e |nterface.

So does this mean that if you have a cIass that


doesn't impIement ComparabIe, and you don't have the
source code, you couId stiII put the things in order by
creating a Comparator!

That's right. The other option (if it's possible) would be
to subclass the element and make the subclass implement
Comparable.

ut why doesn't cIass impIement ComparabIe!



Do you really believe that evetyth|n can be orderedI
|f you have element types that |ust don't lend themselves to
any kind of natural ordering, then you'd be misleading other
programmers if you implement Comparable. And you aren't
taking a huge risk by not implementing Comparable, since
a programmer can compare anything in any way that he
chooses using his own custom Comparator.

the Comparator interface


Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 553
import java.util.*;
import java.io.*;
public class Jukebox5 {
ArrayList<Song> songList = new ArrayList<Song>();
public static void main(String[] args) {
new Jukebox5().go();
}
class ArtistCompare implements Comparator<Song> {
public int compare(Song one, Song two) {
return one.getArtist().compareTo(two.getArtist());
}
}

public void go() {
getSongs();
System.out.println(songList);
Collections.sort(songList);
System.out.println(songList);
ArtistCompare artistCompare = new ArtistCompare();
Collections.sort(songList, artistCompare);
System.out.println(songList);
}

void getSongs() {
// I/O code here
}

void addSong(String lineToParse) {
// parse line and add to song list
}
}
c--.l- . --- ---- :|.:: l.l -|----l:
c--.-.l-- |--l- l.l l: l]-
.-.--l-- -.l:-: l- l]- --'-- --
l- :--.---- l: :.:- -- --:l:`
0p4z!|n] !hc 1ekc|er !e esc z 0empzrz!er
Wc uiu ihicc ncw ihings in ihis couc:
1) Cicaicu an innci class ihai imlcmcnis Comaiaioi anu ihus ihc compore);
mcihou ihai uocs ihc woiI icviously uonc ly comporeTo);).
2) Mauc an insiancc ol ihc Comaiaioi innci class.
S) Callcu ihc ovciloaucu soii) mcihou, giving ii loih ihc song lisi anu ihc
insiancc ol ihc Comaiaioi innci class.
Noic: wc also uuaicu ihc Song class ioSiiing) mcihou io iini loih ihc song
iiilc anu ihc aiiisi. Ii iinis titIe: ortist icgaiulcss ol how ihc lisi is soiicu.)
w-'-- |-ll- l- l-- .-.|-: |-- .-l:l`
- l- .:l-.| :--.-:--, :-:- l--: .|--.]
--- -- l- .|.-l-- l--:-|-:
M.- .- -:l.-:- - l-
c--.-.l-- ---- :|.::
|--- :--l|`, .::- l l- |:l
.- . ------:- l- l- ---
:-:l-- c--.-.l-- --:l
Note: we've made sort-by-title the default sort, by
keeping the compareTo() method in Song use the
titles. 8ut another way to design this would be to
implement both the title sorting and artist sorting as
inner Comparator classes, and not have Song implement
Comparable at all. That means we'd always use the two-
arg version of Collections.sort().
1: -:---: . l-- |l- .-l:l`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
554 chapter 16
geve;ze ]gjee;
j,,a ([j, e] yj,(, jn
z ,jng] |j]. (a j j,
( |j]] jn ([ ]zn[, , ([
([ gz wj]] ez( ([
a(a( ,[wn.
import __________________,
public class SortMountains {
LinkedList______________ mtn = new LinkedList____________{|,
class NameCompare ___________________________________ {
public int compare{Mountain one, Mountain two| {
return ___________________________,
}
}
class HeightCompare _______________________________ {
public int compare{Mountain one, Mountain two| {
return {__________________________|,
}
}
public static void main{String args| {
new SortMountain{|.go{|,
}
public void go{| {
mtn.add{new Mountain{"Longs", l4255||,
mtn.add{new Mountain{"Elbert", l4433||,
mtn.add{new Mountain{"Maroon", l4l56||,
mtn.add{new Mountain{"Castle", l4265||,
System.out.println{"as entered:\n" + mtn|,
NameCompare nc = new NameCompare{|,
_________________________________,
System.out.println{"by name:\n" + mtn|,
HeightCompare hc = new HeightCompare{|,
_________________________________,
System.out.println{"by height:\n" + mtn|,
}
}
class Mountain {
__________________,
_________________,
______________________ {
_________________,
_________________,
}
_________________________ {
______________________________,
}
}
File Edit Window Help ThisOne'sForBob
%java SortMountains
as entered:
[Longs 14255, Elbert 14433, Maroon 14156, Castle 14265]
by name:
[Castle 14265, Elbert 14433, Longs 14255, Maroon 14156]
by height:
[Elbert 14433, Castle 14265, Longs 14255, Maroon 14156]

+,-+ :+ ,-+:.|
coIIections exercise
Note: answers are at the end of
the chapter.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 555
Por each of the questions below, fill in the blank
with one of the words from the "possible answers
list, to correctly answer the question. Answers are
at the end of the chapter.
Givcn ihc lollowing comilallc siaicmcni:
Collections.sort(myArrayList);
1. Whai musi ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni. ________________
2. Whai mcihou musi ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni. ________________
S. Can ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni loih
Comparator AND Comparable. ________________
Givcn ihc lollowing comilallc siaicmcni:
Collections.sort(myArrayList, myCompare);
4. Can ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni Comparable. ________________
. Can ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni Comparator. ________________
6. Musi ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni Comparable. ________________
7. Musi ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni Comparator. ________________
S. Whai musi ihc class ol ihc myCompare ol|cci imlcmcni. ________________
9. Whai mcihou musi ihc class ol ihc myCompare ol|cci imlcmcni. __________________
Possible Answers:
6omparator,
6omparab|e,
compareTo( },
compare( },
yes,
no
]j||-j-ge-|z
+,-+ :+ ,-+:.|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
556 chapter 16
0h-eh. Ihc ser!|n] z|| werks, |e! new wc hzvc 4ep||rz!cs...
Thc soiiing woiIs gicai, now wc Inow how io soii on loih using ihc Song ol|cci`s
comaicTo) mcihou) anu using ihc Comaiaioi`s comaic) mcihou). Bui ihcic`s
a ncw iollcm wc uiun`i noiicc wiih a icsi samlc ol ihc |uIclox icxi hlc-the sorted Iist
contoins dupIicotes.
Ii acais ihai ihc uinci |uIclox |usi Iccs wiiiing io ihc hlc icgaiulcss ol whcihci ihc
samc song has alicauy lccn laycu anu ihus wiiiicn) io ihc icxi hlc. Thc SongIisiMoic.ixi
|uIclox icxi hlc is a comlcic iccoiu ol cvciy song ihai was laycu, anu mighi coniain ihc
samc song muliilc iimcs.
File Edit Window Help TooManyNotes
%java Jukebox4
[Pink Moon: Nick Drake, Somersault: Zero 7, Shiva Moon: Prem
Joshua, Circles: BT, Deep Channel: Afro Celts, Passenger:
Headmix, Listen: Tahiti 80, Listen: Tahiti 80, Listen: Tahiti
80, Circles: BT]
[Circles: BT, Circles: BT, Deep Channel: Afro Celts, Listen:
Tahiti 80, Listen: Tahiti 80, Listen: Tahiti 80, Passenger:
Headmix, Pink Moon: Nick Drake, Shiva Moon: Prem Joshua,
Somersault: Zero 7]
[Deep Channel: Afro Celts, Circles: BT, Circles: BT, Passenger:
Headmix, Pink Moon: Nick Drake, Shiva Moon: Prem Joshua, Listen:
Tahiti 80, Listen: Tahiti 80, Listen: Tahiti 80, Somersault:
Zero 7]
B---- :--l-
SongListMore,tt
Pink Moon/Nick Drake/5/80
Somersault/Zero 7/4/84
Shiva Moon/Prem Joshua/6/120
Circles/BT/5/110
Deep Channel/Afro Celts/4/120
Passenger/Headmix/4/100
Listen/Tahiti 80/5/90
Listen/Tahiti 80/5/90
Listen/Tahiti 80/5/90
Circles/BT/5/110
1- --|:lM--- l-l |- --- .: -|:.l-: -
l, -:.-:- l- --- -.:-- : --l- ---] :--
|.]-, - ---- ----] -:- l- |.] |:l--'
l--- l--: - . ---, -||--- ] c-:|-:', . :--
l.l . --- |.]- -.-|--
w- :.-'l :.-- l- -.] l- l-l |- : --ll--
-:.-:- :---l--: --'-- -- l- --- .|| l.l
----.l-- w- .- l- :.-- l- .. :--
Al-- :--l- -:-
l- --': ---
:--.--1-|` --l-
|:--l ] ll|-`
Al-- :--l- -:-
l- A-l:lc--.--
c--.-.l-- |:--l ]
.-l:l -.--`
deaIing with dupIicates
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 557

L8T - when sequence matters


Co||ecl|ors l|al |roW aooul index osition.
L|sls |roW W|ere sorel||r |s |r l|e ||sl. You
car |ave rore l|ar ore e|ererl relererc|r
l|e sare oojecl.
8ET - when uniqueness matters
Co||ecl|ors l|al do not ellow dulicetes.
3els |roW W|el|er sorel||r |s a|ready |r l|e co||ecl|or.
You car rever |ave rore l|ar ore e|ererl relererc|r
l|e sare oojecl (or rore l|ar ore e|ererl relererc|r
lWo oojecls l|al are cors|dered equa|We'|| |oo| al W|al
oojecl equa||ly rears |r a rorerl).
MAP - when finding something by key matters
Co||ecl|ors l|al use key-velue eirs.
Vaps |roW l|e va|ue assoc|aled W|l| a |ver |ey. You
car |ave lWo |eys l|al relererce l|e sare va|ue, oul you
carrol |ave dup||cale |eys. A|l|ou| |eys are lyp|ca||y
3lr|r rares (so l|al you car ra|e rare/va|ue properly
||sls, lor exarp|e), a |ey car oe ary oojecl.
l-|:.l-: 6r
0 1 2 3
List
N6 -|:.l-:
8et
Map
Ball Fish Car
l-|:.l- .|--: 6r, -l N6 -|:.l- -]:
Ball1 Ball2 Fish Car

Iiom ihc Collcciion API, wc hnu ihicc main inicilaccs, List, Sct, anu
Map. AiiayIisi is a List, lui ii looIs liIc is cxacily whai wc nccu.
Wc ncc4 z 8c! |ns!cz4 ef z I|s!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
the coIIections API
558 chapter 16
hash8et
3et
extends
implements
implementation class
interface

Collection
[interfece}
3et
[interfece}
List
[interfece}
3orted3et
[interfece}
Ye
[interfece}
3ortedYe
[interfece}
L|nkedL|st Vector
Tree8et L|nkedhash8et hash8et ArrayL|st
TreeHap hashtab|e L|nkedhashHap hashHap
Ihc 0e||cr!|en || |pzr! ef | !I
Noiicc ihai ihc Ma inicilacc uocsn`i
aciually cxicnu ihc Collcciion inicilacc,
lui Ma is siill consiucicu aii ol ihc
Collcciion IiamcwoiI" also Inown
as ihc Collcciion API"). So Mas aic
siill collcciions, cvcn ihough ihcy uon`i
incluuc |ava.uiil.Collcciion in ihcii
inhciiiancc iicc.
Noic: ihis is noi ihc comlcic
collcciion API, ihcic aic oihci
classcs anu inicilaccs, lui
ihcsc aic ihc oncs wc caic
mosi aloui.)
M.: --'l -l-- ---
..-l|c-||-:l--, -l
l-]'-- :l|| :--:---
l- - .-l - l-
:-||-:l--: -.-----'
- ).. - . M. :
:l|| ------ l- .: .
:-||-:l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 559
Wc auucu on io ihc ]uIclox io ui ihc songs in a HashSci. Noic: wc lcli oui somc
ol ihc ]uIclox couc, lui you can coy ii liom cailici vcisions. Anu io maIc ii casici
io icau ihc ouiui, wc wcni lacI io ihc cailici vcision ol ihc Song`s ioSiiing)
mcihou, so ihai ii iinis only ihc iiilc insicau ol iiilc aiiisi.)
0s|n] z Hzsh8c! |ns!cz4 ef rrzyI|s!
import java.util.*;
import java.io.*;
public class Jukebox6 {
ArrayList<Song> songList = new ArrayList<Song>();
// main method etc.

public void go() {
getSongs();
System.out.println(songList);
Collections.sort(songList);
System.out.println(songList);
HashSet<Song> songSet = new HashSet<Song>();
songSet.addAll(songList);
System.out.println(songSet);
}
// getSongs() and addSong() methods
}
File Edit Window Help GetBetterMusic
%java Jukebox6
[Pink Moon, Somersault, Shiva Moon, Circles, Deep Channel,
Passenger, Listen, Listen, Listen, Circles]
[Circles, Circles, Deep Channel, Listen, Listen, Listen,
Passenger, Pink Moon, Shiva Moon, Somersault]
[Pink Moon, Listen, Shiva Moon, Circles, Listen, Deep Channel,
Passenger, Circles, Listen, Somersault]
+--- -- :--.l- . --- +.:-l
.-.--l---- l- -| --:
w- -'l :.-- -l--:|`, :- l :l|| -l: l- :--: - .- A--.]|:l
+.:-l .: . :-|- .A|||` --l- l.l :.-
l.- .--l-- :-||-:l-- .- -:- l l- --|.l-
l- +.:-l |l': l- :.-- .: -- .- -.:
:-- --- .l . l-- |-:-l --: :-|--`
1- -l -'l -|''
w- :l|| .- .|| l- -|:.l-: '
B---- :--l-
l- A--.]|:l
Al-- :--l-
l- A--.]|:l
|] ll|-`
Al-- -ll- l
-l- . +.:-l,
.- --l- l-
+.:-l |-- -'l
:.|| :--l|` ..-`
|A- l |-:l l: :--l ----
--- -- -l l- |:l -l- .
+.:-l, -l --'|| ----] .--l
l.l --- |.l--`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
560 chapter 16
Whz! mzkcs ! we e|jcr!s cez| !
Iiisi, wc havc io asI-whai maIcs iwo Song iclcicnccs
uulicaics. Thcy musi lc consiucicu . Is ii simly iwo
iclcicnccs io ihc vciy samc ol|cci, oi is ii iwo scaiaic ol|ccis
ihai loih havc ihc samc .Ie.
This liings u a Icy issuc: .ee.ere cqualiiy vs. obe cqualiiy.

Reference equality
Two references, one object on the heap.

t|t|e: 6|rc|es
hash6ode: 254

Ob]ect equality
Two references, two objects on the heap, but
the objects are cons|dered meeningfully equivelent.

TWo relererces l|al reler lo l|e sare oojecl or


l|e |eap are equa|. Per|od. ll you ca|| l|e hash6ode(} rel|od or
ool| relererces, you'|| el l|e sare resu|l. ll you dor'l overr|de l|e
|as|Code() rel|od, l|e delau|l oe|av|or (rereroer, you |r|er|led
l||s lror c|ass 0ojecl) |s l|al eac| oojecl W||| el a ur|que ruroer
(rosl vers|ors ol Java ass|r a |as|code oased or l|e oojecl's
rerory address or l|e |eap, so ro lWo oojecls W||| |ave l|e sare
|as|code).
ll you Warl lo |roW |l lWo relerenoes are rea||y relerr|r lo l|e sare
oojecl, use l|e == operalor, W||c| (rereroer) corpares l|e o|ls |r
l|e var|ao|es. ll ool| relererces po|rl lo l|e sare oojecl, l|e o|ls W|||
oe |derl|ca|.
t|t|e: 6|rc|es
hash6ode: 254
t|t|e: 6|rc|es
hash6ode: 254

ll you Warl lo lreal lWo d|llererl 3or oojecls as equa| (lor


exarp|e |l you dec|ded l|al lWo 3ors are l|e sare |l l|ey |ave
ralc||r r|r|e var|ao|es), you rusl overr|de oorn l|e hash6ode(}
ard equa|s(} rel|ods |r|er|led lror c|ass 0ojecl.
As We sa|d aoove, |l you oonr overr|de |as|Code(), l|e delau|l
oe|av|or (lror 0ojecl) |s lo |ve eac| oojecl a ur|que |as|code
va|ue. 3o you rusl overr|de |as|Code() lo oe sure l|al lWo
equ|va|erl oojecls relurr l|e sare |as|code. 8ul you rusl a|so
overr|de equa|s() so l|al |l you ca|| |l or e|rner oojecl, pass|r |r
l|e ol|er oojecl, a|Ways relurrs true.
f two ob]ects foo and bar are
equal, foo.equals{bar} must be
true, and both foo and bar must
return the same value from
hashCode{}. For a 8et to treat
two ob]ects as duplicates, you
must override the hashCode{}
and equals{} methods inherited
from class Ob]ect, so that you
can make two different ob]ects
be viewed as equal.
if {foo == bar| {
// both references are referring
// to the same obect on the heap
}
if {foo.eguals{bar} && foo.hashCode{} == bar.hashCode{}| {
// both references are referring to either a
// a single obect, or to two obects that are equal
}
object equaIity
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 561
t|t|e: 6|rc|es
hash6ode: 742
t|t|e: 6|rc|es
hash6ode: 742
Hew z Hzsh8c! rhcrks fer 4ep||rz!cs: hzsh0e4c| I zn4 cez|s| I
Whcn you ui an ol|cci inio a Hashsci, ii uscs ihc
ol|cci`s hashcouc valuc io uciciminc whcic io ui
ihc ol|cci in ihc Sci. Bui ii also comaics ihc ol|cci`s
hashcouc io ihc hashcouc ol all ihc oihci ol|ccis in
ihc HashSci, anu il ihcic`s no maiching hashcouc,
ihc HashSci assumcs ihai ihis ncw ol|cci is noi a
uulicaic.
In oihci woius, il ihc hashcoucs aic uillcicni, ihc
HashSci assumcs ihcic`s no way ihc ol|ccis can lc
cqual!
So you musi ovciiiuc hashCouc) io maIc suic ihc
ol|ccis havc ihc samc valuc.
Bui iwo ol|ccis wiih ihc samc hashCouc) mighi ro
lc cqual moic on ihis on ihc ncxi agc), so il ihc
HashSci hnus a maiching hashcouc loi iwo ol|ccis-
onc you`ic insciiing anu onc alicauy in ihc sci-ihc
HashSci will ihcn call onc ol ihc ol|cci`s cquals)
mcihous io scc il ihcsc hashcouc-maichcu ol|ccis
ically n.e cqual.
Anu il ihcy`ic cqual, ihc HashSci Inows ihai ihc
ol|cci you`ic aiicmiing io auu is a uulicaic ol
somcihing in ihc Sci, so ihc auu uocsn`i hacn.
You uon`i gci an cxcciion, lui ihc HashSci`s auu)
mcihou iciuins a loolcan io icll you il you caic)
whcihci ihc ncw ol|cci was auucu. So il ihc auu)
mcihou iciuins nIe, you Inow ihc ncw ol|cci was a
uulicaic ol somcihing alicauy in ihc sci.
hash8et
I need fo know
if your hoshcode
voIues ore fhe some.
6-:l ]--'-- l-]- l-
. l- l- +.:-l
6-:l .|--.] |N
l- +.:-l
Song

Song

hash6ode(}
7
4
2
hash6ode(}
742
t|t|e: 6|rc|es
hash6ode: 742
t|t|e: 6|rc|es
hash6ode: 742
hash8et
Your hoshcodes
ore fhe some, buf ore
you PEALLY equoI7
6-:l ]--'-- l-]-
l- . ---: l: --.|:|`
--l-, :--.-- l:-|
l- .-, .- --l---: l---
6-:l .|--.] |N
l- +.:-l
Song

Song

equa|s( bar }
tru
e
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
562 chapter 16
Ihc 8en] r|zss w| !h evcrr|44cn
hzsh0e4c|I zn4 cez|s|I
class Song implements Comparable<Song>{
String title;
String artist;
String rating;
String bpm;
public boolean equals(Object aSong) {
Song s = (Song) aSong;
return getTitle().equals(s.getTitle());
}
public int hashCode() {
return title.hashCode();
}

public int compareTo(Song s) {
return title.compareTo(s.getTitle());
}
Song(String t, String a, String r, String b) {
title = t;
artist = a;
rating = r;
bpm = b;
}
public String getTitle() {
return title;
}
public String getArtist() {
return artist;
}
public String getRating() {
return rating;
}
public String getBpm() {
return bpm;
}

public String toString() {
return title;
}
}
1- +.:-l |-- .-]--- -|:- :.||- l:
--l-` :--: l .--l-- --
1- 6!A1 ---: : l.l ll|- : . l--,
.- l--: .- .- ------ --.|:|`
--l- - .|| -- .- l- - : .: ---
ll|- l': --.| l- l- -l-- :--': ll|-
.-- -.| --- l- l-- :|.:: .: .- ------
.:c--|` --l-, :- ]-- :.- -:l --l--- l- --:-|l -
:.||- .:c--|` -- l- ll|- N-l:- -- .:c--|`
.- --.|:|` .-- -:- l- AM! -:l.-:- .-.|-
%java Jukebox6
[Pink Moon, Somersault, Shiva Moon, Circles,
Deep Channel, Passenger, Listen, Listen,
Listen, Circles]
[Circles, Circles, Deep Channel, Listen,
Listen, Listen, Passenger, Pink Moon, Shiva
Moon, Somersault]
[Pink Moon, Listen, Shiva Moon, Circles,
Deep Channel, Passenger, Somersault]
File Edit Window Help RebootWindows
N-- l ---:' N- -|:.l-: --- --
--l --l l- +.:-l B-l -- -'l
:.|| :--l|` ..-, .- --- -- -l
l- A--.]|:l -l- l- +.:-l, l-
+.:-l -'l --:--- l- :--l ----
overriding hashCode() and equaIs()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 563
Java Ob]ect Law For HashCode{}
and equals{}
The AP docs for class Ob]ect state the
rules you MU8T follow:

f two ob]ects are equal, they MU8T


have matching hashcodes.

f two ob]ects are equal, calling


equals{} on either ob]ect MU8T return
true. n other words, if {a.equals{b}} then
{b.equals{a}}.

f two ob]ects have the same hashcode


value, they are NOT required to be equal.
But if they're equal, they MU8T have the
same hashcode value.

8o, if you override equals{}, you MU8T


override hashCode{}.

The default behavior of hashCode{}


is to generate a unique integer for each
ob]ect on the heap. 8o if you don't override
hashCode{} in a class, no two ob]ects of
that type can EVER be considered equal.

The default behavior of equals{} is to


do an == comparison. n other words, to
test whether the two references refer to a
single ob]ect on the heap. 8o if you don't
override equals{} in a class, no two ob]ects
can EVER be considered equal since
references to two different ob]ects will
always contain a different bit pattern.
a.equals{b} must also mean that
a.hashCode{} == b.hashCode{}
But a.hashCode{} == b.hashCode{}
does NOT have to mean a.equals{b}
(-,- a,- |
oa|| qa--(:|-

How come hashcodes can be the same


even if objects aren't equaI!

HashSets use hashcodes to store the ele-
ments in a way that makes it much faster to access.
|f you try to find an ob|ect in an ArrayList by giving
the ArrayList a copy of the ob|ect (as opposed to
an index value), the ArrayList has to start searching
from the beginning, looking at each element in
the list to see if it matches. 8ut a HashSet can find
an ob|ect much more quickly, because it uses the
hashcode as a kind of label on the "bucket where
it stored the element. So if you say, "| want you
to find an ob|ect in the set that's exactly like this
one... the HashSet gets the hashcode value from
the copy of the Song you give it (say, 742), and
then the HashSet says, "Oh, | know exactly where
the ob|ect with hashcode #742 is stored..., and it
goes right to the #742 bucket.
This isn't the whole story you get in a computer
science class, but it's enough for you to use Hash-
Sets effectively. |n reality, developing a good hash-
code algorithm is the sub|ect of many a PhD thesis,
and more than we want to cover in this book.
The point is that hashcodes can be the same
without necessarily guaranteeing that the ob|ects
are equal, because the "hashing algorithm used in
the hashCode() method might happen to return
the same value for multiple ob|ects. And yes, that
means that multiple ob|ects would all land in the
same bucket in the HashSet (because each bucket
represents a single hashcode value), but that's not
the end of the world. |t might mean that the Hash-
Set is |ust a little less efficient (or that it's filled
with an extremely large number of elements), but
if the HashSet finds more than one ob|ect in the
same hashcode bucket, the HashSet will simply
use the equals() method to see if there's a perfect
match. |n other words, hashcode values are some-
times used to narrow down the search, but to find
the one exact match, the HashSet still has to take
all the ob|ects in that one bucket (the bucket for
all ob|ects with the same hashcode) and then call
equals() on them to see if the ob|ect it's looking for
is in that bucket.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
564 chapter 16
n4 |f wc wzn! !hc sc! !e s!zy
ser!c4, wcvc ]e! Ircc8c!
import java.util.*;
import java.io.*;
public class Jukebox8 {
ArrayList<Song> songList = new ArrayList<Song>();
int val;

public static void main(String[] args) {
new Jukebox8().go();
}

public void go() {
getSongs();
System.out.println(songList);
Collections.sort(songList);
System.out.println(songList);
TreeSet<Song> songSet = new TreeSet<Song>();
songSet.addAll(songList);
System.out.println(songSet);
}

void getSongs() {
try {
File hle = new File(SongListMore.txt);
BufferedReader reader = new BufferedReader(new FileReader(hle));
String line = null;
while ((line= reader.readLine()) != null) {
addSong(line);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
void addSong(String lineToParse) {
String[] tokens = lineToParse.split(/);
Song nextSong = new Song(tokens[0], tokens[1], tokens[2], tokens[3]);
songList.add(nextSong);
}
}
TiccSci is similai io HashSci in ihai ii icvcnis uulicaics. Bui ii also ihc lisi soiicu. Ii woiIs
|usi liIc ihc soii) mcihou in ihai il you maIc a TiccSci using ihc sci`s no-aig consiiucioi, ihc
TiccSci uscs cach ol|cci`s comaicTo) mcihou loi ihc soii. Bui you havc ihc oiion ol assing
a Comaiaioi io ihc TiccSci consiiucioi, io havc ihc TiccSci usc ihai insicau. Thc uownsiuc io
TiccSci is ihai il you uon`i soiiing, you`ic siill aying loi ii wiih a small ciloimancc hii. Bui
you`ll iolally hnu ihai ihc hii is almosi imossillc io noiicc loi mosi as.
|-:l.-l.l- . 1----l -:l-. - +.:-l
c.||- l- --~.- 1----l :--:l--:l--
--.-: l- :-l -|| -:- l- -- --:l':
:--.--1-|` --l- -- l- :--l
|w- :--| .- .::- - . c--.-.l--`
w- :.- . .|| l- :--: --- l- +.:-l
-:- .A|||` |6- -- :--| .- .- l-
:--: --.||] -:- :---l.|` -:l
l- -.] -- .- :--: l- l- A--.]|:l`
TreeSets and sorting
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 565
Whz! yee M08I knew z|ee! Ircc8c!...
import java.util.*;
public class TestTree {
public static void main (String[] args) {
new TestTree().go();
}
public void go() {
Book b1 = new Book(How Cats Work);
Book b2 = new Book(Remix your Body);
Book b3 = new Book(Finding Emo);

TreeSet<Book> tree = new TreeSet<Book>();
tree.add(b1);
tree.add(b2);
tree.add(b3);
System.out.println(tree);
}
}
class Book {
String title;
public Book(String t) {
title = t;
}
}
+,-+ :+ ,-+:.|
Look at this code.
Pead it carefully, then
answer the questions
below. (Note: there
are no syntax errors
in this code.)
l). what is the result when you compile this codeI
2). |f it compiles, what is the result when you run the TestTree classI
3). |f there is a problem (either compile-time or runtime) with this code, how would you fix itI
TiccSci looIs casy, lui maIc suic you ically unucisianu whai you nccu io
uo io usc ii. Wc ihoughi ii was so imoiiani ihai wc mauc ii an cxcicisc so
you`u Ln.e io ihinI aloui ii. Do NOT iuin ihc agc uniil you`vc uonc ihis.
Ve enr ..
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
566 chapter 16
Ircc8c! c|cmcn!s M08I |c rempzrz||c
TiccSci can`i icau ihc iogiammci`s minu io hguic oui how ihc
ol|cci`s shoulu lc soiicu. You havc io icll ihc TiccSci .
class Book implements Comparable {
String title;
public Book(String t) {
title = t;
}
public int compareTo(Object b) {
Book book = (Book) b;
return (title.compareTo(book.title));
}
}

The elements in
the list must be of a type that
implements Comparable
T|e 8oo| c|ass or l|e prev|ous
pae d|dr'l |rp|ererl Corparao|e, so |l
Wou|dr'l Wor| al rurl|re. T||r| aooul |l, l|e
poor Tree3el's so|e purpose |r ||le |s lo |eep
your e|ererls sorled, ard orce aa|r|l |ad
ro |dea |oW lo sorl 8oo| oojeclsl ll doesr'l la||
al corp||e-l|re, oecause l|e Tree3el add()
rel|od doesr'l la|e a Corparao|e lype,T|e
Tree3el add() rel|od la|es W|alever lype
you used W|er you crealed l|e Tree3el. lr
ol|er Words, |l you say reW Tree3el<8oo|>()
l|e add() rel|od |s esserl|a||y add(8oo|). Ard
l|ere's ro requ|rererl l|al l|e 8oo| c|ass
|rp|ererl Corparao|el 8ul |l la||s al rurl|re
W|er you add l|e secord e|ererl lo l|e sel.
T|al's l|e l|rsl l|re l|e sel lr|es lo ca|| ore ol
l|e oojecl's corpareTo() rel|ods ard... car'l.

You use the Tree8et's


overloaded constructor
that takes a Comparator
Tree3el Wor|s a |ol |||e l|e sorl()
rel|odyou |ave a c|o|ce ol us|r l|e
e|ererl's corpareTo() rel|od, assur|r
l|e e|ererl lype |rp|ererled l|e
Corparao|e |rlerlace, 0R you car use
a cuslor Corparalor l|al |roWs |oW
lo sorl l|e e|ererls |r l|e sel. To use a
cuslor Corparalor, you ca|| l|e Tree3el
corslruclor l|al la|es a Corparalor.
To use a Tree8et, one of these
things must be true:
OR
public class BookCompare implements Comparator<Book> {
public int compare(Book one, Book two) {
return (one.title.compareTo(two.title));
}
}
class Test {
public void go() {
Book b1 = new Book(How Cats Work);
Book b2 = new Book(Remix your Body);
Book b3 = new Book(Finding Emo);
BookCompare bCompare = new BookCompare();
TreeSet<Book> tree = new TreeSet<Book>(bCompare);
tree.add(new Book(How Cats Work);
tree.add(new Book(Finding Emo);
tree.add(new Book(Remix your Body);
System.out.println(tree);
}
}
how TreeSets sort
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 567
Wcvc sccn I|s!s zn4 8c!s, new wc|| esc z Mzp
Iisis anu Scis aic gicai, lui somciimcs a Ma is ihc lcsi collcciion noi Collcciion
wiih a caiial C"-icmcmlci ihai Mas aic aii ol ]ava collcciions lui ihcy uon`i
imlcmcni ihc Collcciion inicilacc).
Imaginc you wani a collcciion ihai acis liIc a iociiy lisi, whcic you givc ii a namc
anu ii givcs you lacI ihc valuc associaicu wiih ihai namc. Alihough Icys will olicn lc
Siiings, ihcy can lc any ]ava ol|cci oi, ihiough auioloxing, a iimiiivc).
import java.util.*;
public class TestMap {
public static void main(String[] args) {
HashMap<String, Integer> scores = new HashMap<String, Integer>();
scores.put(Kathy, 42);
scores.put(Bert, 343);
scores.put(Skyler, 420);
System.out.println(scores);
System.out.println(scores.get(Bert));
}
}
Map
Ball Fish Car Ball1 Ball2 Ball3 Ball4
Each element in a Map is actually
TWO ob]ects-a key and a value.
You can have duplicate values, but
NOT duplicate keys.
Map example
+.:M. ---: 1w6 l]- .-.--l--:-
--- -- l- -] .- --- -- l- .|--
c:- -l|` -:l-. - .|`, .- --- - :---:-
l l.-: l-- .-----l: |-], .|--`
%java TestMap
{Skyler=420, Bert=343, Kathy=42}
343
File Edit Window Help WhereAm
w-- ]-- --l . M., l -: ]-- l- -]=.|--,
- -.:-: ! -:l-. - l- -.:-l: | 1 ]-- :--
--- ]-- --l |:l: .- :-l:
.|--
-]
1- -l|` --l- l.-: . -], .-
--l---: l- .|-- |- l: :.:-, .- |-l---`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
568 chapter 16
I|nz||y, |zrk !e ]cncr|rs
Rcmcmlci cailici in ihc chaici wc ialIcu aloui how mcihous
ihai iaIc aigumcnis wiih gcnciic iycs can lc... . Anu wc
mcan wciiu in ihc olymoihic scnsc. Il ihings siaii io lccl
siiangc hcic, |usi Icc going-ii iaIcs a lcw agcs io ically icll
ihc wholc sioiy.
Wc`ll siaii wiih a icminuci on how aigumcnis woiI,
olymoihically, anu ihcn looI ai uoing ihc samc ihing wiih
gcnciic lisis. Thc couc lclow comilcs anu iuns wiihoui ciiois:
import java.util.*;
public class TestGenerics1 {
public static void main(String[] args) {
new TestGenerics1().go();
}
public void go() {
Animal[] animals = {new Dog(), new Cat(), new Dog()};
Dog[] dogs = {new Dog(), new Dog(), new Dog()};
takeAnimals(animals);
takeAnimals(dogs);
}
public void takeAnimals(Animal[] animals) {
for(Animal a: animals) {
a.eat();
}
}
}
abstract class Animal {
void eat() {
System.out.println(animal eating);
}
}
class Dog extends Animal {
void bark() { }
}
class Cat extends Animal {
void meow() { }
}

l-:|.-- .- :--.l- .- A--.| .--.],
l.l -|: -l -: .- :.l:
f a method argument is an array
of Animals, it will also take an
array of any Animal subtype.
n other words, if a method is
declared as:
void foo{Animal[j a} [ ]
Assuming Dog extends Animal,
you are free to call both:
foo{anAnimalArray};
foo{aDogArray};
l-:|.-- .- :--.l- . l- .--.],
l.l -|: --|] l-: |l- :--|--
---'l |-l ]-- -l . c.l -`
c.|| l.-A--.|:|`, -:- -l
.--.] l]-: .: .-----l:
1- :--:.| --l : l.l l- l.-A--.|:|`
--l- :.- l.- .- A--.||1 -- . l-|1, :-:-
l- |~A A--.| |-|]---:- - .:l--
------, -- :.- :.|| 6N|/ l- --l-: -:|.-- - l]- .--.|, :-:- l- .--.|: .-.--l-- : - l]- A--.| .--.], .- -- -'l - .-] :.:l- |w.l ---| -- :.:l l l- 1.l .--.] -l -| -l l-: .- c.l:`
1- :-|- A--.| :|.:: --.-:]
generic types
Here's how it works with regular arrays:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 569
0s|n] pe|ymerph|r zr]emcn!s zn4 ]cncr|rs
So wc saw how ihc wholc ihing woiIcu wiih aiiays, lui will ii woiI
ihc samc way whcn wc swiich liom an aiiay io an AiiayIisi. Sounus
icasonallc, uocsn`i ii.
Iiisi, lci`s iiy ii wiih only ihc Animal AiiayIisi. Wc mauc |usi a lcw
changcs io ihc go) mcihou:
public void go() {
ArrayList<Animal> animals = new ArrayList<Animal>();
animals.add(new Dog());
animals.add(new Cat());
animals.add(new Dog());
takeAnimals(animals);
}
public void takeAnimals(ArrayList<Animal> animals) {
for(Animal a: animals) {
a.eat();
}
}
A :-|- :.-- --- A--.||1 l-
A--.]|:lA--.|
w- .- l- . --- .l . l-- :-:- l---': --
:--l:-l :]-l. |- l--- : -- .--.] :--.l--
1: : l- :.-- :--, -:-l --- l- .--.|:'
.-.|- ----: l- .- A--.]|:l -:l-. - .--.]
1- --l- --- l.-: .- A--.]|:l
-:l-. - .- .--.], -l ---]l- -|:- :
l- :.-- ------, l.l -- |-- :]-l.
---: -- -l .--.]: .- :-||-:l--:
Passing in ]ust ArrayList<Animal>
%java TestGenerics2
animal eating
animal eating
animal eating
animal eating
animal eating
animal eating
File Edit Window Help CatFoodsBetter
Compiles and runs ]ust hne
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
570 chapter 16
Be! w||| | ! werk w| !h rrzyI|s!cPe]: !
Bccausc ol olymoihism, ihc comilci lci us ass a Dog aiiay
io a mcihou wiih an Animal aiiay aigumcni. No iollcm. Anu
an AiiayIisiAnimal> can lc asscu io a mcihou wiih an
AiiayIisiAnimal> aigumcni. So ihc lig qucsiion is, will ihc
AiiayIisiAnimal> aigumcni accci an AiiayIisiDog>. Il ii woiIs
wiih aiiays, shoulun`i ii woiI hcic ioo.
public void go() {
ArrayList<Animal> animals = new ArrayList<Animal>();
animals.add(new Dog());
animals.add(new Cat());
animals.add(new Dog());
takeAnimals(animals);
ArrayList<Dog> dogs = new ArrayList<Dog>();
dogs.add(new Dog());
dogs.add(new Dog());
takeAnimals(dogs);
}
public void takeAnimals(ArrayList<Animal> animals) {
for(Animal a: animals) {
a.eat();
}
}
w- --- l: |-- ---- --
M.- . l- A--.]|:l .- -l . :--|- -: -
Passing in ]ust ArrayList<Dog>
%java TestGenerics3
TestGenerics3.java:21: takeAnimals(java.util.
ArrayList<Animal>) in TestGenerics3 cannot be applied to
(java.util.ArrayList<Dog>)
takeAnimals(dogs);
^
1 error
File Edit Window Help CatsAreSmarter
When we compile it:
|l |--- :- -l,
-l ---l :- ----
w|| l: --- --- l.l -- :.--
--- .- .--.] l- .- A--.]|:l
poIymorphism and generics
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 571
And I'm supposed fo be OI wifh fhis7 Thof
fofoIIy screws my onimoI simuIofion where fhe
veferinory progrom fokes o Iisf of ony fype of
onimoI, so fhof o dog kenneI con send o Iisf of dogs,
ond o cof kenneI con send o Iisf of cofs... now
you're soying I con'f do fhof if I use coIIecfions
insfeod of orroys7
Whz! ree|4 hzppcn |f | ! wcrc z||ewc4...
Imaginc ihc comilci lci you gci away wiih ihai. Ii lci you ass an
AiiayIisiDog> io a mcihou ucclaicu as:
public void takeAnimals(ArrayList<Animal> animals) {
for(Animal a: animals) {
a.eat();
}
}
Thcic`s noihing in ihai mcihou ihai IooI haimlul, iighi. Alici all,
ihc wholc oini ol olymoihism is ihai anyihing an Animal can
uo in ihis casc, ihc cai) mcihou), a Dog can uo as wcll. So whai`s
ihc iollcm wiih having ihc mcihou call cai) on cach ol ihc Dog
iclcicnccs.
NoL.r. Noihing ai all.
Thcic`s noihing wiong wiih Ln couc. Bui imaginc L. couc insicau:
public void takeAnimals(ArrayList<Animal> animals) {
animals.add(new Cat());
}
/-: '' w- -:l :l-: . c.l - -.l
-l - . l-:~--|] A--.]|:l
So ihai`s ihc iollcm. Thcic`s cciiainly noihing wiong wiih auuing a
Cai io an AiiayIisiAnimal>, anu ihai`s ihc wholc oini ol having an
AiiayIisi ol a suciiyc liIc Animal-so ihai you can ui all iycs ol
animals in a singlc Animal AiiayIisi.
Bui il you asscu a Dog AiiayIisi-onc mcani io holu ONIY Dogs-
io ihis mcihou ihai iaIcs an Animal AiiayIisi, ihcn suuucnly you`u
cnu u wiih a Cai in ihc Dog lisi. Thc comilci Inows ihai il ii lcis
you ass a Dog AiiayIisi inio ihc mcihou liIc ihai, somconc coulu,
ai iuniimc, auu a Cai io youi Dog lisi. So insicau, ihc comilci |usi
won`i lci you iaIc ihc iisI.
I[ you decIore o method to tohe ArroyList<AnimoI> it con tohe ONLY on
ArroyList<AnimoI>, not ArroyList<Dog> or ArroyList<Cot>.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
572 chapter 16
Woif o minufe... if fhis is why fhey won'f Ief
you poss o Dog ArroyLisf info o mefhod fhof
fokes on AnimoI ArroyLisf-fo sfop you from
possibIy puffing o Cof in whof wos ocfuoIIy o Dog Iisf,
fhen why does if work wifh orroys7 Don'f you hove
fhe some probIem wifh orroys7 Con'f you sfiII odd
o Cof objecf fo o Dog[] 7
Array types are checked again at
runtime, but collection type checks
happen only when you compile
Ici`s say you auu a Cai io an aiiay ucclaicu as Dog]| an aiiay ihai
was asscu inio a mcihou aigumcni ucclaicu as Animal]|, which is a
cilccily lcgal assignmcni loi aiiays).
public void go() {
Dog[] dogs = {new Dog(), new Dog(), new Dog()};
takeAnimals(dogs);
}
public void takeAnimals(Animal[] animals) {
animals[0] = new Cat();
} w- -l . --- c.l -l- . l- .--.] 1-
:--|-- .||--- l, -:.-:- l ---: l.l
]-- -l .- .::- . c.l .--.] -- A--.|
.--.] l- l- --l-, :- l- l- :--|-- l
-.: -::|- l.l l: -.: 6r
%java TestGenerics1
Exception in thread main java.lang.ArrayStoreException:
Cat
at TestGenerics1.takeAnimals(TestGenerics1.java:16)
at TestGenerics1.go(TestGenerics1.java:12)
at TestGenerics1.main(TestGenerics1.java:5)
File Edit Window Help CatsAreSmarter
t compiles, but when we run it:
w--' Al |-.:l l-
)/M :l-- l
arrays vs. ArrayLists
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 573
WouIdn'f if be dreomy if fhere were
o woy fo sfiII use poIymorphic coIIecfion
fypes os mefhod orgumenfs, so fhof my
veferinory progrom couId foke Dog Iisfs
ond Cof Iisfs7 Thof woy I couId Ioop fhrough
fhe Iisfs ond coII fheir immuni;e() mefhod,
buf if wouId sfiII hove fo be sofe so fhof you
couIdn'f odd o Cof in fo fhe Dog Iisf. 8uf I
guess fhof's jusf o fonfosy...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
574 chapter 16
W||4rzr4s !e !hc rcsrec
Ii looIs unusual, lui ihcic . a way io cicaic a mcihou aigumcni ihai
can accci an AiiayIisi ol any Animal suliyc. Thc simlcsi way is io
usc a -auucu io ihc ]ava languagc cxliciily loi ihis icason.
public void takeAnimals(ArrayList<? extends Animal> animals) {
for(Animal a: animals) {
a.eat();
}
}
So now you`ic wonuciing, Whai`s ihc J.e.ere. Don`i you havc
ihc samc iollcm as lcloic. Thc mcihou alovc isn`i uoing
anyihing uangcious-calling a mcihou any Animal suliyc is
guaianiccu io havc-lui can`i somconc siill changc ihis io auu a
Cai io ihc nr.nI lisi, cvcn ihough ii`s ically an AiiayIisiDog>.
Anu sincc ii`s noi chccIcu again ai iuniimc, how is ihis any
uillcicni liom ucclaiing ii wiihoui ihc wilucaiu."
Anu you`u lc iighi loi wonuciing. Thc answci is NO. Whcn you
usc ihc wilucaiu .> in youi ucclaiaiion, ihc comilci won`i lci
you uo anyihing ihai auus io ihc lisi!
When you use a wildcard in your method
argument, the compiler will 8TOP you from doing
anything that could hurt the list referenced by the
method parameter.
You can still invoke methods on the elements in
the list, but you cannot add elements to the list.
n other words, you can do things with the list
elements, but you can't put new things in the list.
8o you're safe at runtime, because the compiler
won't let you do anything that might be horrible at
runtime.
8o, this is OK inside takeAnimals{}:
for(Animal a: animals) {
a.eat();
}
But TH8 would not compile:
animals.add(new Cat());
------, l- -]--- -l--:'
--- --.-: -l-- -l--: 6
-|----l: ---- -- l-
l]- - ]-- -.-l l- l.-
.- A--.]|:l - l]-: l.l
-|----l l- |-l -l--.:-,
]--' -:|.-- l .:
A--.]|:l -l--: |-l
generic wiIdcards
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 575
| !crnz!c syn!zr fer 4e|n] !hc szmc !h|n]
You iolally icmcmlci ihai whcn wc looIcu ai ihc soii) mcihou,
ii uscu a gcnciic iyc, lui wiih an unusual loimai whcic ihc iyc
aiamcici was ucclaicu lcloic ihc iciuin iyc. Ii`s |usi a uillcicni way
ol ucclaiing ihc iyc aiamcici, lui ihc icsulis aic ihc samc:
public <T extends Animal> void takeThing(ArrayList<T> list)
This:
public void takeThing(ArrayList<? extends Animal> list)
Does the same thing as this:
(-,- a,- |
oa|| qa--(:|-

If they both do the same thing, why wouId you use


one over the other!

|t all depends on whether you want to use "T some-
where else. Por example, what if you want the method to
have two argumentsboth of which are lists of a type that
extend AnimalI |n that case, it's more efficient to |ust declare
the type parameter once:
|nstead of typing:
public <T extends Animal> void takeThing(ArrayList<T> one, ArrayList<T> two)
public void takeThing(ArrayList<? extends Animal> one,
ArrayList<? extends Animal> two)

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
576 chapter 16

our |ob is to play compiler and determine which of


these statements would compile. 8ut some of this
code wasn't covered in the chapter, so you need to
work out the answers based on what you D|D learn,
applying the "rules to these new situations. |n
some cases, you might have to guess, but the
point is to come up with a reasonable answer
based on what you know so far.
(Note: assume that this code is within a legal class and
method.)
] ge eomgj|e;, vee

ArrayList<Dog> dogs1 = new ArrayList<Animal>();


ArrayList<Animal> animals1 = new ArrayList<Dog>();


List<Animal> list = new ArrayList<Animal>();

ArrayList<Dog> dogs = new ArrayList<Dog>();

ArrayList<Animal> animals = dogs;

List<Dog> dogList = dogs;

ArrayList<Object> objects = new ArrayList<Object>();

List<Object> objList = objects;

ArrayList<Object> objs = new ArrayList<Dog>();



CompiIes!
be the compiIer exercise
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 577
import juvu,utiI,*,
public class SortMountains {
LinkedList-Mountuin> mtn = new LinkedList-Mountuin>{|,
class NameCompare impIements Compurutor -Mountuin> {
public int compare{Mountain one, Mountain two| {
return one,nume,compureTo{two,nume},
}
}
class HeightCompare impIements Compurutor -Mountuin> {
public int compare{Mountain one, Mountain two| {
return {two,height - one,height|,
}
}
public static void main{String args| {
new SortMountain{|.go{|,
}
public void go{| {
mtn.add{new Mountain{"Longs", l4255||,
mtn.add{new Mountain{"Elbert", l4433||,
mtn.add{new Mountain{"Maroon", l4l56||,
mtn.add{new Mountain{"Castle", l4265||,
System.out.println{"as entered:\n" + mtn|,
NameCompare nc = new NameCompare{|,
CoIIections,sort{mtn nc},
System.out.println{"by name:\n" + mtn|,
HeightCompare hc = new HeightCompare{|,
CoIIections,sort{mtn hc},
System.out.println{"by height:\n" + mtn|,
}
}
class Mountain {
String nume,
int height,
Mountuin{String n int h} {
nume = n,
height = h,
}
pubIic String toString{ } {
return nume + " " + height,
}
File Edit Window Help ThisOne'sForBob
%java SortMountains
as entered:
[Longs 14255, Elbert 14433, Maroon 14156, Castle 14265]
by name:
[Castle 14265, Elbert 14433, Longs 14255, Maroon 14156]
by height:
[Elbert 14433, Castle 14265, Longs 14255, Maroon 14156]

l ]-- --l:- l.l l- -l |:l :


- l!c!Nl|N6 :----:- `
o|ajo o ge geve;ze
]gjee; zg;ge ee;ejze
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
578 chapter 16
Givcn ihc lollowing comilallc siaicmcni:
Collections.sort(myArrayList);
1. Whai musi ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni. CompurubIe
2. Whai mcihou musi ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni. compureTo{ }
S. Can ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni loih
Comparator AND Comparable. yes
Givcn ihc lollowing comilallc siaicmcni:
Collections.sort(myArrayList, myCompare);
4. Can ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni Comparable. yes
. Can ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni Comparator. yes
6. Musi ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni Comparable. no
7. Musi ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni Comparator. no
S. Whai musi ihc class ol ihc myCompare ol|cci imlcmcni. Compurutor
9. Whai mcihou musi ihc class ol ihc myCompare ol|cci imlcmcni. compure{ }
]e;ejze o|ajo
Possible Answers:
6omparator,
6omparab|e,
compareTo( },
compare( },
yes,
no
fiII-in-the-bIank soIution
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 579
] ge eomgj|e; zo|ajo

ArrayList<Dog> dogs1 = new ArrayList<Animal>();


ArrayList<Animal> animals1 = new ArrayList<Dog>();


List<Animal> list = new ArrayList<Animal>();

ArrayList<Dog> dogs = new ArrayList<Dog>();

ArrayList<Animal> animals = dogs;

List<Dog> dogList = dogs;

ArrayList<Object> objects = new ArrayList<Object>();

List<Object> objList = objects;

ArrayList<Object> objs = new ArrayList<Dog>();



CompiIes!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 581
It's time to Iet go. ou wrote your code. ou tested your code. ou refined your code.
ou told everyone you know that if you never saw a line of code again, that'd be fine. 8ut in the
end, you've created a work of art. The thing actually runs! 8ut now whatI do you give it to
end usersI exactly do you give to end usersI what if you don't even know who your end
users areI |n these final two chapters, we'll explore how to organize, package, and deploy your
1ava code. we'll look at local, semi-local, and remote deployment options including executable
|ars, 1ava web Start, PM|, and Servlets. |n this chapter, we'll spend most of our time on organizing
and packaging your codethings you'll need to know regardless of your ultimate deployment
choice. |n the final chapter, we'll finish with one of the coolest things you can do in 1ava. Pelax.
Peleasing your code is not saying goodbye. There's always maintenance...
Release Your Code
17 package, jars and depIoyment
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
582 chapter 17
Java depIoyment
j ]zvz gz j, z ane[
| e]z,,,. [[z(', ([
a(a( | ya ]v]n(.
[[ z] ga,(jn j, w[z(
( ] wj([ ([, e]z,,,
w[n ya' ]n.
Pcp|ey|n] yeer zpp||rz!|en
Whai cxacily a ]ava alicaiion. In oihci woius,
oncc you`ic uonc wiih ucvclomcni, whai is ii ihai you
uclivci. Chanccs aic, youi cnu-uscis uon`i havc a sysicm
iucniical io youis. Moic imoiianily, ihcy uon`i havc youi
alicaiion. So now ii`s iimc io gci youi iogiam in shac
loi ucloymcni inio Thc Ouisiuc Woilu. In ihis chaici,
wc`ll looI ai local ucloymcnis, incluuing Exccuiallc ]ais
anu ihc aii-local/aii-icmoic icchnology callcu ]ava Wcl
Siaii. In ihc ncxi chaici, wc`ll looI ai ihc moic icmoic
ucloymcni oiions, incluuing RMI anu Scivlcis.
Deployment options
Bui lcloic wc ically gci inio ihc wholc ucloymcni ihing,
lci`s iaIc a sic lacI anu looI ai whai hacns whcn you`vc
hnishcu iogiamming youi a anu you simly wani io ull
oui ihc class hlcs io givc ihcm io an cnu-usci. Whai`s ically
ihai woiIing uiiccioiy.
3
1
LocuI
The enfire oppIicofion runs on fhe
end-user's compufer, os o sfond-oIone,
probobIy 0UI, progrom, depIoyed os
on execufobIe JAP (we'II Iook of JAP
in o few poges.)
2
Pemote
The enfire Jovo oppIicofion runs on o
server sysfem, wifh fhe cIienf occessing
fhe sysfem fhrough some non-Jovo
meons, probobIy o web browser.
Combinution of IocuI und remote
The oppIicofion is disfribufed wifh o
cIienf porfion running on fhe user's
IocoI sysfem, connecfed fo o server
where ofher porfs of fhe oppIicofion
ore running.
100% LocuI Combinution 100% Pemote
8erv|ets

web 8tart
FiIe Edit View

RH| app
FiIe Edit View

8f8l 88f00ll
what are the advantages and
disadvantages of delivering your
1ava program as a local, stand-
alone application running on
the end-user's computerI
what are the advantages and
disadvantages of delivering your
1ava program as web-based
system where the user interacts
with a web browser, and the
1ava code runs as servlets on the
serverI
Executab|e
Jar
FiIe Edit View
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 583
|mz]|nc !h|s srcnzr|e...
Bol`s haily ai woiI on ihc hnal icccs ol his cool ncw
]ava iogiam. Alici wccIs ol lcing in ihc I`m-|usi-
onc-comilc-away" mouc, ihis iimc hc`s ically
uonc. Thc iogiam is a laiily sohisiicaicu
GUI a, lui sincc ihc lulI ol ii is Swing
couc, hc`s mauc only ninc classcs ol his
own.
Ai lasi, ii`s iimc io uclivci ihc iogiam io ihc
clicni. Hc hguics all hc has io uo is coy ihc
ninc class hlcs, sincc ihc clicni alicauy has
ihc ]ava API insiallcu. Hc siaiis ly uoing an
on ihc uiiccioiy whcic all his hlcs aic...
Whoa! Somcihing siiangc has hacncu. Insicau ol 1S
hlcs ninc souicc couc hlcs anu ninc comilcu class
hlcs), hc sccs S1 hlcs, many ol which havc vciy siiangc
namcs liIc:
AccouniSIilcIisicnci.class
ChaiiSSavcIisicnci.class
anu on ii gocs. Hc hau comlcicly loigoiicn
ihai ihc comilci has io gcnciaic class hlcs
loi all ihosc innci class GUI cvcni lisicncis
hc mauc, anu ihai`s whai all ihc siiangcly-
namcu classcs aic.
Now hc has io caiclully cxiiaci all ihc class
hlcs hc nccus. Il hc lcavcs cvcn onc ol ihcm oui,
his iogiam won`i woiI. Bui ii`s iiicIy sincc hc
uocsn`i wani io acciucnially scnu ihc clicni
onc ol his couc hlcs, yci cvciyihing is
in ihc samc uiiccioiy in onc lig mcss.
Whof fhe... 7
If's
fnoIIy donel
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
organizing your cIasses
584 chapter 17
%cd MyProject/classes
%java Mini
%cd MyProject/source
%javac -d ../classes MyApp.java
8cpzrz!c seerrc re4c zn4 r|zss f||cs
A singlc uiiccioiy wiih a ilc ol souicc couc anu class hlcs is a
mcss. Ii iuins oui, Bol shoulu havc lccn oiganizing his hlcs
liom ihc lcginning, Iccing ihc souicc couc anu comilcu
couc scaiaic. In oihci woius, maIing suic his comilcu class
hlcs uiun`i lanu in ihc samc uiiccioiy as his souicc couc.
The hey is o combinotion o[ directory structure orgonizotion ond the
compiIer option.
8uf I fhoughf I didn'f hove
o choice obouf puffing fhe cIoss
fIes in wifh fhe source fIes.
When you compiIe, fhey jusf go
fhere, so whof do I do7
Thcic aic uozcns ol ways you can oiganizc youi hlcs, anu youi
comany mighi havc a sccihc way ihcy wani you io uo ii. Wc
iccommcnu an oiganizaiional schcmc ihai`s lccomc almosi
sianuaiu, ihough.
Wiih ihis schcmc, you cicaic a io|cci uiiccioiy, anu insiuc
ihai you cicaic a uiiccioiy callcu sourcc anu a uiiccioiy callcu
classcs. You siaii ly saving youi souicc couc .|ava hlcs) inio
ihc sourcc uiiccioiy. Thcn ihc iiicI is io comilc youi couc
in such a way ihai ihc ouiui ihc .class hlcs) cnus u in ihc
cIosses uiiccioiy.
Anu ihcic`s a nicc comilci uag, -d, ihai lcis you uo ihai.
Compiling with the -d {directory} hag
l-||: l- :--|-- l- -l l-
:--|- :-- |:|.:: |-:`
-l- l- :|.::-: --:l--]
l.l': --- --:l--] - .-
.: --- ..- --- l-
:-----l ---- --:l--]
l- |.:l l- : :l||
l- -.-- - l- ..
|- l- :--|-
By using ihc -d uag, gci io ucciuc which directory ihc
comilcu couc lanus in, iaihci ihan accciing ihc uclauli ol
class hlcs lanuing in ihc samc uiiccioiy as ihc souicc couc.
To comilc all ihc .|ava hlcs in ihc souicc uiiccioiy, usc:
Running your code
--- ]--- ---.- ---
l- ':|.::-:' --:l--]
%javac -d ../classes *.java
.. :--|-: A||
:---:- |-: - l-
:-----l --:l--]
HyProject
source c|asses
Lorper
iure eugue
tat vero
conse
eugueroLore
do eliquis
do del dip
101101
101101
10101000010
1010 10 0
01010 1
1010101
10101010
1001010101
HyApp.java
HyApp.c|ass
:--|- ---
1+| --:l--]
:--|- :--
|.-: ---
--- ]--- -.-|`
--- ---
|l---|-:--l- --l- ---]l- - l: :.l-- .::---: l.l l-
:-----l ---- --:l--] |- l- '` : - ]--- :|.::.l | ]--
.- -|:l|] :-l . :|.::.l --------l .-.|-, - :--l.-
l.l l :--l.-: l- ' `
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 585
|e! yeer 1zvz |n z 1K
A hlc is a ava chivc. Ii`s lascu on ihc Izi hlc loimai, anu ii lcis you lunulc
all youi classcs so ihai insicau ol icscniing youi clicni wiih 2S class hlcs, you hanu
ovci |usi a singlc ]AR hlc. Il you`ic lamiliai wiih ihc iai commanu on UNIX, you`ll
iccognizc ihc |ai iool commanus. Noic: whcn wc say ]AR in all cas, wc`ic iclciiing
io ihc aichivc Ie. Whcn wc usc lowcicasc, wc`ic iclciiing io ihc n. ooI you usc io
cicaic ]AR hlcs.)
Thc qucsiion is, whai uocs ihc clicni Jo wiih ihc ]AR. How uo you gci ii io .ur.
You maIc ihc ]AR executobIe.
An cxccuiallc ]AR mcans ihc cnu-usci uocsn`i havc io ull ihc class hlcs oui lcloic
iunning ihc iogiam. Thc usci can iun ihc a whilc ihc class hlcs aic siill in ihc
]AR. Thc iiicI is io cicaic a moni[est hlc, ihai gocs in ihc ]AR anu holus inloimaiion
aloui ihc hlcs in ihc ]AR. To maIc a ]AR cxccuiallc, ihc manilcsi musi icll ihc ]VM
wL.L In Ln Le n.r() eLoJ
JAP
101101
101101
10101000010
1010 10 0
01010 1
1010101
10101010
1001010101
Making an executable JAR
1
Muke sure uII of your cIuss h Ies ure in
the cIusses directory
We're going fo refne fhis in o few poges, buf
for now, keep oII your cIoss fIes siffing in fhe
direcfory nomed 'cIosses'.
2
Creute u munifest,tt h Ie thut stutes
which cIuss hus the muin{} method
Moke o fexf fIe nomed monifesf.fxf fhof hos o
one Iine:
Main-Class: MyApp
Press fhe refurn key offer fyping fhe Moin-
CIoss Iine, or your monifesf moy nof work
correcfIy. Puf fhe monifesf fIe info fhe "cIosses"
direcfory.
101101
101101
10101000010
1010 10 0
01010 1
1010101
10101010
1001010101
101101
101101
10101000010
1010 10 0
01010 1
1010101
10101010
1001010101
Va|r-C|ass: Vy|App
3
Pun the jur tooI to creute u JAP h Ie
thut contuins everything in the cIusses
directory pIus the munifest,
%cd MiniProject/classes
%jar -cvmf manifest.txt app1.jar *.class
OR
%jar -cvmf manifest.txt app1.jar MyApp.class
c|asses
HyProject
101101
101101
c|asses
101101
101101
101101
101101
HyProject
Va|r-C|ass: V|r|App
rar|lesl.lxl
upp1,jur
101101
101101
101101
101101
101101
101101
Va|r-C|ass: V|r|App
--'l -l l- :|.::
-- l- --
-- :---:-
:-- |..`
- l- )A
VyApp.c|ass
c|asses
rar|lesl.lxl
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
586 chapter 17
Kenn|n] |crcre!|n]I !hc 1K
]ava ihc ]VM) is caallc ol loauing a class liom a ]AR, anu calling
ihc main) mcihou ol ihai class. In laci, ihc cniiic alicaiion can
n, in ihc ]AR. Oncc ihc lall is iolling i.c., ihc main) mcihou
siaiis iunning), ihc ]VM uocsn`i caic wLe.e youi classcs comc
liom, as long as ii can hnu ihcm. Anu onc ol ihc laccs ihc ]VM
looIs is wiihin any ]AR hlcs in ihc classaih. Il ii can ee a ]AR, ihc
]VM will IooI in ihai ]AR whcn ii nccus io hnu anu loau a class.
%cd MyProject/classes
%java -jar app1.jar
upp1,jur
101101
101101
101101
101101
101101
101101
Va|r-C|ass: V|r|App
c|asses
1- )/M .: l- ':--' l- )A, :-
l --:l - - ]--- :|.::.l 1-
-.:-:l -.] l- -.- l- )A :|-
: l- -.- ]--- ---- --:l--]
l- |.:- ---- l- )A :
1- ~.- |. l-||: l- )/M ]--'-- - l . )A -:l-. - . :|.::
1
- )/M
|--: -:- l: )A
--
. -.--:l -l .- --l-] -- M
.-~
c|.:: | l --:-'l - ---, ]-- -l
. ---l-- -:-l--
Dccnuing on how youi ociaiing sysicm is conhguicu, you
mighi cvcn lc allc io simly uoullc-clicI ihc ]AR hlc io launch
ii. This woiIs on mosi uavois ol Winuows, anu Mac OS X. You
can usually maIc ihis hacn ly sclcciing ihc ]AR anu iclling
ihc OS io Ocn wiih..." oi whaicvci ihc cquivalcni is on youi
ociaiing sysicm).

Why can't I just 1AR up an entire directory!


The 1vM looks inside the 1AP and expects to find
what it needs t|ht thete. |t won't go digging into other
directories, unless the class is part of a package, and even
then the 1vM looks only in the directories that match the
package statementI

What did you just say!

ou can't put your class files into some arbitrary
directory and 1AP them up that way. 8ut if your classes
belong to packages, you can 1AP up the entire package
directory structure. |n fact, you must. we'll explain all this on
the next page, so you can relax.
100% LocuI Combinution 100% Pemote
CU| c||ent
FiIe Edit View
8erv|ets
HTTP
web 8tart
FiIe Edit View
HTTP
RH| app
FiIe Edit View
RMI
Executab|e
Jar
FiIe Edit View
(-,- a,- |
oa|| qa--(:|-
p,( Jee/ ]ez] ]zvz
z, z ]]y] z,
yea(z] ]j |j],.
executabIe JAR
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 587
|e! yeer r|zsscs |n pzrkz]cs|
So you`vc wiiiicn somc niccly icusallc class hlcs, anu you`vc
osicu ihcm in youi inicinal ucvclomcni liliaiy loi oihci
iogiammcis io usc. Whilc lasIing in ihc glow ol having
|usi uclivcicu somc ol ihc in youi humllc oinion) lcsi
cxamlcs ol OO cvci conccivcu, you gci a honc call. A
lianiic onc. Two ol youi classcs havc ihc samc namc as
ihc classcs Iicu |usi uclivcicu io ihc liliaiy. Anu all hcll is
licaIing loosc oui ihcic, as naming collisions anu amliguiiics
liing ucvclomcni io iis Inccs.
Anu all lccausc you uiun`i usc acIagcs! Wcll, you uiu usc
acIagcs, in ihc scnsc ol using classcs in ihc ]ava API ihai aic,
ol couisc, in acIagcs. Bui you uiun`i ui youi own classcs
inio acIagcs, anu in ihc Rcal Woilu, ihai`s Rcally Bau.
Wc`ic going io mouily ihc oiganizaiional siiuciuic liom ihc
icvious agcs, |usi a liiilc, io ui classcs inio a acIagc, anu
io ]AR ihc cniiic acIagc. Pay vciy closc aiicniion io ihc
sulilc anu icIy uciails. Evcn ihc iinicsi ucviaiion can sio
youi couc liom comiling anu/oi iunning.
|zrkz]cs prcvcn! r|zss nzmc renf||r!s
Alihough acIagcs aicn`i |usi loi icvcniing namc collisions,
ihai`s a Icy lcaiuic. You mighi wiiic a class namcu Cusiomci
anu a class namcu Accouni anu a class namcu ShoingCaii.
Anu whai uo you Inow, hall ol all ucvclocis woiIing in
cniciiisc c-commcicc havc iolally wiiiicn classcs wiih
ihosc namcs. In an OO woilu, ihai`s |usi uangcious. Il aii ol
ihc oini ol OO is io wiiic icusallc comoncnis, ucvclocis
nccu io lc allc io iccc iogcihci comoncnis liom a
vaiiciy ol souiccs, anu luilu somcihing ncw oui ol ihcm.
Youi comoncnis havc io lc allc io lay wcll wiih oihcis`,
incluuing ihosc you uiun`i wiiic oi cvcn Inow aloui.
Rcmcmlci way lacI in chaici 6 whcn wc uiscusscu how
a acIagc namc is liIc ihc lull namc ol a class, icchnically
Inown as ihc uII,-qunI.eJ rne. Class AiiayIisi is ically
jovo.utiI.ArroyList, ]Buiion is ically jovox.swing.]Button, anu
SocIci is ically jovo.net.Sochet. Noiicc ihai iwo ol ihosc classcs,
AiiayIisi anu SocIci, loih havc n.n as ihcii hisi namc".
In oihci woius, ihc hisi aii ol ihcii lully-qualihcu namcs
is |ava". ThinI ol a hiciaichy whcn you ihinI ol acIagc
siiuciuics, anu oiganizc youi classcs accoiuingly.
]ava
net
util
text
awt
event










3oc|el
Acl|orEverl





F|oWLayoul





ArrayL|sl





NuroerForral
Puckuge structure of the Juvu API for:
Whut does this picture Iook Iike to
you? Doesn't it Iook u whoIe Iot Iike
u directory hierurchy?
jovo.fexf.MumberFormof
jovo.ufiI.ArroyLisf
jovo.owf.FIowLoyouf
jovo.owf.evenf.AcfionEvenf
jovo.nef.Sockef
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
588 chapter 17
|rcvcn!|n] pzrkz]c nzmc renf||r!s
Puiiing youi class in a acIagc icuuccs ihc chanccs ol naming
conuicis wiih oihci classcs, lui whai`s io sio iwo iogiammcis
liom coming u wiih iucniical nIne namcs. In oihci woius,
whai`s io sio iwo iogiammcis, cach wiih a class namcu Accouni,
liom uiiing ihc class in a acIagc namcu shoing.cusiomcis.
Boih classcs, in ihai casc, woulu .II havc ihc samc namc:
shopping.customers.Account
Sun siiongly suggcsis a acIagc naming convcniion ihai gicaily
icuuccs ihai iisI-iccnu cvciy class wiih youi icvcisc uomain
namc. Rcmcmlci, uomain namcs aic guaianiccu io lc uniquc.
Two uillcicni guys can lc namcu Baiiholomcw Simson, lui iwo
uillcicni uomains cannoi lc namcu uoh.com.
...so I fnoIIy seffIed on
foo.bor.Heisenberg for my
quonfum boking cIoss
Why, fhof's fhe some nome
I wos fhinking of for my
sub-ofomic ironing cIossl
0uess I'II jusf hove fo come
up wifh somefhing eIse.
Reverse domain package names
com.heodfrsfjovo.projecfs.Chorf
:l.-l l- .:.- -l ]--- ----:-
--.-, :-.-.l- ] . -l |`,
l-- . ]--- --- --.--.l--.|
:l--:l--- .l-- l.l
l

- :
|.
:: -
.
-
- :
.
|-
.
]
: :
.

l
.
|-
-
---:l:c.-l -l - . :-----
-.--, -l .- :---.-:l..
--.-: -- .- l- ----] .--l --|]
--- --- -~--:- --|---:
]ze[zg, ezn vn( nz
en|]je(,, a( n]y j| ya
e[, z ze[zg nz
([z(', gazzn(] (
anjga. [[ ,( wzy (
] ([z( j, ( |ze ya
ze[zg, wj([ ya v,
]zjn nz.
com.heodfrsfbooks.8ook
.:.- -.--
:
|.
:: -
.
-
-
package naming
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 589
p
o
c
k
o
g
e

s
f
r
u
c
f
u
r
e
HyProject
source c|asses
101101
101101
10101000010
1010 10 0
01010 1
1010101
10101010
1001010101
PackageExerc|se.c|ass
com
heedfirstjeve
com
heedfirstjeve
Lorper
iure eugue
tat vero
conse
eugueroLore
do eliquis
do del dip
PackageExerc|se.java
1
Choose u puckuge nume
We're using com,heudhrstjuvu os our
exompIe. The cIoss nome is PockogeExercise,
so fhe fuIIy-quoIifed nome of fhe cIoss is now:
com,heudhrstjuvu,PuckugeEercise.
To put your class in a package:
2
Put u puckuge stutement in your cIuss
package com.head rstjava;
import javax.swing.*;
public class PackageExercise {
// life-altering code here
}
3
Set up u mutching directory structure
If musf be fhe frsf sfofemenf in fhe source
code fIe, obove ony imporf sfofemenfs. There
con be onIy one pockoge sfofemenf per source
code fIe, so uII cIusses in u source hIe must
be in the sume puckuge. Thof incIudes inner
cIosses, of course.
If's nof enough fo suy your cIoss is in o pockoge,
by mereIy puffing o pockoge sfofemenf in
fhe code. Your cIoss isn'f fruIy in o pockoge
unfiI you puf fhe cIoss in o mofching direcfory
sfrucfure. So, if fhe fuIIy-quoIifed cIoss nome
is com.heodfrsfjovo.PockogeExercise, you
must puf fhe PockogeExercise source code in o
direcfory nomed heudhrstjuvu, which must be in
o direcfory nomed com.
If is possibIe fo compiIe wifhouf doing fhof, buf
frusf us-if's nof worfh fhe ofher probIems
you'II hove. Ieep your source code in o direcfory
sfrucfure fhof mofches fhe pockoge sfrucfure,
ond you'II ovoid o fon of poinfuI heodoches down
fhe rood.
You must put a class
into a directory
structure that matches
the package hierarchy.
Sef up o mofching direcfory sfrucfure for
bofh fhe source ond cIosses frees.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
590 chapter 17
%cd MyProject/classes
%java com.head rstjava.PackageExercise
%cd MyProject/source
%javac -d ../classes com/head rstjava/PackageExercise.java
Compiling with the -d {directory} hag
l-||: l- :--|-- l- -l l-
:--|- :-- |:|.:: |-:`
-l- l- :|.::-: --:l--],
-l- l- -l .:.-
:l--:l---'' /-:, l ---:
N-- ]-- .- l- :-:]
l- |A1+ l- -l l- l-
.:l-.| :---:- |-
To comilc all ihc .|ava hlcs in ihc com.hcauhisi|ava
acIagc, usc:
Running your code
--- ]--- ---.- ---
l- ':|.::-:' --:l--]
%javac -d ../classes com/head rstjava/*.java
0emp|||n] zn4 renn|n] w| !h pzrkz]cs
Whcn youi class is in a acIagc, ii`s a liiilc iiicIici io comilc anu
iun. Thc main issuc is ihai loih ihc comilci anu ]VM havc io lc
caallc ol hnuing youi class anu all ol ihc oihci classcs ii uscs.
Ioi ihc classcs in ihc coic API, ihai`s ncvci a iollcm. ]ava always
Inows whcic iis own siull is. Bui loi youi classcs, ihc soluiion
ol comiling liom ihc samc uiiccioiy whcic ihc souicc hlcs aic
simly won`i woiI oi ai lcasi noi ). Wc guaianicc, ihough,
ihai il you lollow ihc siiuciuic wc ucsciilc on ihis agc, you`ll lc
succcsslul. Thcic aic oihci ways io uo ii, lui ihis is ihc onc wc`vc
lounu ihc mosi icliallc anu ihc casicsi io siicI io.
HyProject
source c|asses
101101
10 110 1
0 11 0
001 10
001 01
PackageExerc|se.c|ass
com
heedfirstjeve
com
heedfirstjeve
Lorper
iure
eugue
tat vero
conse
euguero-
PackageExerc|se.java
]--'|| :l|| :--|-
--- ---
:l.] - l- :---:- --:l--]' l- N61 : ---
-l- l- --:l--] ---- l- .. |- :'
:--|-: ---] :---:- |..` |- - l: --:l--]
/-- Mc1 - l- -||]~-.|- :|.:: -.--' 1- )/M -||
:-- l.l, .- ---.l-|] |-- -:- l: :-----l --:l--]
|:|.::-:` .- --:l l- - . --:l--] -.-- :--, ----
l --:l: l- - . --:l--] -.-- -.-:l.., .- -
l--- l --:l: l- - l- :|.:: | l- :|.:: : - l- :--'
--:l--], -- --- - :|.::-:', l ---'l ---'
]
-
-'|| :l
|| -
--

-
-
-

--
-
compiIe and run with packages
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 591
(-,- a,- |
oa|| qa--(:|-

I tried to cd into the
directory where my main cIass
was, but now the 1VM says it can't
nd my cIassl ut it's right 7HR
in the current directoryl

Once your class is in a
package, you can't call it by its
'short' name. ou MUST specify,
at the command-line, the fully-
qualified name of the class whose
main() method you want to run.
8ut since the fully-qualified name
includes the ocloe structure,
1ava insists that the class be in a
matching J|tectoty structure. So if
at the command-line you say:
%ava com.foo.Book
the 1vM will look in its current
directory (and the rest of its
classpath), for a directory named
"com. lr will ner leek Ier n clnss
nnmeJ 8eek, unril ir hns IeunJ
n Jirecrery nnmeJ "cem" wirh n
Jirecrery insiJe nnmeJ "Iee". Only
then will the 1vM accept that its
found the correct 8ook class. |f it
finds a 8ook class anywhere else,
it assumes the class isn't in the
right structure, even if it is! The
1vM won't for example, look back
up the directory tree to say, "Oh, |
can see that above us is a directory
named com, so this must be the
right package...
Ihc -4 f|z] |s cvcn ree|cr !hzn wc sz|4
Comiling wiih ihc -d uag is wonucilul lccausc noi only uocs ii
lci you scnu youi comilcu class hlcs inio a uiiccioiy oihci ihan
ihc onc whcic ihc souicc hlc is, lui ii also Inows io ui ihc class
inio ihc coiicci uiiccioiy siiuciuic loi ihc acIagc ihc class is in.
Bui ii gcis cvcn lciici!
Ici`s say ihai you havc a nicc
uiiccioiy siiuciuic all sci u loi youi
souicc couc. Bui you havcn`i sci
u a maiching uiiccioiy siiuciuic
loi youi classcs uiiccioiy. Noi a
iollcm! Comiling wiih
-u iclls ihc comilci io noi
|usi youi classcs inio ihc
coiicci uiiccioiy iicc, lui io
ihc uiiccioiics il ihcy uon`i cxisi.
HyProject
source c|asses
com
heedfirstjeve
Lorper
iure
eugue
tat vero
conse
euguero-
PackageExerc|se.java
| l- .:.- --:l--] :l--:l---
--:-'l -:l ---- l- ':|.::-:'
--:l--], l- :--|-- -|| -| l-
--:l---: ]-- -:- l- ~ |.
- ]-- --'l .:l-.||] .- l-
]::.||] :--.l- l- --:l---: ----
l- ':|.::-:' ---l --:l--] A- -
.:l, ]-- |-l l- :--|-- - l
l---': -- :.-:- - . l]-
The -d hag tells the compiler,
Put the class into its package
directory structure, using the
class specihed after the -d as
the root directory. But... if the
directories aren't there, create
them hrst and then put the class
in the right placel
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
592 chapter 17
Whcn youi class is in a acIagc, ihc acIagc uiiccioiy siiuciuic
musi lc insiuc ihc ]AR! You can`i |usi o youi classcs in ihc
]AR ihc way wc uiu ic-acIagcs. Anu you musi lc suic ihai you
uon`i incluuc any oihci uiiccioiics alovc youi acIagc. Thc
hisi uiiccioiy ol youi acIagc usually com) musi lc ihc hisi
uiiccioiy wiihin ihc ]AR! Il you wcic io acciucnially incluuc ihc
uiiccioiy ihc acIagc c.g. ihc classcs" uiiccioiy), ihc ]AR
woulun`i woiI coiiccily.
PackageExerc|se.c|ass
c|asses
com
heedfirstjeve
101101
10 110 1
0 11 0
001 10
001 01
Mzk|n] zn crcre!z||c 1K w| !h pzrkz]cs
JAP
Making an executable JAR
1
Muke sure uII of your cIuss h Ies ure
within the correct puckuge structure
under the cIusses directory,
2
Creute u munifest,tt h Ie thut stutes
which cIuss hus the muin{} method
und be sure to use the fuIIy-quuIih ed
cIuss nume|
Moke o fexf fIe nomed monifesf.fxf fhof hos o
singIe Iine:
Main-Class: com.head rstjava.PackageExercise
Puf fhe monifesf fIe info fhe cIosses direcfory
3
Pun the jur tooI to creute u JAP h Ie
thut contuins the puckuge directories
pIus the munifest
%cd MyProject/classes
%jar -cvmf manifest.txt packEx.jar com
puckE,jur
c|asses
man|fest.txt
c|asses
com
heedfirstjeve
101101
10 110 1
0 11 0
001 10
001 01
Va|r-C|ass: V|r|App
PackageExerc|se.c|ass
com
heedfirstjeve
101101
10 110 1
0 11 0
001 10
001 01
PackageExerc|se.c|ass
A|| ]-- :-:] : l-
:-- --:l--]' A- ]--'||
-l ---]l- - l'
The onIy fhing you need fo incIude is fhe 'com'
direcfory, ond fhe enfire pockoge (ond oII cIosses)
wiII go info fhe JAP.
JARs and packages
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 593
8e whcrc 4|4 !hc mzn|fcs! f||c ]e!
~l :l.-: -- '1.|- ||-' .: -
:-- -- . l.|- - l- )A |-'
-- -l l- )A
|- -l- .
--:l--] -.-- ]|--
Why uon`i wc looI insiuc ihc ]AR anu hnu oui. Iiom ihc
commanu-linc, ihc |ai iool can uo moic ihan |usi cicaic anu iun a
]AR. You can cxiiaci ihc conicnis ol a ]AR |usi liIc unziing` oi
uniaiiing`).
Imaginc you`vc ui ihc acIEx.|ai inio a uiiccioiy namcu SIylci.
eckEx.jer
]ar commands for listing and extracting
1
List the contents of u JAP
% jar -tf packEx.jar
File Edit Window Help Pickle
% cd Skyler
% jar -tf packEx.jar
META-INF/
META-INF/MANIFEST.MF
com/
com/headfirstjava/
com/headfirstjava/
PackageExercise.class
~ :l.-: -- '!l-.:l ||-' .- l
---: -:l |- ---- -- --l.---
| ]-- -l-.:l l- .:!.-, ]--'||
:-- l- M!1A~|N| --:l--] .- l-
:-- --:l--] --:l--] - ]--- :-----l
--:l--]
2
Etruct the contents of u JAP {i,e, unjur}
% cd Skyler
% jar -xf packEx.jar
HAN|FE8T.HF
Va|r-C|ass: V|r|App
com
heedfirstjeve
PackageExerc|se.c|ass
YE7A-/hF
8ky|er
l- .- l--| .-l--.l:.||]
-|: . M
!1
A
~|N|
--:l--], .- -l: l-
-.--:l -:-
101101
10 110 1
0 11 0
001 10
001 01
8ky|er
HAN|FE8T.HF
Va|r-C|ass: V|r|App
com
heedfirstjeve
YE7A-/hF
PackageExerc|se.c|ass
101101
10 110 1
0 11 0
001 10
001 01
META-IMF sfonds for 'mefo
informofion'. The jor fooI creofes
fhe META-IMF direcfory os
weII os fhe MAMIFEST.MF fIe.
If oIso fokes fhe confenfs of
your monifesf fIe, ond pufs if
info fhe MAMIFEST.MF fIe. So,
your monifesf fIe doesn'f go info
fhe JAP, buf fhe confenfs of if
ore puf info fhe 'reoI' monifesf
(MAMIFEST.MF).
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
organizing your cIasses
594 chapter 17
+,-+ :+ ,-+:.|
Foof.c|ass
c|asses
101101
10 110 1
0 11 0
001 10
001 01
Given the package/directory structure in this
picture, gure out what you should type at the
command-line to compile, run, create a 1AP, and
execute a 1AP. Assume we're using the standard
where the package directory structure starts |ust
below soutce and closses. |n other words, the soutce
and closses directories are not part of the package.
%cd source
%javac ________________________________
javaranch
cows
CompiIe:
%cd ___________
%java _________________________________
Pun:
%cd ___________
%______________________________________
Creute u JAP
man|fest.txt
Va|r-C|ass: V|r|App
source
javaranch
cows
Lorper
iure
eugue
tat vero
conse
euguero-
Foof.java
HyProject
%cd ___________
% _____________________________________
Eecute u JAP
8onus question: what's wrong with the package nameI
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 595
8ll P0lk5
0rar|ze your projecl so l|al your source code ard c|ass l||es are rol |r
l|e sare d|reclory.
A slardard orar|zal|or slruclure |s lo creale a rojeor d|reclory, ard l|er
pul a souroe d|reclory ard a o|asses d|reclory |rs|de l|e projecl d|reclory.
0rar|z|r your c|asses |rlo pac|aes preverls rar|r co|||s|ors W|l|
ol|er c|asses, |l you preperd your reverse dora|r rare or lo l|e lrorl ol
a c|ass rare.
To pul a c|ass |r a pac|ae, pul a pac|ae slalererl al l|e lop ol l|e
source code l||e, oelore ary |rporl slalererls:
package com.wickedlysmart;
To oe |r a pac|ae, a c|ass rusl oe |r a o|reorory srruorure rnar exaor|y
marones rne aokage srruorure. For a c|ass, cor.W|c|ed|ysrarl.Foo,
l|e Foo c|ass rusl oe |r a d|reclory rared u|okeo|ysmarr, W||c| |s |r a
d|reclory rared oom.
To ra|e your corp||ed c|ass |ard |r l|e correcl pac|ae d|reclory
slruclure urder l|e o|asses d|reclory, use l|e -d corp||er l|a:
% cd source
javac -d ../classes com/wickedlysmart/Foo.java
To rur your code, cd lo l|e c|asses d|reclory, ard |ve l|e lu||y-qua||l|ed
rare ol your c|ass:
% cd classes
java com.wickedlysmart.Foo
You car ourd|e your c|asses |rlo JAR (Java ARc||ve) l||es. JAR |s oased
or l|e p|z|p lorral.
You car ra|e ar execulao|e JAR l||e oy pull|r a rar|lesl |rlo l|e JAR
l|al slales W||c| c|ass |as l|e ra|r() rel|od. To creale a rar|lesl l||e,
ra|e a lexl l||e W|l| ar erlry |||e l|e lo||oW|r (lor exarp|e):
Main-Class: com.wickedlysmart.Foo
8e sure you ||l l|e relurr |ey aller lyp|r l|e Va|r-C|ass ||re, or your
rar|lesl l||e ray rol Wor|.
To creale a JAR l||e, lype:
jar -cvfm manifest.txt MyJar.jar com
T|e erl|re pac|ae d|reclory slruclure (ard on|y l|e d|reclor|es ralc||r
l|e pac|ae) rusl oe |rred|ale|y |rs|de l|e JAR l||e.
To rur ar execulao|e JAR l||e, lype:
java -jar MyJar.jar
(-,- a,- |
oa|| qa--(:|-

What happens if you try


to run an executabIe 1AR, and
the end-user doesn't have java
instaIIed!
Nothing will run, since
without a 1vM, 1ava code can't
run. The end-user must have 1ava
installed.

How can I get 1ava
instaIIed on the end-user's
machine!
|deally, you can create a custom
installer and distribute it along
with your application. Several
companies offer installer pro-
grams ranging from simple to
extremely powerful. An installer
program could, for example, de-
tect whether or not the end-user
has an appropropriate version
of 1ava installed, and if not,
install and configure 1ava before
installing your application.
|nstallshield, |nstallAnywhere,
and DeployDirector all offer 1ava
installer solutions.
Another cool thing about some
of the installer programs is that
you can even make a deploy-
ment CD-POM that includes
installers for all ma|or 1ava
platforms, so... one CD to rule
them all. |f the user's running on
Solaris, for example, the Solaris
version of 1ava is installed. On
windows, the windows, ver-
sion, etc. |f you have the budget,
this is by far the easiest way for
your end-users to get the right
version of 1ava installed and
configured.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
596 chapter 17
ExecufobIe JAP fIes
ore nice, buf wouIdn'f if be dreomy
if fhere were o woy fo moke o rich, sfond-
oIone cIienf 0UI fhof couId be disfribufed
over fhe Web7 So fhof you wouIdn'f hove fo
press ond disfribufe oII fhose CD-POMs. And
wouIdn'f if be jusf wonderfuI if fhe progrom
couId oufomoficoIIy updofe ifseIf, repIocing
jusf fhe pieces fhof chonged7 The cIienfs
wouId oIwoys be up-fo-dofe, ond you'd never
hove fo worry obouf deIivering new
wouIdn't it be dreamy...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 597
Wiih ]ava Wcl Siaii ]WS), youi alicaiion is launchcu loi ihc
hisi iimc liom a Wcl liowsci gci ii. Veb Sn..) lui ii iuns as a
sianu-alonc alicaiion wcll, nIo), wiihoui ihc consiiainis ol ihc
liowsci. Anu oncc ii`s uownloaucu io ihc cnu-usci`s machinc which
hacns ihc hisi iimc ihc usci acccsscs ihc liowsci linI ihai siaiis
ihc uownloau), ii n, ihcic.
]ava Wcl Siaii is, among oihci ihings, a small ]ava iogiam ihai livcs
on ihc clicni machinc anu woiIs much liIc a liowsci lug-in ihc
way, say, Auolc Aciolai Rcauci ocns whcn youi liowsci gcis a .ul
hlc). This ]ava iogiam is callcu ihc ]ava Wcb Start 'hclpcr app',
anu iis Icy uiosc is io managc ihc uownloauing, uuaiing, anu
launching cxccuiing) ol ,ou. ]WS as.
Whcn ]WS uownloaus youi alicaiion an cxccuiallc ]AR), ii
invoIcs ihc main) mcihou loi youi a. Alici ihai, ihc cnu-usci can
launch youi alicaiion uiiccioiy liom ihc ]WS hclci a w.Lou
having io go lacI ihiough ihc Wcl agc linI.
Bui ihai`s noi ihc lcsi aii. Thc amazing ihing aloui ]WS is iis
aliliiy io ucicci whcn cvcn a small aii ol alicaiion say, a singlc
class hlc) has changcu on ihc scivci, anu-wiihoui any cnu-usci
inicivcniion-uownloau anu inicgiaic ihc uuaicu couc.
Thcic`s siill an issuc, ol couisc, liIc how uocs ihc cnu-usci e ]ava
anu ]ava Wcl Siaii. Thcy nccu loih-]ava io iun ihc a, anu ]ava
Wcl Siaii a small ]ava alicaiion iiscll) io hanulc iciiicving anu
launching ihc a. Bui cvcn Ln has lccn solvcu. You can sci ihings
u so ihai il youi cnu-uscis uon`i havc ]WS, ihcy can uownloau
ii liom Sun. Anu il ihcy Jo havc ]WS, lui ihcii vcision ol ]ava is
oui-ol-uaic lccausc you`vc sccihcu in youi ]WS a ihai you
nccu a sccihc vcision ol ]ava), ihc ]ava 2 Sianuaiu Euiiion can lc
uownloaucu io ihc cnu-usci machinc.
Bcsi ol all, ii`s simlc io usc. You can scivc u a ]WS a much liIc
any oihci iyc ol Wcl icsouicc such as a lain olu HTMI agc oi a
]PEG imagc. You sci u a Wcl HTMI) agc wiih a linI io youi ]WS
alicaiion, anu you`ic in lusincss.
In ihc cnu, youi ]WS alicaiion isn`i much moic ihan an
cxccuiallc ]AR ihai cnu-uscis can uownloau liom ihc Wcl.
1zvz Wc| 8!zr!
100% LocuI Combinution 100% Pemote
8erv|ets

web 8tart
FiIe Edit View

RH| app
FiIe Edit View

Executab|e
Jar
FiIe Edit View
web 8tart
FiIe Edit View

[n]-a,, ]zane[ z ]zvz


y (z( z y e]je[jng
n z ]jn[ jn z y
zg. @a( ne ([ z
]wn]z],, j( an, a(,j]
([ w,, ja,( ]j[ zny
([ ,(zn]-z]n ]zvz
z]jez(jn. ]n |ze(, z
]zvz y (z( z j, ja,(
zn yea(z] ]j ([z(',
]j,(ja(] v ([ y.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
598 chapter 17
How Java Web 8tart works
1
The cIient cIicks on u Web puge Iink
to your JWS uppIicution {u ,jnIp hIe},
The Web poge Iink
<a href=MyApp.jnlp>Click</a>

2
The Web server {HTTP} gets the
request und sends buck u ,jnIp hIe
{this is NOT the JAP},
Web 8erver
Lorper
iure
eugue
tat vero
conse
euguero-
HyApp.jn|p HyApp.jar
click
3
Juvu Web Sturt {u smuII 'heIper upp'
on the cIient} is sturted up by the
browser, The JWS heIper upp reuds
the ,jnIp hIe und usks the server for
the MyApp,jur hIe,
The .jnIp fIe is on XML documenf fhof
sfofes fhe nome of fhe oppIicofion's
execufobIe JAP fIe.
click
Lorper
iure
eugue
tat vero
conse
euguero-
HyApp.jn|p HyApp.jar
Lorper
iure
eugue
tat vero
conse
euguero-
HyApp.jn|p
Web 8erver
JW8
Web 8erver
Lorper
iure
eugue
tat vero
conse
euguero-
HyApp.jn|p
"give me MyApp.jor"
HyApp.jar
4
The Web server 'serves' up the
requested ,jur hIe,
JW8
Web 8erver
Lorper
iure
eugue
tat vero
conse
euguero-
HyApp.jn|p HyApp.jar
5
Juvu Web Sturt gets the JAP und
sturts the uppIicution by cuIIing the
specihed muin{ } method {just Iike un
eecutubIe JAP},
Hello
Web 8erver
Lorper
iure
eugue
tat vero
conse
euguero-
HyApp.jn|p HyApp.jar
HyApp.jar
"give me MyApp.jnIp"
w- ---:--
).. w- l.-l
+-||-w-l.-l |l- . - l- )A`
Mexf fime fhe user wonfs fo run fhis opp, he con
open fhe Jovo Web Sforf oppIicofion ond from
fhere Iounch your opp, wifhouf even being onIine.
Java Web Start
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 599
To maIc a ]ava Wcl Siaii a, you nccu io .|nl ]ava NciwoiI
Iaunch Pioiocol) hlc ihai ucsciilcs youi alicaiion. This is ihc
hlc ihc ]WS a icaus anu uscs io hnu youi ]AR anu launch ihc
a ly calling ihc ]AR`s main) mcihou). A .|nl hlc is a simlc
XMI uocumcni ihai has scvcial uillcicni ihings you can ui in,
lui as a minimum, ii shoulu looI liIc ihis:
Ihc .jn|p f||c
<?xml version=1.0 encoding=utf-8?>
<jnlp spec=0.2 1.0
codebase=http://127.0.0.1/~kathy
href=MyApp.jnlp>
<information>
<title>kathy App</title>
<vendor>Wickedly Smart</vendor>
<homepage href=index.html/>
<description>Head First WebStart demo</description>
<icon href=kathys.gif/>
<ofine-allowed/>
</information>
<resources>
<j2se version=1.3+/>
<jar href=MyApp.jar/>
</resources>
<application-desc main-class=HelloWebStart/>
</jnlp>
1
- ':-
-.:-' l. : -
--- ]-- :-:
] l- '---l'
-
-
--- ]--- -
- :l.-l :l-

: -- l- :----
w
-'-- l-:l- l: -- --- |-:.|-:l, :- -
-'-- -:-
l- |-:.| |--.: .

--:: |i
7
o
o
|' |
-- -
-
:l.-l .: -- --- -l----l -
- :----, l: -
--|

:.], ll//-
-
-
-
:-
|]:-
.-l:--
'
1: : l- |-:.l-- - l- -| |- --|.l- l- l-
:--.:- 1: -.-|- :--: l.l M]A-| :
..|.|- - l- ---l --:l--] - l- -- :----, --l
--:l- - :--- -l-- --:l--]
B- :--- l- -:|-- .|| - l-:- l.:, -- ]--- . -l
--l --- :----:l|]' 1- '----.l--' l.: .-- -:- ]
l- )w -|-- ., --:l|] -- :|.]- --- l- -:--
-.-l: l- --|.--: . ----:|]~---|-.- .|:.l--
1: --.-: l- -:-- :.- --- ]--- ---.- -l--l
-- :----:l- l- l- -l----l | l- -:-- : -|--,
l --.-: l- .-l--.l:~-.l- -.l--- ---'l ---
1: :.]: l.l ]--- . ---: --:-- |?
- ).., -- --.l--
1- -.-- - ]--- --:-l.|- )A' /-- -l .-
-l-- )A |-: .: --||, l.l -| -l-- :|.::-: --
--- :---: .- -.-: -:- ] ]--- .
1: : |- l- -.--:l M.-~c|.:: --l-] l :.]:
-: :|.:: - l- )A .: l- -.-|` --l-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
600 chapter 17
8teps for making and deploying
a Java Web 8tart app
1 Muke un eecutubIe JAP
for your uppIicution,
HyApp.jar
2 Write u ,jnIp hIe,
Lorper
iure
eugue
tat vero
conse
euguero-
HyApp.jn|p
3
Web 8erver
HyApp.jar
Lorper
iure
eugue
tat vero
conse
euguero-
roo.htm|
Lorper
<iure
eugue
tat vero
conse
HyApp.jn|p
PIuce your JAP und ,jnIp
hIes on your Web server,
4 Add u new mime type to your Web server,
This couses fhe server fo send fhe .jnIp fIe wifh fhe
correcf heoder, so fhof when fhe browser receives
fhe .jnIp fIe if knows whof if is ond knows fo sforf
fhe JWS heIper opp.
application/x-java-jnlp-le
Web 8erver
conhgure
mime type
5 Creute u Web puge with u Iink
to your ,jnIp hIe
<HTML>
<BODY>
<a href=MyApp2.jnlp>Launch My Application</a>
</BODY>
</HTML>
Lorper
iure
eugue
tat vero
conse
euguero-
HyJw8App.htm|
depIoying with JWS
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 601
yg'z
]j;z/
8ll P0lk5
Java weo 3larl lec|ro|oy |els you dep|oy a
slard-a|ore c||erl app||cal|or lror l|e weo.
Java weo 3larl |rc|udes a '|e|per app' l|al rusl
oe |rsla||ed or l|e c||erl (a|or W|l| Java).
A Java weo 3larl (Jw3) app |as lWo p|eces:
ar execulao|e JAR ard a .jr|p l||e.
A .jr|p l||e |s a s|rp|e XVL docurerl l|al
descr|oes your Jw3 app||cal|or. ll |rc|udes
las lor spec|ly|r l|e rare ard |ocal|or ol l|e
JAR, ard l|e rare ol l|e c|ass W|l| l|e ra|r()
rel|od.
w|er a oroWser els a .jr|p l||e lror l|e server
(oecause l|e user c||c|ed or a ||r| lo l|e .jr|p
l||e), l|e oroWser slarls up l|e Jw3 |e|per app.
T|e Jw3 |e|per app reads l|e .jr|p l||e ard
requesls l|e execulao|e JAR lror l|e weo
server.
w|er l|e Jw3 els l|e JAR, |l |rvo|es l|e
ra|r() rel|od (spec|l|ed |r l|e .jr|p l||e).
l.
2.
3.
4.
5.
6.
7.
Look at the sequence of events below, and
place them in the order in which they
occur in a 1wS application.
user c||c|s a weo pae ||r|
oroWser requesls a .jr|p l||e
lror l|e weo server
l|e weo server serds a .jr|p
l||e lo l|e oroWser
l|e weo oroWser slarls up
l|e Jw3 |e|per app
l|e Jw3 |e|per app requesls
l|e JAR l||e
l|e weo server serds a JAR
l||e lo l|e Jw3 |e|per app
l|e Jw3 |e|per app |rvo|es
l|e JAR's ra|r() rel|od
(-,- a,- |
oa|| qa--(:|-
How is 1ava Web Start different from an appIet!

Applets can't live outside of a web browser. An applet is
downloaded from the web as part of a web page rather than
simply from a web page. |n other words, to the browser, the applet
is |ust like a 1PLG or any other resource. The browser uses either a
1ava plug-in or the browser's own built-in 1ava (far less common
today) to run the applet. Applets don't have the same level of
functionality for things such as automatic updating, and they must
always be launched from the browser. with 1wS applications, once
they're downloaded from the web, the user doesn't even have to
be using a browser to relaunch the application locally. |nstead,
the user can start up the 1wS helper app, and use it to launch the
already-downloaded application again.
What are the security restrictions of 1WS!

1wS apps have several limitations including being
restricted from reading and writing to the user's hard drive. 8ut...
1wS has its own AP| with a special open and save dialog box so
that, with the user's permission, your app can save and read its
own files in a special, restricted area of the user's drive.

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
602 chapter 17

we explored packaging, deployment, and 1wS


in this chapter. our |ob is to decide whether
each of the following statements is true or false.
1. Thc ]ava comilci has a uag, -u, ihai lcis you ucciuc whcic youi .class hlcs shoulu go.
2. A ]AR is a sianuaiu uiiccioiy whcic youi .class hlcs shoulu icsiuc.
S. Whcn cicaiing a ]ava Aichivc you musi cicaic a hlc callcu |ai.ml.
4. Thc suoiiing hlc in a ]ava Aichivc ucclaics which class has ihc main) mcihou.
. ]AR hlcs musi lc unzicu lcloic ihc ]VM can usc ihc classcs insiuc.
6. Ai ihc commanu linc, ]ava Aichivcs aic invoIcu using ihc -aich uag.
7. PacIagc siiuciuics aic mcaninglully icicscnicu using hiciaichics.
S. Using youi comany`s uomain namc is noi iccommcnucu whcn naming acIagcs.
9. Dillcicni classcs wiihin a souicc hlc can lclong io uillcicni acIagcs.
10. Whcn comiling classcs in a acIagc, ihc - uag is highly iccommcnucu.
11. Whcn comiling classcs in a acIagc, ihc lull namc musi miiioi ihc uiiccioiy iicc.
12. ]uuicious usc ol ihc -u uag can hcl io assuic ihai ihcic aic no iyos in youi class iicc.
1S. Exiiaciing a ]AR wiih acIagcs will cicaic a uiiccioiy callcu mcia-inl.
14. Exiiaciing a ]AR wiih acIagcs will cicaic a hlc callcu manilcsi.ml.
1. Thc ]WS hclci a always iuns in con|unciion wiih a liowsci.
16. ]WS alicaiions icquiic a .nl NciwoiI Iaunch Pioiocol) hlc io woiI iocily.
17. A ]WS`s main mcihou is sccihcu in iis ]AR hlc.
fs-s cs |s.ss
exercise: True or FaIse
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 603
ajj|i(iss ).c
Anything in the book
is fair game for this
one!

l. Pushy widgets
2. ____ of my desire
3. 'Abandoned' moniker
4. A chunk
5. Math not trig
6. 8e brave
7. Arrange well
8. Swing slang
ll. |/O canals
l3. Organized release
l4. Not for an instance

6. won't travel
9. Don't split me
l0. Pelease-able
ll. Got the key
l2. |/O gang
l5. Platten
l7. Lncapsulated returner
l8. Ship this one
2l. Make it so
22. |/O sieve
25. Disk leaf
26. Mine is unique
27. GU|'s target
29. 1ava team
30. Pactory
32. Por a while
33. Atomic ` 8
35. Good as new
37. Pairs event
4l. where do | start
42. A little rewall
l6. who's allowed
l9. Lfciency expert
20. Larly exit
2l. Common wrapper
23. es or no
24. 1ava |ackets
26. Not behavior
28. Socket's suite
l
l7
25
29
33
4l 42
2 3 4 5 6 7 8
ll
l2 l4 l5 l6
20 2l 22
26 27
30 32
34 35 36 37 38 39
24
3l
l8
l0
9
l9
l3
23
28
40
30. |/O cleanup
3l. Milli-nap
34. Trig method
36. Lncaps method
38. 1NLP format
39. v8's nal
40. 1ava branch

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
604 chapter 17

user c||c|s a weo pae ||r|


oroWser requesls a .jr|p l||e
lror l|e weo server
l|e weo server serds a .jr|p
l||e lo l|e oroWser
l|e weo oroWser slarls up
l|e Jw3 |e|per app
l|e Jw3 |e|per app requesls
l|e JAR l||e
l|e weo server serds a JAR
l||e lo l|e Jw3 |e|per app
l|e Jw3 |e|per app |rvo|es
l|e JAR's ra|r() rel|od
1. Thc ]ava comilci has a u ag, -u, ihai lcis you ucciuc whcic youi .class h lcs shoulu go.
2. A ]AR is a sianuaiu uiiccioiy whcic youi .class h lcs shoulu icsiuc.
S. Whcn cicaiing a ]ava Aichivc you musi cicaic a h lc callcu |ai,ml.
4. Thc suoiiing h lc in a ]ava Aichivc ucclaics which class has ihc main) mcihou.
. ]AR h lcs musi lc unzicu lcloic ihc ]VM can usc ihc classcs insiuc.
6. Ai ihc commanu linc, ]ava Aichivcs aic invoIcu using ihc -aich u ag.
7. PacIagc siiuciuics aic mcaninglully icicscnicu using hiciaichics.
S. Using youi comany`s uomain namc is noi iccommcnucu whcn naming acIagcs.
9. Dillcicni classcs wiihin a souicc h lc can lclong io uillcicni acIagcs.
10. Whcn comiling classcs in a acIagc, ihc - u ag is highly iccommcnucu.
11. Whcn comiling classcs in a acIagc, ihc lull namc musi miiioi ihc uiiccioiy iicc.
12. ]uuicious usc ol ihc -u u ag can hcl io assuic ihai ihcic aic no iyos in youi iicc.
1S. Exiiaciing a ]AR wiih acIagcs will cicaic a uiiccioiy callcu mcia-inl.
14. Exiiaciing a ]AR wiih acIagcs will cicaic a h lc callcu manilcsi.ml.
1. Thc ]WS hclci a always iuns in con|unciion wiih a liowsci.
16. ]WS alicaiions icquiic a .nl NciwoiI Iaunch Pioiocol) h lc io woiI iocily.
17. A ]WS`s main mcihou is sccih cu in iis ]AR h lc.

]e;ejze
o|ajoz
exercise soIutions
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 605
l
l7
25
29
33
4l 42
2 3 4 5 6 7 8
ll
l2 l4 l5 l6
20 2l 22
26 27
30 32
34 35 36 37 38 39
24
3l
l8
l0
9
l9
l3
23
28
40
ajj|i(iss ).c
D O 0 T M T P A M S I E M T W
I 8 A T O M I C P O I
A J A P I M S Y M C H P O M I Z E D
L E 8 E T T 0
O C H A I M E D P S S A V E
0 E T 0 E X E C U T A 8 L E C T
S E P A A U C S
8 I M P L E M E M T F I L T E P
8 P M O I F S W
D I P E C T O P Y S O C I E T U S E P
M A E T P P A
P A C I A 0 E C L A S S L O O P P
P E L T L P P
8 Y T E P E S T O P E E E X T P E M E
A I E S E M X P
M A M I F E S T E M C A P S U L A T E S
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 607
Being remote doesn't have to be a bad thing. Sure, things ote easier when
all the parts of your application are in one place, in one heap, with one 1vM to rule them all. 8ut
that's not always possible. Or desirable. what if your application handles powerful computations,
but the end-users are on a wimpy little 1ava-enabled deviceI what if your app needs data
from a database, but for security reasons, only code on your server can access the databaseI
|magine a big e-commerce back-end, that has to run within a transaction-management systemI
Sometimes, part of your app must run on a server, while another part (usually a client) must
run on a J|lletent machine. |n this chapter, we'll learn to use 1ava's amazingly simple Pemote
Method |nvocation (PM|) technology. we'll also take a quick peek at Servlets, Lnterprise 1ava
8eans (L18) , and 1ini, and look at the ways in which L18 and 1ini JeenJ on PM|. we'll end the
book by writing one of the coolest things you can make in 1ava, a un|vetsol setv|ce otowset.
Distributed
Computing
18 remote depIoyment with RMI
Everyone soys Iong-
disfonce reIofionships ore hord,
buf wifh PMI, if's eosy. Mo
moffer how for oporf we reoIIy
ore, PMI mokes if seem Iike
we're fogefher.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
608 chapter 18
100% LocuI Combinution 100% Pemote
8erv|ets
HTTP
web 8tart
FiIe Edit View
HTTP
RH| app
FiIe Edit View
RMI
Executab|e
Jar
FiIe Edit View
RH| app
FiIe Edit View
RMI
So lai in ihis looI, cvciy mcihou wc`vc invoIcu has lccn on
an ol|cci iunning in ihc samc viiiual machinc as ihc callci.
In oihci woius, ihc calling ol|cci anu ihc callcc ihc ol|cci
wc`ic invoIing ihc mcihou on) livc on ihc samc hca.
Mc!he4 rz||s zrc z| wzys |c! wccn
! we e|jcr!s en !hc szmc hczp.
class Foo {
void go() {
Bar b = new Bar();
b.doStuff();
}
public static void main (String[] args) {
Foo f = new Foo();
f.go();
}
}
F
o
o obj
e
c
f
8
o
r obj
e
c
f

d
o
S
f
u
f
f
(
)
In mosf oppIicofions, when one objecf
coIIs o mefhod on onofher, bofh objecfs
ore on fhe some heop. In ofher words,
bofh ore running wifhin fhe some JVM.
--- -., l
-
- --:l
:
In ihc couc alovc, wc Inow ihai ihc Ioo insiancc
iclcicnccu ly anu ihc Bai ol|cci iclcicnccu ly b aic
loih on ihc samc hca, iun ly ihc samc ]VM. Rcmcmlci,
ihc ]VM is icsonsillc loi siulhng liis inio ihc iclcicncc
vaiiallc ihai icicscni Low o e o nr obe or Le Len.
Thc ]VM always Inows whcic cach ol|cci is, anu how io
gci io ii. Bui ihc ]VM can Inow aloui iclcicnccs on only
iis owr hca! You can`i, loi cxamlc, havc a ]VM iunning
on onc machinc Inowing aloui ihc hca sacc ol a ]VM
iunning on a J.e.er machinc. In laci, a ]VM iunning on
onc machinc can`i Inow anyihing aloui a uillcicni ]VM
iunning on ihc ne machinc. Ii maIcs no uillcicncc il
ihc ]VMs aic on ihc samc oi uillcicni hysical machincs,
ii maiicis only ihai ihc iwo ]VMs aic, wcll, iwo uillcicni
invocaiions ol ihc ]VM.
how many heaps?
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 609
Wc Inow how io gci inloimaiion liom onc machinc io anoihci-
wiih SocIcis anu I/O. Wc ocn a SocIci conncciion io anoihci
machinc, anu gci an OuiuiSiicam anu wiiic somc uaia io ii.
Bui whai il wc aciually wani io nII n eLoJ on somcihing iunning
in anoihci machinc... anoihci ]VM. Ol couisc wc coulu always luilu
oui own ioiocol, anu whcn you scnu uaia io a ScivciSocIci ihc
scivci coulu aisc ii, hguic oui whai you mcani, uo ihc woiI, anu
scnu lacI ihc icsuli on anoihci siicam. Whai a ain, ihough. ThinI
how much nicci ii woulu lc io |usi gci a iclcicncc io ihc ol|cci on
ihc oihci machinc, anu call a mcihou.
Whz! |f yee wzn! !e |nvekc z mc!he4 en
zn e|jcr! renn|n] en zne!hcr mzrh|nc!
!ag:ae tva :aate:s...
5:g has saeth:ag I:tt|e vaats.
Caate ave:.
I:tt|e vaats ta seaJ sae Jata ta 5:g, sa that 5:g :aa Ja the
heavy :aat:ag.
I:tt|e vaats s:|y ta :a|| a ethaJ...
double doCalcUsingDatabase(CalcNumbers numbers)
aaJ get la:| the :esa|t.
5at hav :aa I:tt|e get a :eIe:ea:e ta aa ale:t aa 5:g!
LiffIe 8ig
-----|, .:l, |--:
l- :---: l---
:.|:-|.l--:
l-], --], .--||]
:|-- .l :.|:-|.l--:
JVM
JVM
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
two objects, two heaps
610 chapter 18

Thc qucsiion is, how uo wc gci an ol|cci on onc machinc
which mcans a uillcicni hca/]VM) io call a mcihou on
anoihci machinc.

0|jcr! , renn|n] en I| !!|c, wzn!s !e rz||
z mc!he4 en 0|jcr! B, renn|n] en B|].
A
8
doCoIcUsingDofobose()
refurn voIue
Wcll, noi uiiccily anyway. You can`i gci a iclcicncc io
somcihing on anoihci hca. Il you say:
Dog u ...
Whaicvci J is iclcicncing musi lc in ihc samc hca sacc as
ihc couc iunning ihc siaicmcni.
Bui imaginc you wani io ucsign somcihing ihai will usc
SocIcis anu I/O io communicaic youi inicniion a mcihou
invocaiion on an ol|cci iunning on anoihci machinc), yci
siill eeI as ihough you wcic maIing a local mcihou call.
In oihci woius, you wani io causc a mcihou invocaiion on a
.eoe ol|cci i.c., an ol|cci in a hca somcwhcic clsc), lui
wiih couc ihai lcis you .eerJ ihai you`ic invoIing a mcihou
on a local ol|cci. Thc casc ol a lain olu cvciyuay mcihou
call, lui ihc owci ol icmoic mcihou invocaiion. Thai`s oui
goal.
Thai`s whai RMI Rcmoic Mcihou Invocaiion) givcs you!
Bui lci`s sic lacI anu imaginc how you woulu ucsign RMI il
you wcic uoing ii youiscll. Unucisianuing whai you`u havc io
luilu youiscll will hcl you lcain how RMI woiIs.
Be! yee rzn! 4e !hz!.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 611
A design for remote method calls
Create four things: server, client,
server helper, client helper
1
Creofe cIienf ond server opps. The server opp is fhe
remote service fhof hos on objecf wifh fhe mefhod
fhof fhe cIienf wonfs fo invoke.
S
e
r
v
ice o
b
j
e
c
f

Server heup
C
I
i
e
n
f ob
j
e
c
f

CIient heup
2
Creofe cIienf ond server 'heIpers'. They'II hondIe oII
fhe Iow-IeveI nefworking ond I/O defoiIs so your cIienf
ond service con prefend Iike fhey're in fhe some heop.
S
e
r
v
ice o
b
j
e
c
f

Server heup
C
I
i
e
n
f ob
j
e
c
f

CIient heup
C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
612 chapter 18
Thc hclcis` aic ihc ol|ccis ihai aciually uo ihc communicaiing.
Thcy maIc ii ossillc loi ihc clicni io n as ihough iis calling a
mcihou on a local ol|cci. In laci, ii .. Thc clicni calls a mcihou on
ihc clicni hclci, n . Le I.er LeIe. we.e Le nunI e...e. TLe I.er
LeIe. . n .o:, o. Le FenI TL.r.
In oihci woius, ihc clicni ol|cci L.rI ii`s calling a mcihou on
ihc icmoic scivicc, lccausc ihc clicni hclci is .eerJ.r io lc
ihc scivicc ol|cci. Pretending to be the thing with the method the cIient
wonts to coII:
Bui ihc clicni hclci isn`i ically ihc icmoic scivicc. Alihough ihc
clicni hclci n liIc ii lccausc ii has ihc samc mcihou ihai ihc
scivicc is auvciiising), ihc clicni hclci uocsn`i havc any ol ihc
aciual mcihou logic ihc clicni is cxcciing. Insicau, ihc clicni
hclci coniacis ihc scivci, iianslcis inloimaiion aloui ihc mcihou
call c.g., namc ol ihc mcihou, aigumcnis, cic.), anu waiis loi a
iciuin liom ihc scivci.
On ihc scivci siuc, ihc scivicc hclci icccivcs ihc icqucsi liom
ihc clicni hclci ihiough a SocIci conncciion), unacIs ihc
inloimaiion aloui ihc call, anu ihcn invoIcs ihc .enI mcihou on
ihc .enI scivicc ol|cci. So io ihc scivicc ol|cci, ihc call is local. Ii`s
coming liom ihc scivicc hclci, noi a icmoic clicni.
Thc scivicc hclci gcis ihc iciuin valuc liom ihc scivicc, acIs ii
u, anu shis ii lacI ovci a SocIci`s ouiui siicam) io ihc clicni
hclci. Thc clicni hclci unacIs ihc inloimaiion anu iciuins ihc
valuc io ihc clicni ol|cci.
Ihc re|c ef !hc 'hc|pcrs
(a e]jn( je( g(, (
ze( ]j[ j(', z[jng (
([] ez]],. @a( w[z(
j(', z]]y ]jng j, ez]]jng
([], n z [z-]ez]
'yy' je( ([z( [zn]],
z]] ([ ]w-]v] ](zj], |
e[(, zn] ,(z,.
S
e
r
v
ice o
b
j
e
c
f

Server heup
C
I
i
e
n
f ob
j
e
c
f

CIient heup
C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
c|--l --:l l-:
l': l.|- l- l-
-.| --:- |l
l-: l- :|--l
-|-- : l- l-
l.l :.- .:l-.||]
- l- --.| ---
c|--l -|-- --l--:
l- - l- :--:-, -l
l': -:l . --] -- l-
-.| 1-
--:- -|-- -l: l-
----:l --- l- :|--l
-|--, --.:: l, .-
:.||: l- --l- -- l-
-.| --:-
1
- --:- --:l |
l-
-.| --:- |l': l-
--:l -
l l- -
-l-
l.l .:l-.||] --: l-
--.| -
-l- -
--
cIient and server heIpers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 613
S
e
r
v
ice o
b
j
e
c
f

Server heup
C
I
i
e
n
f ob
j
e
c
f

CIient heup
C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
How the method call happens
1 CIienf objecf coIIs do8igThing() on fhe cIienf heIper objecf
S
e
r
v
ice o
b
j
e
c
f

Server heup
C
I
i
e
n
f ob
j
e
c
f

CIient heup
C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
2 CIienf heIper pockoges up informofion obouf fhe coII
(orgumenfs, mefhod nome, efc.) ond ships if over fhe
nefwork fo fhe service heIper.
do8igThing()
do8igThing()
"cIienf wonfs fo coII o mefhod"
S
e
r
v
ice o
b
j
e
c
f

Server heup
C
I
i
e
n
f ob
j
e
c
f

CIient heup
C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
3 Service heIper unpocks fhe informofion from fhe cIienf heIper,
fnds ouf which mefhod fo coII (ond on which objecf) ond
invokes fhe reoI mefhod on fhe reoI service objecf.
do8igThing()
"cIienf wonfs fo coII o mefhod"
do8igThing()
------, l: : l-
--:l -l l- !A|
--l- |-: 1- -]
l.l --: l- --.| ---'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
614 chapter 18
In ]ava, RMI luilus ihc clicni anu scivicc hclci
ol|ccis loi you, anu ii cvcn Inows how io maIc ihc
clicni hclci looI liIc ihc Rcal Scivicc. In oihci
woius, RMI Inows how io givc ihc clicni hclci
ol|cci ihc samc mcihous you wani io call on ihc
icmoic scivicc.
Plus, RMI ioviucs all ihc iuniimc inliasiiuciuic io
maIc ii woiI, incluuing a looIu scivicc so ihai ihc
clicni can hnu anu gci ihc clicni hclci ihc ioxy
loi ihc Rcal Scivicc).
Wiih RMI, you uon`i wiiic nr, ol ihc nciwoiIing
oi I/O couc youiscll. Thc clicni gcis io call icmoic
mcihous i.c. ihc oncs ihc Rcal Scivicc has) |usi
liIc noimal mcihou calls on ol|ccis iunning in ihc
clicni`s own local ]VM.
Almosi.
Thcic is onc uillcicncc lciwccn RMI calls anu local
noimal) mcihou calls. Rcmcmlci ihai cvcn ihough
io ihc clicni ii looIs liIc ihc mcihou call is local,
ihc clicni hclci scnus ihc mcihou call acioss ihc
nciwoiI. So ihcic is nciwoiIing anu I/O. Anu whai
uo wc Inow aloui nciwoiIing anu I/O mcihous.
Thcy`ic iisIy!
Thcy ihiow cxcciions all ovci ihc lacc.
So, ihc clicni uocs havc io acInowlcugc ihc iisI. Thc
clicni has io acInowlcugc ihai whcn ii calls a icmoic
mcihou, cvcn ihough io ihc clicni ii`s |usi a local call
io ihc ioxy/hclci ol|cci, ihc call uI.neI, involvcs
SocIcis anu siicams. Thc clicni`s oiiginal call is IonI,
lui ihc ioxy iuins ii inio a .eoe call. A icmoic call
|usi mcans a mcihou ihai`s invoIcu on an ol|cci on
anoihci ]VM. How ihc inloimaiion aloui ihai call
gcis iianslciicu liom onc ]VM io anoihci uccnus
on ihc ioiocol uscu ly ihc hclci ol|ccis.
Wiih RMI, you havc a choicc ol ioiocols: ]RMP oi
IIOP. ]RMP is RMI`s naiivc` ioiocol, ihc onc mauc
|usi loi ]ava-io-]ava icmoic calls. IIOP, on ihc oihci
hanu, is ihc ioiocol loi CORBA Common Ol|cci
Rcqucsi BioIci Aichiicciuic), anu lcis you maIc
icmoic calls on ihings which aicn`i ncccssaiily ]ava
ol|ccis. CORBA is usually uL moic ainlul ihan
RMI, lccausc il you uon`i havc ]ava on loih cnus,
ihcic`s an awlul loi ol iianslaiion anu convcision ihai
has io hacn.
Bui ihanIlully, all wc caic aloui is ]ava-io-]ava, so
wc`ic siicIing wiih lain olu, icmaiIally casy RMI.
1zvz KM| ]| vcs yee !hc r||cn! zn4
scrv|rc hc|pcr e|jcr!s|
S
e
r
v
ice o
b
j
e
c
f

C
I
i
e
n
f ob
j
e
c
f

C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
Server heup
CIient heup
PMI STU
PMI SkELETON
n RM, the client helper is a stub'
and the server helper is a skeleton'.
RMI heIper objects
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 615
Server
Making the Remote 8ervice
Moke o Pemote Interfuce
Moke o Pemote ImpIementution
0enerofe fhe stubs ond skeIetons using rmic
Sforf fhe PMI registry (rmiregisfry)
Sforf fhe remote service
HyRemote.java
puo||c |rlerlace
VyRerole exlerds
Rerole {
HyRemote|mp|.java
puo||c |rlerlace
VyRerole exlerds
Rerole {
This is an ol ihc hvc sics loi maIing ihc icmoic
scivicc ihai iuns on ihc scivci). Don`i woiiy, cach sic is
cxlaincu in uciail ovci ihc ncxi lcw agcs.
Thc icmoic inicilacc uchncs ihc mcihous
ihai a clicni can call icmoicly. Ii`s whai
ihc clicni will usc as ihc olymoihic class
iyc loi youi scivicc. Boih ihc Siul anu
aciual scivicc will imlcmcni ihis!
1
: -l--.:- ---: l-
---
-l- -
-l-: l.l ]--
-
.-l :|--l: l- :.||
This is ihc class ihai uocs ihc Rcal WoiI.
Ii has ihc ical imlcmcniaiion ol ihc
icmoic mcihous uchncu in ihc icmoic
inicilacc. Ii`s ihc ol|cci ihai ihc clicni
wanis io call mcihous on.
1- -.| --:- 1- :|.::
-l l- --l-: l.l -
l- --.| --- |l -|----l:
l- ----l- -l--.:-
Thcsc aic ihc clicni anu scivci hclcis`.
You uon`i havc io cicaic ihcsc classcs oi cvci
looI ai ihc souicc couc ihai gcnciaics ihcm.
Ii`s all hanulcu auiomaiically whcn you
iun ihc imic iool ihai shis wiih youi ]ava
ucvclomcni Iii.
File Edit Window Help Eat
%rmic MyRemoteImpl
HyRemote|mp|_8tub.c|ass
HyRemote|mp|_8ke|.c|ass
---- --: ..-:l l- .:l-.|
:--:- -|----l.l-- :|.::
:l: --l l-- ---
:|.::-: -- l-
-|-- --:l:
File Edit Window Help Drink
%rmiregistry
File Edit Window Help BeMerry
%java MyRemoteImpl
Thc is liIc ihc whiic agcs ol a
honc looI. Ii`s whcic ihc usci gocs io gci
ihc ioxy ihc clicni siul/hclci ol|cci).
You havc io gci ihc scivicc ol|cci u anu iunning.
Youi scivicc imlcmcniaiion class insianiiaics an
insiancc ol ihc scivicc anu icgisicis ii wiih ihc RMI
icgisiiy. Rcgisiciing ii maIcs ihc scivicc availallc loi
clicnis.
--- l: - .
:-.-.l- l----.|
8tep one:
8tep two:
8tep three:
8tep four:
8tep hve:
101101
10 110 1
0 11 0
001 10
001 01
101101
10 110 1
0 11 0
001 10
001 01
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
616 chapter 18
8tep one: Make a Remote nterface
1 Etend juvu,rmi,Pemote
HyRemote.java
puo||c |rlerlace
VyRerole exlerds
Rerole {
Rcmoic is a maiIci` inicilacc, which mcans ii has no mcihous. Ii has
sccial mcaning loi RMI, ihough, so you musi lollow ihis iulc. Noiicc
ihai wc say cxicnus` hcic. Onc inicilacc is allowcu io anoihci
inicilacc.
public interface MyRemote extends Remote {
2 DecIore fhof oII mefhods throw u PemoteEception
Thc icmoic inicilacc is ihc onc ihc clicni uscs as ihc olymoihic iyc
loi ihc scivicc. In oihci woius, ihc clicni invoIcs mcihous on somcihing
ihai imlcmcnis ihc icmoic inicilacc. Thai somcihing is ihc siul, ol
couisc, anu sincc ihc siul is uoing nciwoiIing anu I/O, all Iinus ol Bau
Things can hacn. Thc clicni has io acInowlcugc ihc iisIs ly hanuling
oi ucclaiing ihc icmoic cxcciions. Il ihc mcihous in an inicilacc
ucclaic cxcciions, any couc calling mcihous on a iclcicncc ol ihai iyc
ihc inicilacc iyc) musi hanulc oi ucclaic ihc cxcciions.
import java.rmi.*;
public interface MyRemote extends Remote {
public String sayHello() throws RemoteException;
}
3 e sure urguments und return vuIues ure primitives or SeriuIizubIe
Aigumcnis anu iciuin valucs ol a icmoic mcihou musi lc ciihci iimiiivc
oi Sciializallc. ThinI aloui ii. Any aigumcni io a icmoic mcihou has io
lc acIagcu u anu shicu acioss ihc nciwoiI, anu ihai`s uonc ihiough
Sciializaiion. Samc ihing wiih iciuin valucs. Il you usc iimiiivcs, Siiings,
anu ihc ma|oiiiy ol iycs in ihc API incluuing aiiays anu collcciions),
you`ll lc hnc. Il you aic assing aiounu youi own iycs, |usi lc suic ihai
you maIc youi classcs imlcmcni Sciializallc.
public String sayHello() throws RemoteException;
/--- -l--.:- .: l-
.-----:- l.l l': --
----l- --l- :.||: A-
-l--.:- :.-'l -|----l
.-]l-, -l l :.- -l--
-l-- -l--.:-:
!--] ----l- --l- :.|| :
:--:--- '-:]' l-:|.--
---l-!:-l-- -- ---]
--l- --:-: l- :|--l
l- .] .ll--l-- .-
.:---|-- l.l l-:
-l --l ---
1: --l--- .|-- : ---. - :-
--- l- --- --- l- :---- .: l-
l- :|--l, :- l --:l - --.|-.|-
1.l': -- .-: .- --l--- .|--: -l
.:.- - .- :--l
l- ---l- -l--.:- : - ..--
a remote interface
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 617
8tep two: Make a Remote mplementation
1 ImpIement the Pemote interfuce
HyRemote|mp|.java
puo||c |rlerlace
VyRerole exlerds
Rerole {
Youi scivicc has io imlcmcni ihc icmoic inicilacc-ihc onc
wiih ihc mcihous youi clicni is going io call.
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {
public String sayHello() {
return Server says, `Hey';
}
// more code in class
}
2 Etend UnicustPemoteObject
In oiuci io woiI as a icmoic scivicc ol|cci, youi ol|cci nccus somc
lunciionaliiy iclaicu io lcing icmoic`. Thc simlcsi way is io cxicnu
UnicasiRcmoicOl|cci liom ihc |ava.imi.scivci acIagc) anu lci ihai
class youi suciclass) uo ihc woiI loi you.
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {
3 Write u no-urg constructor thut decIures u PemoteEception
Youi ncw suciclass, UnicasiRcmoicOl|cci, has onc liiilc iollcm-iis
consiiucioi ihiows a RcmoicExcciion. Thc only way io ucal wiih ihis is
io ucclaic a consiiucioi loi youi icmoic imlcmcniaiion, |usi so ihai you
havc a lacc io ucclaic ihc RcmoicExcciion. Rcmcmlci, whcn a class is
insianiiaicu, iis suciclass consiiucioi is always callcu. Il youi suciclass
consiiucioi ihiows an cxcciion, you havc no choicc lui io ucclaic ihai
youi consiiucioi also ihiows an cxcciion.
public MyRemoteImpl() throws RemoteException { }
4 Pegister the service with the PMI registry
Now ihai you`vc goi a icmoic scivicc, you havc io maIc ii availallc io
icmoic clicnis. You uo ihis ly insianiiaiing ii anu uiiing ii inio ihc RMI
icgisiiy which musi lc iunning oi ihis linc ol couc lails). Whcn you
icgisici ihc imlcmcniaiion ol|cci, ihc RMI sysicm aciually uis ihc in
ihc icgisiiy, sincc ihai`s whai ihc clicni ically nccus. Rcgisici youi scivicc
using ihc siaiic iclinu) mcihou ol ihc |ava.imi.Naming class.
try {
MyRemote service = new MyRemoteImpl();
Naming.rebind(Remote Hello, service);
} catch(Exception ex) {...}
1- :--|-- -|| -.- :--- l.l
]--'- -|----l- .|| l- --l-:
--- l- -l--.:- ]-- -|----l |-
l: :.:-, l---': --|] ---
/-- --'l .- l- -l .-]l- -
l- :--:l--:l-- /-- -:l --- .
-.] l- -:|.-- l.l ]--- :---:|.::
:--:l--:l-- l---: .- -:-l--
6- ]--- :--:- . -.-- |l.l :|--l: :.- -:-
l- |-- l - - l- --:l-]` .- --:l-- l
-l l- M| --:l-] w-- ]-- - l-
:--:- --:l, M| :-.: l- :--:- -- l-
:l- .- -l: l- :l- - l- --:l-]
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
618 chapter 18
8tep three: generate stubs and skeletons
1 Pun rmic on the remote impIementution cIuss
{not the remote interfuce}
Thc imic iool, ihai comcs wiih ihc ]ava soliwaic
ucvclomcni Iii, iaIcs a scivicc imlcmcniaiion anu
cicaics iwo ncw classcs, ihc siul anu ihc sIclcion.
Ii uscs a naming convcniion ihai is ihc namc ol
youi icmoic imlcmcniaiion, wiih ciihci _Siul oi
_SIclcion auucu io ihc cnu. Thcic aic oihci oiions
wiih imic, incluuing noi gcnciaiing sIclcions,
sccing whai ihc souicc couc loi ihcsc classcs looIcu
liIc, anu cvcn using IIOP as ihc ioiocol. Thc way
wc`ic uoing ii hcic is ihc way you`ll usually uo ii.
Thc classcs will lanu in ihc cuiicni uiiccioiy i.c.
whaicvci you uiu a cu io). Rcmcmlci, musi
lc allc io scc youi imlcmcniaiion class, so you`ll
iolally iun imic liom ihc uiiccioiy whcic youi
icmoic imlcmcniaiion is. Wc`ic uclilciaicly noi
using acIagcs hcic, io maIc ii simlci. In ihc Rcal
Woilu, you`ll nccu io accouni loi acIagc uiiccioiy
siiuciuics anu lully-qualihcu namcs).
%rmic MyRemoteImpl
HyRemote|mp|_8tub.c|ass
HyRemote|mp|_8ke|.c|ass
N-l:- l.l ]-- --'l :.] :|.::'
-- l- -- )-:l l- :|.:: -.--
:l: --l l-- ---
:|.::-: -- l-
-|-- --:l:
8tep four: run rmiregistry
1 ring up u terminuI und sturt the rmiregistry,
Bc suic you siaii ii liom a uiiccioiy ihai has acccss
io youi classcs. Thc simlcsi way is io siaii ii liom
youi classcs` uiiccioiy.
File Edit Window Help Huh?
%rmiregistry
File Edit Window Help Whuffe
8tep hve: start the service
1 ring up unother terminuI und sturt your service
This mighi lc liom a main) mcihou in youi icmoic
imlcmcniaiion class, oi liom a scaiaic launchci class.
In ihis simlc cxamlc, wc ui ihc siaiici couc in ihc
imlcmcniaiion class, in a main mcihou ihai insianiiaics
ihc ol|cci anu icgisicis ii wiih RMI icgisiiy.
File Edit Window Help Huh?
%java MyRemoteImpl
101101
10 110 1
0 11 0
001 10
001 01
101101
10 110 1
0 11 0
001 10
001 01
stubs and skeIetons
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 619
Complete code for the server side

import java.rmi.*;
import java.rmi.server.*;
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {

public String sayHello() {
return Server says, `Hey';
}
public MyRemoteImpl() throws RemoteException { }
public static void main (String[] args) {
try {
MyRemote service = new MyRemoteImpl();
Naming.rebind(Remote Hello, service);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
import java.rmi.*;
public interface MyRemote extends Remote {
public String sayHello() throws RemoteException;
}
---l-!:-l-- .- ---l-
-l--.:- .-- - ..-- .:.-
/--- -l--.:- Mc1 -l--
..-----l-
A|| - ]--- ----l- --l-: --:l
-:|.-- . ---l-!:-l--
c
-:.:l---l-6-:l : - l-
..--:---- .:.-
The Remote interface:
The Remote service {the implementation}:
-l--- c-:.:l---l-6-:l : l-
-.:-:l -.] l- -.- . ----l- --:l
]-- Mc1 -|----l ]--- ----l- -l--.:-''
/-- .- l- -|----l .|| l-
-l--.:- --l-:, - :---:- B-l
--l:- l.l ]-- - N61 .- l-
-:|.-- l- ---l-!:-l--
]--- :---:|.:: :--:l--:l-- |--
c-:.:l---l-6-:l` -:|.--: .- -:-l--, :-
/6c --:l --l- . :--:l--:l--, -:.-:- l --.-:
l.l ]--- :--:l--:l-- : :.||- -:] :-- |l:
:--- :--:l--:l--`
M.- l- ----l- --:l, l-- '-' l l- l-
----:l-] -:- l- :l.l: N.--,---|` 1-
-.-- ]-- --:l-- l ---- : l- -.-- :|--l: -||
--- l- |-- l - - l- -- --:l-]
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
620 chapter 18
Hew 4ecs !hc r||cn! ]c! !hc s!e| e|jcr!!
Thc clicni has io gci ihc siul ol|cci, sincc ihai`s ihc ihing ihc
clicni will call mcihous on. Anu ihai`s whcic ihc RMI icgisiiy
comcs in. Thc clicni uocs a looIu`, liIc going io ihc whiic agcs
ol a honc looI, anu csscniially says, Hcic`s a namc, anu I`u liIc
ihc siul ihai gocs wiih ihai namc."
MyRemote service = (MyRemote) Naming.lookup(rmi://127.0.0.1/Remote Hello);
1- :|--l .|-.]: -:-: l-
----l- -|----l.l-- .: l-
l]- - l- :--:- |- .:l,
l- :|--l ---- ---: l- ---
l- .:l-.| :|.:: -.-- - ]---
----l- :--:-
/-- .- l- :.:l l l- l-
-l--.:-, :-:- l- |---
--l- --l---: l]- 6-:l
|---|` : . :l.l: --l- -
l- N.-- :|.::
]--- -:l -.-- -- ||
.--:: --: ---
1: --:l - l- -.--
l.l l- :--:- -.:
--:l--- ----
S
e
r
v
ice o
b
j
e
c
f

C
I
i
e
n
f ob
j
e
c
f

Sfub
S
k
eIefo
n
Server
CIient

Stub
PMI registry {on server}
1 CIient does u Iookup on the PMI registry
2 PMI registry returns the stub object
as ihc iciuin valuc ol ihc looIu mcihou) anu RMI
ucsciializcs ihc siul auiomaiically. You MUST havc
ihc siul class ihai imic gcnciaicu loi you) on ihc
clicni oi ihc siul won`i lc ucsciializcu
3 CIient invokes u method on the stub us
though the stub IS the reuI service
1
2
3
Naming.lookup(rmi://127.0.0.1/Remote Hello);
I
o
o
k
u
p
(

)
s
f
u
b

r
e
f
u
r
n
e
d
so
y
H
e
IIo
( )
getting the stub
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 621
Hew 4ecs !hc r||cn! ]c! !hc s!e| r|zss!
Now wc gci io ihc inicicsiing qucsiion. Somchow, somcway, ihc
clicni musi havc ihc siul class ihai you gcnciaicu cailici using
imic) ai ihc iimc ihc clicni uocs ihc looIu, oi clsc ihc siul won`i
lc ucsciializcu on ihc clicni anu ihc wholc ihing llows u. In a
simlc sysicm, you can simly hanu-uclivci ihc siul class io ihc
clicni.
Thcic`s a much coolci way, ihough, alihough ii`s lcyonu ihc
scoc ol ihis looI. Bui |usi in casc you`ic inicicsicu, ihc coolci
way is callcu uynamic class uownloauing". Wiih uynamic class
uownloauing, a siul ol|cci oi ically any Sciializcu ol|cci) is
siamcu` wiih a URI ihai iclls ihc RMI sysicm on ihc clicni
whcic io hnu ihc class hlc loi ihai ol|cci. Thcn, in ihc ioccss ol
ucsciializing an ol|cci, il RMI can`i hnu ihc class locally, ii uscs
ihai URI io uo an HTTP Gci io iciiicvc ihc class hlc. So you`u
nccu a simlc Wcl scivci io scivc u class hlcs, anu you`u also
nccu io changc somc sccuiiiy aiamcicis on ihc clicni. Thcic aic
a lcw oihci iiicIy issucs wiih uynamic class uownloauing, lui ihai`s
ihc ovcivicw.
import java.rmi.*;
public class MyRemoteClient {
public static void main (String[] args) {
new MyRemoteClient().go();
}
public void go() {
try {
MyRemote service = (MyRemote) Naming.lookup(rmi://127.0.0.1/Remote Hello);
String s = service.sayHello();
System.out.println(s);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Complete client code
1- N.-- :|.:: |-- -- l-
-----:l-] |---` : - l-
..-- .:.-
|l :---: --l - l- --:l-] .: l]-
6-:l, :- --'l ---l l- :.:l
]-- --- l- || .--::
-- -:l-.--
.- l- -.-- -:- l-
-/--- l- :--:-
|l |--: -:l |- . ---|.- -| --l- :.||' |!:-l l --:l .:---|-- l- ---l-!:-l--`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
622 chapter 18
Bc serc czrh mzrh|nc hzs !hc r|zss
f||cs | ! ncc4s.
Thc io ihicc ihings iogiammcis uo wiong wiih RMI aic:
1) Ioigci io siaii imiicgisiiy lcloic siaiiing icmoic scivicc
whcn you icgisici ihc scivicc using Naming.iclinu), ihc
imiicgisiiy musi lc iunning!)
2) Ioigci io maIc aigumcnis anu iciuin iycs sciializallc
you won`i Inow uniil iuniimc, ihis is noi somcihing ihc
comilci will ucicci.)
S) Ioigci io givc ihc siul class io ihc clicni.
S
e
r
v
ice o
b
j
e
c
f

C
I
i
e
n
f ob
j
e
c
f

Sfub
S
k
eIefo
n
Server
CIient










HyRemote|mp|_8tub.c|ass
6||ent.c|ass





HyRemote|mp|_8tub.c|ass
Sfub





HyRemote.c|ass





HyRemote.c|ass
HyRemote|mp|.c|ass
HyRemote|mp|_8ke|.c|ass










l--'l ---l, l- :|--l
-:-: l- -l--.:- l- :.||
--l-: -- l- :l- 1-
:|--l )/M ---: l- :l-
:|.::, -l l- :|--l ----
----: l- l- :l- :|.::
- :-- 1- :|--l .|-.]:
-:-: l- ----l- -l--.:-,
.: l-- l- ----l-
-l--.:- w!! l-
.:l-.| ----l- --:l
---- ---: -l l- l- .- -|-l--
:|.::-:, .: --|| .: l- :--:- .- l-
----l- -l--.:- |l ---: l- :l- :|.::
-:.-:- -------, l- :l- : :-:ll-l-
-- l- --.| :--:-, --- l- --.| :--:-
: --- l- l- M| --:l-]
RMI cIass fiIes
1
- ---
-l- -l--.:-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 623
yg'z
]j;z/
l.
2.
3.
4.
5.
6.
7.
Look at the sequence of events below, and
place them in the order in which they
occur in a 1ava PM| application.
T|e RVl re|slry |s slarled
T|e rerole serv|ce (rerole
|rp|ererlal|or) |s |rslarl|aled
T|e c||erl does a |oo|up or
l|e RVl Re|slry
T|e sluo serds l|e rel|od
ca|| lo l|e server
T|e c||erl |rvo|es a rel|od
or l|e sluo
T|e c||erl els l|e sluo lror
l|e RVl re|slry
T|e rerole serv|ce |s re|s-
lered W|l| l|e RVl re|slry
+,-+ :+ ,-+:.|
8ll P0lk5
Ar oojecl or ore |eap carrol el a rorra| Java
relererce lo ar oojecl or a d|llererl |eap (W||c| rears
rurr|r or a d|llererl JvV)
Java Rerole Vel|od lrvocal|or (RVl) ra|es |l seem |||e
you're ca|||r a rel|od or a rerole oojecl (|.e. ar oojecl
|r a d|llererl JvV), oul you arer'l.
w|er a c||erl ca||s a rel|od or a rerole oojecl, l|e
c||erl |s rea||y ca|||r a rel|od or a roxy ol l|e rerole
oojecl. T|e proxy |s ca||ed a 'sluo'.
A sluo |s a c||erl |e|per oojecl l|al la|es care ol l|e |oW-
|eve| relWor||r dela||s (soc|els, slrears, ser|a||zal|or,
elc.) oy pac|a|r ard serd|r rel|od ca||s lo l|e
server.
To ou||d a rerole serv|ce (|r ol|er Words, ar oojecl l|al
a rerole c||erl car u|l|rale|y ca|| rel|ods or), you rusl
slarl W|l| a rerole |rlerlace.
A rerole |rlerlace rusl exlerd l|e java.rr|.Rerole
|rlerlace, ard a|| rel|ods rusl dec|are
ReroleExcepl|or.
Your rerole serv|ce |rp|ererls your rerole |rlerlace.
Your rerole serv|ce s|ou|d exlerd ur|caslRerole0ojecl.
(Tec|r|ca||y l|ere are ol|er Ways lo creale a rerole oo-
jecl, oul exlerd|r ur|caslRerole0ojecl |s l|e s|rp|esl).
Your rerole serv|ce c|ass rusl |ave a corslruclor,
ard l|e corslruclor rusl dec|are a ReroleExcepl|or
(oecause l|e superc|ass corslruclor dec|ares ore).
Your rerole serv|ce rusl oe |rslarl|aled, ard l|e oojecl
re|slered W|l| l|e RVl re|slry.
To re|sler a rerole serv|ce, use l|e slal|c
Nar|r.reo|rd('3erv|ce Nare, serv|celrslarce),
T|e RVl re|slry rusl oe rurr|r or l|e sare rac||re
as l|e rerole serv|ce, oelore you lry lo re|sler a rerole
oojecl W|l| l|e RVl re|slry.
T|e c||erl |oo|s up your rerole serv|ce us|r l|e slal|c
Nar|r.|oo|up('rr|://VyloslNare/3erv|ceNare),
A|rosl everyl||r re|aled lo RVl car l|roW a
ReroleExcepl|or (c|ec|ed oy l|e corp||er). T||s
|rc|udes re|sler|r or |oo||r up a serv|ce |r l|e re|slry,
ard a|| rerole rel|od ca||s lror l|e c||erl lo l|e sluo.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
624 chapter 18
Yczh, |e! whe rcz||y escs KM|!
I use if
for serious 8-fo-8,
e-commerce bock-
ends, running on JZEE
fechnoIogy.
We use if
for our cooI
new decision-supporf
sysfem.
I heord your ex-
wife sfiII uses
pIoin sockefs.
We've gof on
EJ8-bosed hofeI
reservofion sysfem.
And EJ8 uses PMIl
I jusf con'f imogine
Iife wifhouf our Jini-
enobIed home nefwork
ond oppIiconces.
Me fool How
did onyone gef
by7 I jusf Iove PMI
for giving us Jini
fechnoIogy.
uses for RMI
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 625
Thonks
Ko|hy
5ierro
obs
Pe|s
Kathy
Sierra
Whz! z|ee! 8crv|c!s!
Scivlcis aic ]ava iogiams ihai iun on anu wiih) an HTTP wcl scivci. Whcn a clicni uscs a
wcl liowsci io iniciaci wiih a wcl agc, a icqucsi is scni lacI io ihc wcl scivci. Il ihc icqucsi
nccus ihc hcl ol a ]ava scivlci, ihc wcl scivci iuns oi calls, il ihc scivlci is alicauy iunning)
ihc scivlci couc. Scivlci couc is simly couc ihai iuns on ihc scivci, io uo woiI as a icsuli ol
whaicvci ihc clicni icqucsis loi cxamlc, savc inloimaiion io a icxi hlc oi uaialasc on ihc
scivci). Il you`ic lamiliai wiih CGI sciiis wiiiicn in Pcil, you Inow cxacily whai wc`ic ialIing
aloui. Wcl ucvclocis usc CGI sciiis oi scivlcis io uo cvciyihing liom scnuing usci-sulmiiicu
inlo io a uaialasc, io iunning a wcl-siic`s uiscussion loaiu.
ArJ e.er e..Ie nr ue FAI
By lai, ihc mosi common usc ol ]2EE icchnology is io mix scivlcis anu E]Bs iogcihci, whcic
scivlcis aic ihc clicni ol ihc E]B. Anu in ihai casc, Le e..Ie . u.r FAI o nII o Le EJB.
Alihough ihc way you usc RMI wiih E]B is a I.Ie uillcicni liom ihc ioccss wc |usi looIcu ai.)
101101
10 110 1
0 11 0
001 10
001 01
Hy8erv|et.c|ass
Web Server
Web rowser
{cIient}
"cIienf requesfs PegisferServIef"
1
CIienf fIIs ouf o regisfrofion form ond cIicks 'submif'.
The HTTP server (i.e. web server) gefs fhe requesf, sees fhof
if's for o servIef, ond sends fhe requesf fo fhe servIef.
101101
10 110 1
0 11 0
001 10
001 01
Hy8erv|et.c|ass
Web Server
Web rowser
{cIient}
"cIienf requesfs PegisferServIef"
2
ServIef (Jovo code) runs, odds dofo fo fhe dofobose,
composes o web poge (wifh cusfom info) ond sends if bock fo
fhe cIienf where if dispIoys in fhe browser.
conf|rm.htm|
<HTML>
<BODY>
Java
rules!
<BODY>
<HTML>
"here's o confrmofion poge"
100% LocuI Combinution 100% Pemote
8erv|ets
HTTP
web 8tart
FiIe Edit View
HTTP
RH| app
FiIe Edit View
RMI
Executab|e
Jar
FiIe Edit View
8erv|ets
HTTP
8erv|ets
HTTP
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
626 chapter 18
very simpIe servIet
8tep for making and running a servlet
1 Find out where your servIets need to be pIuced,
Ioi ihcsc cxamlcs, wc`ll assumc ihai you alicauy havc a wcl scivci
u anu iunning, anu ihai ii`s alicauy conhguicu io suoii scivlcis.
Thc mosi imoiiani ihing is io hnu oui cxacily whcic youi scivlci
class hlcs havc io lc laccu in oiuci loi youi scivci io scc` ihcm. Il
you havc a wcl siic hosicu ly an ISP, ihc hosiing scivicc can icll you
whcic io ui youi scivlcis, |usi as ihcy`ll icll you whcic io lacc youi
CGI sciiis.
101101
10 110 1
0 11 0
001 10
001 01
Hy8erv|etA.c|ass
Web Server
8erv|ets
2 Set the servIets,jur und udd it to your cIussputh
Scivlcis aicn`i aii ol ihc sianuaiu ]ava liliaiics, you nccu
ihc scivlcis classcs acIagcu inio ihc scivlcis.|ai hlc. You can
uownloau ihc scivlcis classcs liom |ava.sun.com, oi you can gci
ihcm liom youi ]ava-cnallcu wcl scivci liIc Aachc Tomcai, ai
ihc aachc.oig siic). Wiihoui ihcsc classcs, you won`i lc allc io
comilc youi scivlcis.
3 Write u servIet cIuss by etending HttpServIet
A scivlci is |usi a ]ava class ihai cxicnus HiiScivlci liom ihc
|avax.scivlci.hii acIagc). Thcic aic oihci iycs ol scivlcis you
can maIc, lui mosi ol ihc iimc wc caic only aloui HiiScivlci.
public class MyServletA extends HttpServlet { ... }
serv|ets.jar
4 Write un HTML puge thut invokes your servIet
Whcn ihc usci clicIs a linI ihai iclcicnccs youi scivlci, ihc wcl
scivci will hnu ihc scivlci anu invoIc ihc aioiiaic mcihou
uccnuing on ihc HTTP commanu GET, POST, cic.)
<a href=servlets/MyServletA>This is the most amazing servlet.</a>
5 Muke your servIet und HTML puge uvuiIubIe to your server
This is comlcicly uccnucni on youi wcl scivci anu moic sccih-
cally, on which ol ]ava Scivlcis ihai you`ic using). Youi ISP
may simly icll you io uio ii inio a Scivlcis" uiiccioiy on youi
wcl siic. Bui il you`ic using, say, ihc laicsi vcision ol Tomcai, you`ll
havc a loi moic woiI io uo io gci ihc scivlci anu wcl agc) inio
ihc iighi locaiion. Wc |usi hacn io havc a looI on ihis ioo .)
101101
10 110 1
0 11 0
001 10
001 01
Hy8erv|etA.c|ass
HyPage.htm|
<HTML>
<BODY>
Java
rules!
<BODY>
<HTML>
101101
10 110 1
0 11 0
001 10
001 01
Hy8erv|etA.c|ass
Web Server
8erv|ets
HyPage.htm|
<HTML>
<BODY>
Java
rules!
<BODY>
<HTML>
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 627
vcry s|mp|c 8crv|c!
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServletA extends HttpServlet {


public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


response.setContentType(text/html);

PrintWriter out = response.getWriter();
String message = If you're reading this, it worked!;
out.println(<HTML><BODY>);
out.println(<H1> + message + </H1>);
out.println(</BODY></HTML>);
out.close();
}
}
B-:-: -, -- --- l- ---l l-- - l- :--|-l .:.-:
------, l-:- l-- .:.-: .-- N61 .-l - l- )..
:l.-.- |-.--: ~~ ]-- .- l- ---|-. l-- :-.-.l-|]
M-:l '----.|' :--|-l: -|| -l--
+ll--|-l, l-- ----- --- --
---- --l-:
6---- l- -6-l -- :-|-
+11| 6!1 --::.-:
1- -- :---- :.||: l: --l-, .-- ]-- l- :|--l':
----:l |]-- :.- -l .l. --l - l` .- . '--:--:-'
--:l l.l ]--'|| -:- l- :-- .: . --:--:- |. .-`
1: l-||: l- :---- |.- ---:--` -.l - -
'l-' : :--- .: --- l- :---- .: . ---:|l -
l: :--|-l -----
1- --:--:- --:l -: -: .- --l-l :l--.- l-
'--l-' ----.l-- .: --l l- l- :----
w.l -- '--l-' : .- +1M| .-' 1- .-
-l: -|--- l--- l- :---- .: l-
l- ---:--, -:l |- .-] -l-- +1M| .-,
--- l-- l: : . .- l.l ---- -:l-
--l| --- |- -l-- ---:, l---': -- l-| |-
:------- -l l: :l- - l
<HTML>
<BODY>
<a href=servlets/MyServletA>This is an amazing servlet.</a>
</BODY>
</HTML>
HIMI pz]c w| !h z ||nk !e !h|s scrv|c!
T||s ar araz|r serv|el.
w.l l- -- .- |--: |-
:|: l- |-
l- l--- l-
:--|-l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
628 chapter 18
(-,- a,- |
oa|| qa--(:|-

What's a 1SP, and how does it reIate to servIets!

1SP stands for 1ava Server Pages. |n the end, the web server
turns a 1SP into a servlet, but the difference between a servlet and
a 1SP is what OU (the developer) actually create. with a servlet,
you write a 1ava closs that contains l7Vl in the output statements
(if you're sending back an HTML page to the client). 8ut with a
1SP, it's the oppositeyou write an l7Vl page that contains 1ovo
code!
This gives you the ability to have dynamic web pages where you
write the page as a normal HTML page, except you embed 1ava
code (and other tags that "trigger 1ava code at runtime) that
gets processed at runtime. |n other words, part of the page is
customized at runtime when the 1ava code runs.
The main benefit of 1SP over regular servlets is that it's |ust a lot
easier to write the HTML part of a servlet as a 1SP page than to
write HTML in the torturous print out statements in the servlet's
response. |magine a reasonably complex HTML page, and now
imagine formatting it within println statements. ikes!
8ut for many applications, it isn't necessary to use 1SPs because
the servlet doesn't need to send a dynamic response, or the
HTML is simple enough not to be such a big pain. And, there are
still many web servers out there that support servlets but do not
support 1SPs, so you're stuck.
Another benefit of 1SPs is that you can separate the work by
having the 1ava developers write the servlets and the web page
developers write the 1SPs. That's the promised benefit, anyway.
|n reality, there's still a 1ava learning curve (and a tag learning
curve) for anyone writing a 1SP, so to think that an HTML web page
designer can bang out 1SPs is not realistic. well, not without tools.
8ut that's the good newsauthoring tools are starting to appear,
that help web page designers create 1SPs without writing the
code from scratch.

Is this aII you're gonna say about servIets! After such a
thing on RMI!

es. PM| is part of the 1ava language, and all the classes for
PM| are in the standard libraries. Servlets and 1SPs are not part of
the 1ava language, they're considered stonJotJ extens|ons. ou
can run PM| on any modern 1vM, but Servlets and 1SPs require a
properly configured web server with a servlet "container. This is
our way of saying, "it's beyond the scope of this book. 8ut you can
read much more in the lovely leoJ l|tst 5etvlets 8 15P.
8ll P0lk5
3erv|els are Java c|asses l|al rur erl|re|y or
(ard/or W|l||r) ar lTTP (Weo) server.
3erv|els are uselu| lor rurr|r code or l|e
server as a resu|l ol c||erl |rleracl|or W|l| a
Weo pae. For exarp|e, |l a c||erl suor|ls
|rlorral|or |r a Weo pae lorr, l|e serv|el car
process l|e |rlorral|or, add |l lo a dalaoase,
ard serd oac| a cuslor|zed, corl|rral|or
resporse pae.
To corp||e a serv|el, you reed l|e serv|el
pac|aes W||c| are |r l|e serv|els.jar l||e. T|e
serv|el c|asses are rol parl ol l|e Java slardard
||orar|es, so you reed lo doWr|oad l|e serv|els.
jar lror java.sur.cor or el l|er lror a serv|el-
capao|e Weo server. (Nole: l|e 3erv|el ||orary
|s |rc|uded W|l| l|e Java 2 Erlerpr|se Ed|l|or
(J2EE))
To rur a serv|el, you rusl |ave a Weo server
capao|e ol rurr|r serv|els, suc| as l|e Torcal
server lror apac|e.or.
Your serv|el rusl oe p|aced |r a |ocal|or l|al's
spec|l|c lo your parl|cu|ar Weo server, so you'||
reed lo l|rd l|al oul oelore you lry lo rur your
serv|els. ll you |ave a Weo s|le |osled oy ar l3P
l|al supporls serv|els, l|e l3P W||| le|| you W||c|
d|reclory lo p|ace your serv|els |r.
A lyp|ca| serv|el exlerds lllp3erv|el ard
overr|des ore or rore serv|el rel|ods, suc| as
do0el() or doPosl().
T|e Weo server slarls l|e serv|el ard ca||s l|e
appropr|ale rel|od (do0el(), elc.) oased or l|e
c||erl's requesl.
T|e serv|el car serd oac| a resporse oy ell|r
a Pr|rlwr|ler oulpul slrear lror l|e resporse
parareler ol l|e do0el() rel|od.
T|e serv|el 'Wr|les' oul ar lTVL pae, corp|ele
W|l| las).
servIets and JSP
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 629
1es! fer fen, |c!s mzkc !hc |hrzsc-0-Mz!|r
werk zs z scrv|c!
Now ihai wc iolu you ihai wc won`i
say any moic aloui scivlcis, wc can`i
icsisi scivlciizing ycs, wc vcilily
ii) ihc Phiasc-O-Maiic liom chaici 1.
A scivlci is siill |usi ]ava. Anu ]ava couc
can call ]ava couc liom oihci classcs.
So a scivlci is licc io call a mcihou on
ihc Phiasc-O-Maiic. All you havc io uo
is uio ihc Phiasc-O-Maiic class inio
ihc samc uiiccioiy as youi scivlci, anu
you`ic in lusincss. Thc Phiasc-O-
Maiic couc is on ihc ncxi agc).
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class KathyServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String title = PhraseOMatic has generated the following phrase.;
response.setContentType(text/html);
PrintWriter out = response.getWriter();
out.println(<HTML><HEAD><TITLE>);
out.println(PhraseOmatic);
out.println(</TITLE></HEAD><BODY>);
out.println(<H1> + title + </H1>);
out.println(<P> + PhraseOMatic.makePhrase());
out.println(<P><a href=\KathyServlet\>make another phrase</a></p>);
out.println(</BODY></HTML>);

out.close();
}
}
Try my
new web-enobIed
phrose-o-mofic ond you'II
be o sIick foIker jusf Iike
fhe boss or fhose guys in
morkefing.
-- /--- :--|-l :.- :.|| --l-: --
.--l-- :|.:: |- l: :.:-, --'-- :.||-
l- :l.l: -.-|-.:-|` --l- - l-
|-.:-6M.l: :|.:: |-- l- --l .-`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
630 chapter 18
public class PhraseOMatic {
public static String makePhrase() {
// make three sets of words to choose from
String[] wordListOne = {24/7,multi-Tier,30,000 foot,B-to-B,win-win,front-
end, web-based,pervasive, smart, six-sigma,critical-path, dynamic};
String[] wordListTwo = {empowered, sticky, valued-added, oriented, centric,
distributed, clustered, branded,outside-the-box, positioned, networked, fo-
cused, leveraged, aligned, targeted, shared, cooperative, accelerated};
String[] wordListThree = {process, tipping point, solution, architecture,
core competency, strategy, mindshare, portal, space, vision, paradigm, mis-
sion};
// nd out how many words are in each list
int oneLength = wordListOne.length;
int twoLength = wordListTwo.length;
int threeLength = wordListThree.length;
// generate three random numbers, to pull random words from each list
int rand1 = (int) (Math.random() * oneLength);
int rand2 = (int) (Math.random() * twoLength);
int rand3 = (int) (Math.random() * threeLength);
// now build a phrase
String phrase = wordListOne[rand1] + + wordListTwo[rand2] + +
wordListThree[rand3];
// now return it
return (What we need is a + phrase);
}
}
|hrzsc-0-Mz!|r re4c, scrv|c!-fr|cn4|y
This is a slighily uillcicni vcision liom ihc couc in chaici onc. In ihc
oiiginal, wc ian ihc cniiic ihing in a main) mcihou, anu wc hau io iciun
ihc iogiam cach iimc io gcnciaic a ncw hiasc ai ihc commanu-linc. In ihis
vcision, ihc couc simly iciuins a Siiing wiih ihc hiasc) whcn you invoIc
ihc siaiic maIcPhiasc) mcihou. Thai way, you can call ihc mcihou liom any
oihci couc anu gci lacI a Siiing wiih ihc ianuomly-comoscu hiasc.
Plcasc noic ihai ihcsc long Siiing]| aiiay assignmcnis aic a viciim ol woiu-
ioccssing hcic-uon`i iyc in ihc hyhcns! ]usi Icc on iying anu lci youi
couc cuiioi uo ihc wiaing. Anu whaicvci you uo, uon`i hii ihc iciuin Icy in
ihc miuulc ol a Siiing i.c. somcihing lciwccn uoullc quoics).
Phrase-O-Matic code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 631
In!crpr|sc 1zvzBczns: KM| en s!cre|4s
RMI is gicai loi wiiiing anu iunning icmoic sciviccs. Bui
you woulun`i iun somcihing liIc an Amazon oi cBay on RMI
alonc. Ioi a laigc, ucauly sciious, cniciiisc alicaiion, you
nccu somcihing moic. You nccu somcihing ihai can hanulc
iiansaciions, hcavy concuiicncy issucs liIc a gazillion
colc aic hiiiing youi scivci ai oncc io luy ihosc oiganic
uog Iilllcs), sccuiiiy noi |usi anyonc shoulu hii youi
ayioll uaialasc), anu uaia managcmcni. Ioi ihai, you nccu
an ere...e nI.n.or e..e..
In ]ava, ihai mcans a ]ava 2 Eniciiisc Euiiion ]2EE) scivci.
A ]2EE scivci incluucs loih a wcl scivci anu an Eniciiisc
]avaBcansE]B) scivci, so ihai you can ucloy an alicaiion
ihai incluucs loih scivlcis anu E]Bs. IiIc scivlcis, E]B is
way lcyonu ihc scoc ol ihis looI, anu ihcic`s no way io
show |usi a liiilc" E]B cxamlc wiih couc, lui wc w.II iaIc
a quicI looI ai how ii woiIs. Ioi a much moic uciailcu
iicaimcni ol E]B, wc can iccommcnu ihc livcly Hcau Iiisi
E]B cciiihcaiion siuuy guiuc.)
E
J
8
obje
c
f

C
I
i
e
n
f ob
j
e
c
f

C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
CIient
PMI STU
PMI SkELETON
1: :|--l :--| - AN/1+|N6, -l
l]:.||] .- !)B :|--l : . :--|-l
----- - l- :.-- )i!! :----
e
n
f
e
r
pris
e

b
e
o
n

+---': ---- l- !)B :---- -l:
--|-' 1- !)B --:l -l--:-l:
l- :.||: l- l- -.- |l- -.- -|:
l- --.| -:--:: |-:` .- |.]--: -
.|| l- :--:-: --- ] l- !)B
:---- |:-:--l], l-.-:.:l--:, -l:`
EJ server
1- -.- --:l : --l-:l- ---
--:l :|--l .::-::' 6-|] l- :----
:.- .:l-.||] l.| l- l- -.- 1:
|-l: l- :---- - l-: |- :.],
w-.' 1: :|--l --:-'l .-
l- :-:--l] :|-.-.-:- l- :.|| l:
--l-' A|--:l ---]l- ]-- .]
-- - .- !)B :---- .--: -l
+!!, ---- l- :---- :l-: -'
D
jn []@ ,v z]], z ane[
| ,vje, ([z( ya ]n'( g(
wj([ ,(zjg[( p]. [[jng,
]j[ (zn,ze(jn,, ,eaj(y,
eneaney, ]z(zz,
znzgn(, zn] n(w[jng.
jn []@ ,v ,(, jn( ([
j]]] | zn p] ez]] zn]
]zy, jn z]] | ([ ,vje,.
This is onIy o smoII porf of fhe EJ8 picfurel
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
632 chapter 18
Ier eer f|nz| !r|rk... z || !!|c 1|n|
Wc lovc ]ini. Wc ihinI ]ini is iciiy much ihc lcsi ihing in ]ava. Il E]B is RMI
on sicioius wiih a lunch ol managcis), ]ini is RMI wiih w.r. Puic ]ava bI..
IiIc ihc E]B maiciial, wc can`i gci inio any ol ihc ]ini uciails hcic, lui il you
Inow RMI, you`ic ihicc-quaiicis ol ihc way ihcic. In icims ol icchnology,
anyway. In icims ol .rJe, ii`s iimc io maIc a lig lca. No, ii`s iimc io ,.
]ini uscs RMI alihough oihci ioiocols can lc involvcu), lui givcs you a lcw
Icy lcaiuics incluuing:
Adoptive discovery
SeI[-heoIing networhs
Wiih RMI, icmcmlci, ihc clicni has io Inow ihc
namc anu locaiion ol ihc icmoic scivicc. Thc
clicni couc loi ihc looIu incluucs ihc IP auuicss oi
hosinamc ol ihc icmoic scivicc lccausc ihai`s whcic
ihc RMI icgisiiy is iunning) nrJ ihc logical namc ihc
scivicc was icgisicicu unuci.
Bui wiih ]ini, ihc clicni has io Inow only onc ihing: Le
inter[oce .IeereJ b, Le e...e Thai`s ii.
So how uo you hnu ihings. Thc iiicI icvolvcs aiounu ]ini looIu
sciviccs. ]ini looIu sciviccs aic lai moic owcilul anu ucxillc ihan
ihc RMI icgisiiy. Ioi onc ihing, ]ini looIu sciviccs announcc ihcmsclvcs io ihc
nciwoiI, nuon.nII,. Whcn a looIu scivicc comcs onlinc, ii scnus a mcssagc using IP
muliicasi) oui io ihc nciwoiI saying, I`m hcic, il anyonc`s inicicsicu."
Bui ihai`s noi all. Ici`s say you a clicni) comc onlinc ne. ihc looIu scivicc has alicauy
announccu iiscll, ,ou can scnu a mcssagc io ihc cniiic nciwoiI saying, Aic ihcic any
looIu sciviccs oui ihcic."
Excci ihai you`ic noi ically inicicsicu in ihc looIu scivicc .eI-you`ic inicicsicu in
ihc sciviccs ihai aic .e.e.eJ wiih ihc looIu scivicc. Things liIc RMI icmoic sciviccs,
oihci sciializallc ]ava ol|ccis, anu cvcn ucviccs such as iinicis, camcias, anu collcc-
maIcis.
Anu hcic`s whcic ii gcis cvcn moic lun: whcn a scivicc comcs onlinc, ii will uynamically
uiscovci anu .e.e. iiscll wiih) any ]ini looIu sciviccs on ihc nciwoiI. Whcn ihc
scivicc icgisicis wiih ihc looIu scivicc, ihc scivicc scnus a sciializcu ol|cci io lc laccu
in ihc looIu scivicc. Thai sciializcu ol|cci can lc a siul io an RMI icmoic scivicc, a
uiivci loi a nciwoiIcu ucvicc, oi cvcn ihc wholc scivicc iiscll ihai oncc you gci ii liom
ihc looIu scivicc) iuns locally on youi machinc. Anu insicau ol icgisiciing ly rne, ihc
scivicc icgisicis ly ihc .re.ne ii imlcmcnis.
Oncc you ihc clicni) havc a iclcicncc io a looIu scivicc, you can say io ihai looIu
scivicc, Hcy, uo you havc anyihing ihai imlcmcnis ScicniihcCalculaioi." Ai ihai oini,
ihc looIu scivicc will chccI iis lisi ol icgisicicu inicilaccs, anu assuming ii hnus a
maich, says lacI io you, Ycs I Jo havc somcihing ihai imlcmcnis ihai inicilacc. Hcic`s
ihc sciializcu ol|cci ihc ScicniihcCalculaioi scivicc icgisicicu wiih mc."
a IittIe Jini
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 633
4zp!| vc 4|srevcry |n zr!|en
1
Jini Iookup service is Iounched somewhere on fhe nefwork, ond
onnounces ifseIf using IP muIficosf.
2
An oIreody-running Jini service on
onofher mochine osks fo be regisfered
wifh fhis newIy-onnounced Iookup
service. If regisfers by copobiIify,
rofher fhon by nome. In ofher words,
if regisfers os fhe service inferfoce if
impIemenfs. If sends o serioIi;ed objecf
fo be pIoced in fhe Iookup service.
Jini Lookup 8ervice
muchine on the network
somewhere,,,
Hey everybody,
I'm herel
unother muchine on the network
unother muchine on the network
Jini Lookup 8ervice
muchine on the network
somewhere,,,
unother muchine on the network
unother muchine on the network
Jini 8ervice
Pegisfer
me os somefhing
fhof impIemenfs
ScienfifcCoIcuIofor. Here's o
serioIi;ed objecf fhof represenfs
my service. Send if fo
onybody who osks...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
634 chapter 18
4zp!| vc 4|srevcry |n zr!|en, ren!|nec4...
3
A cIienf on fhe nefwork wonfs
somefhing fhof impIemenfs fhe
ScienfifcCoIcuIofor inferfoce. If hos
no ideo where (or if) fhof fhing exisfs,
so if osks fhe Iookup service.
4
The Iookup service responds, since if does hove somefhing
regisfered os o ScienfifcCoIcuIofor inferfoce.
Jini Lookup 8ervice
muchine on the network
somewhere,,,
Do you
hove onyfhing
fhof impIemenfs
ScienfifcCoIcuIofor7
unother muchine on the network
unother muchine
on the network
Jini Lookup 8ervice
muchine on the network
somewhere,,,
unother muchine on the network
unother muchine on the network
Jini 8ervice
Jini 8ervice
Java app
Java app
Yes, I do
hove somefhing.
I'm sending you fhe
serioIi;ed objecf
now...
adaptive discovery in Jini
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 635
8c|f-hcz||n] nc! werk |n zr!|en
1
A Jini Service hos osked fo regisfer wifh fhe Iookup service. The Iookup
service responds wifh o "Ieose". The newIy-regisfered service musf keep
renewing fhe Ieose, or fhe Iookup service ossumes fhe service hos gone
ofine. The Iookup service wonfs oIwoys fo presenf on occurofe picfure
fo fhe resf of fhe nefwork obouf which services ore ovoiIobIe.
2
The service goes offIine (somebody shufs if down), so if foiIs fo
renew ifs Ieose wifh fhe Iookup service. The Iookup service drops if.
Jini Lookup 8ervice
muchine on the network
somewhere,,,
I'II
regisfer you,
ond here's your
Ieose. If you don'f
renew if, I'II drop you.
unother muchine on the network
unother muchine
on the network
Jini Lookup 8ervice
muchine on the network
somewhere,,,
unother muchine on the network
unother muchine on the network
Jini 8ervice
Hmmmm... I
didn'f gef o Ieose
renewoI from fhof one... if
musf be down. I'II drop if. If if
comes bock, if wiII oufomoficoIIy
rediscover me.
Ieuse
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
636 chapter 18
I|nz| |rejcr!: !hc 0n| vcrsz| 8crv|rc |rewscr
Wc`ic going io maIc somcihing ihai isn`i ]ini-cnallcu, lui quiic casily coulu lc.
Ii will givc you ihc uavoi anu lccling ol ]ini, lui using siiaighi RMI. In laci ihc
main uillcicncc lciwccn oui alicaiion anu a ]ini alicaiion is how ihc scivicc is
uiscovcicu. Insicau ol ihc ]ini looIu scivicc, which auiomaiically announccs iiscll anu
livcs anywhcic on ihc nciwoiI, wc`ic using ihc RMI icgisiiy which musi lc on ihc samc
machinc as ihc icmoic scivicc, anu which uocs noi announcc iiscll auiomaiically.
Anu insicau ol oui scivicc icgisiciing iiscll auiomaiically wiih ihc looIu scivicc, we
havc io icgisici ii in ihc RMI icgisiiy using Naming.iclinu)).
Bui oncc ihc clicni has lounu ihc scivicc in ihc RMI icgisiiy, ihc icsi ol ihc alicaiion
is almosi iucniical io ihc way wc`u uo ii in ]ini. Thc main ihing missing is ihc Iene ihai
woulu lci us havc a scll-hcaling nciwoiI il any ol ihc sciviccs go uown.)
Thc univcisal scivicc liowsci is liIc a sccializcu wcl liowsci, cxcci insicau ol HTMI
agcs, ihc scivicc liowsci uownloaus anu uislays iniciaciivc ]ava GUIs ihai wc`ic
calling ur..e.nI e...e.
w
-- ]-- :-|-:l . :--:-,
l -|| :-- - --- '
c--:- . :--:- --- l-
|:l 1- M| ----l- :--:-
.: . -l--:-|:l|`
--l- l.l :--: .: l:
|:l - :--:-:
w-- l- -:-- :-|-:l: ---,
l- :|--l .:: -- l-
.:l-.| :--:- |l:--||-,
l.]61-w--, -l:` l-
- :--l .: --- l- M|
----l- :--:-
universaI service project
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 637
How it works:
1 CIienf sforfs up ond
does o Iookup on fhe
PMI regisfry for
fhe service coIIed
"ServiceServer", ond
gefs bock fhe sfub.
Server
Service rowser
{cIient}
"
P
Ie
o
s
e

g
iv
e

m
e

f
h
e

f
h
in
g

n
o
m
e
d

"
S
e
r
v
ic
e
S
e
r
v
e
r
"
Server
Service rowser
{cIient}
"gefServiceLisf()"
"OI, here's on orroy of services"
Ser
v
ic
e
S
e
r
v
e
r

Stub
PMI registry {on server}
"
O
I
,
h
e
r
e
's

f
h
e

s
f
u
b
"
2 CIienf coIIs gefServiceLisf() on fhe sfub. The ServiceServer
refurns on orroy of services
Server
Service rowser
{cIient}
Ser
v
ic
e
S
e
r
v
e
r

3 CIienf dispIoys fhe Iisf of services in o 0UI
Ser
v
ic
e
S
e
r
v
e
r

Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
638 chapter 18
Server
Service rowser
{cIient}
Ser
v
ic
e
S
e
r
v
e
r

4 User seIecfs from fhe Iisf, so cIienf coIIs fhe gefService()
mefhod on fhe remofe service. The remofe service refurns o
serioIi;ed objecf fhof is on ocfuoI service fhof wiII run inside
fhe cIienf browser.
How it works, continued...
universaI service browser
"gefService(seIecfedSvc)"
"OI, here's fhe service"
Service rowser
{cIient}
5 CIienf coIIs fhe gef0uiPoneI() on fhe serioIi;ed service objecf if
jusf gof from fhe remofe service. The 0UI for fhof service is
dispIoyed inside fhe browser, ond fhe user con inferocf wifh if
IocoIIy. Af fhis poinf, we don'f need fhe remofe service unIess/unfiI
fhe user decides fo seIecf onofher service.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 639
1 interfuce ServiceServer impIements Pemote
A reguIor oId PMI remofe inferfoce for fhe remofe service (fhe
remofe service hos fhe mefhod for geffing fhe service Iisf ond
refurning o seIecfed service).
The classes and interfaces:
2 cIuss ServiceServerImpI impIements ServiceServer
The ocfuoI PMI remofe service (exfends UnicosfPemofeObjecf).
Ifs job is fo insfonfiofe ond sfore oII fhe services (fhe fhings
fhof wiII be shipped fo fhe cIienf), ond regisfer fhe server ifseIf
(ServiceServerImpI) wifh fhe PMI regisfry.
3 cIuss Servicerowser
The cIienf. If buiIds o very simpIe 0UI, does o Iookup in fhe PMI
regisfry fo gef fhe ServiceServer sfub, fhen coIIs o remofe mefhod on
if fo gef fhe Iisf of services fo dispIoy in fhe 0UI Iisf.
4 interfuce Service
This is fhe key fo everyfhing. This very simpIe inferfoce hos jusf one
mefhod, gef0uiPoneI(). Every service fhof gefs shipped over fo fhe
cIienf musf impIemenf fhis inferfoce. This is whof mokes fhe whoIe fhing
UMIVEPSALl 8y impIemenfing fhis inferfoce, o service con come over
even fhough fhe cIienf hos no ideo whof fhe ocfuoI cIoss (or cIosses)
ore fhof moke up fhof service. AII fhe cIienf knows is fhof whofever
comes over, if impIemenfs fhe Service inferfoce, so if MUST hove o
gef0uiPoneI() mefhod.
The cIienf gefs o serioIi;ed objecf os o resuIf of coIIing
gefService(seIecfedSvc) on fhe ServiceServer sfub, ond oII fhe cIienf
soys fo fhof objecf is, "I don'f know who or whof you ore, buf I DO
know fhof you impIemenf fhe Service inferfoce, so I know I con coII
gef0uiPoneI() on you. And since gef0uiPoneI() refurns o JPoneI, I'II jusf
sIop if info fhe browser 0UI ond sforf inferocfing wifh ifl
5 cIuss DiceService impIements Service
0of dice7 If nof, buf you need some, use fhis service fo roII onywhere
from I fo o virfuoI dice for you.
6 cIuss MiniMusicService impIements Service
Pemember fhof fobuIous IiffIe 'music video' progrom from fhe frsf
0UI Code Iifchen7 We've furned if info o service, ond you con pIoy if
over ond over ond over unfiI your roommofes fnoIIy Ieove.
7 cIuss DuyOfTheWeekService impIements Service
Were you born on o Fridoy7 Type in your birfhdoy ond fnd ouf.

ger$erv|oesL|sr{j
ger$erv|oe{j
8erv|ce8erver|mp|
el3erv|cesL|sl()
el3erv|ce()
8erv|cerowser
ra|r()

gerSu|Pane|{j
0|ce8erv|ce
el0u|Pare|()
H|n|Hus|c8erv|ce
el0u|Pare|()
0ay0fTheweek8erv|ce
el0u|Pare|()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
640 chapter 18
universaI service code
interface 8ervice8erver {the remote interface}
import java.rmi.*;
public interface ServiceServer extends Remote {
Object[] getServiceList() throws RemoteException;
Service getService(Object serviceKey) throws RemoteException;
}
interface 8ervice {what the GU services implement}
import javax.swing.*;
import java.io.*;
public interface Service extends Serializable {
public JPanel getGuiPanel();
}
A ----.| M
| ----l- -l--.:-,
---: l- l-- --l-: l-
----l- :--:- -|| .-
A |.- -| |- ---~----l-` -l--.:-, l.l
---: l- --- --l- l.l .-] ----:.|
:--:- --:l .---l6-|.--||` 1-
-l--.:- -l--: --.|-.|-, :- l.l .-]
:|.:: -|----l- l- --:- -l--.:- -||
.-l--.l:.||] - --.|-.|-
1.l': . --:l, -:.-:- l- :--:-: -l
:- --- l- --- --- l- :----, .: .
--:-|l - l- :|--l :.||- -l--:-|` --
l- ----l- --:-----
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 641
import java.rmi.*;
import java.util.*;
import java.rmi.server.*;
public class ServiceServerImpl extends UnicastRemoteObject implements ServiceServer {
HashMap serviceList;


public ServiceServerImpl() throws RemoteException {
setUpServices();
}
private void setUpServices() {
serviceList = new HashMap();
serviceList.put(Dice Rolling Service, new DiceService());
serviceList.put(Day of the Week Service, new DayOfTheWeekService());
serviceList.put(Visual Music Service, new MiniMusicService());
}

public Object[] getServiceList() {
System.out.println(in remote);
return serviceList.keySet().toArray();

}

public Service getService(Object serviceKey) throws RemoteException {
Service theService = (Service) serviceList.get(serviceKey);
return theService;
}

public static void main (String[] args) {
try {
Naming.rebind(ServiceServer, new ServiceServerImpl());
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println(Remote service is running);
}
}
class 8ervice8ervermpl {the remote implementation}
A ----.| M
| -|----l.l--
1- :--:-: -|| - :l--- - . +.:M. :-||-:l-- |-:l-. - -ll- 6N!
--:l - l- :-||-:l--, ]-- -l 1w6 ~~ . -] --:l ||- . l--` .- .
.|-- --:l |-.l--- ]-- -.-l` |:-- .-- B -- ---- -- +.:M.`
w-- l- :--:l--:l-- : :.||-, -l.|-- l- .:l-.|
----:.| :--:-: |l:---:-, M-M-::--:-, -l:`
c|--l :.||: l: - ---- l- -l . |:l - :--:-: l-
:|.] - l- ---:-- |:- l- -:-- :.- :-|-:l ---` w-
:-- .- .--.] - l]- 6-:l |--- l-- l .: l--:
-:-` ] -.- .- .--.] - -:l l- r!/ l.l .--
- l- +.:M. w- ---'l :-- .- .:l-.| --:- --:l
--|-:: l- :|--l .:: -- l ] :.||- -l--:-|`
M.- l- :--:-: |l- .:l-.| :--:-
--:l:` .- -l l-- -l- l-
+.:M., -l . l-- -.-- |--
l- '-]'`
c|--l :.||: l: --l- .l-- l- -:-- :-|-:l: . :--:-
--- l- :|.]- |:l - :--:-: |l.l l -l --- l-
--l- .--` 1: :-- -:-: l- -] |l- :.-- -]
---.||] :--l l- l- :|--l` l- -l l- :----:---
:--:- --l - l- +.:M.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
642 chapter 18
import java.awt.*;
import javax.swing.*;
import java.rmi.*;
import java.awt.event.*;
public class ServiceBrowser {
JPanel mainPanel;
JComboBox serviceList;
ServiceServer server;
public void buildGUI() {
JFrame frame = new JFrame(RMI Browser);
mainPanel = new JPanel();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);

Object[] services = getServicesList();



serviceList = new JComboBox(services);
frame.getContentPane().add(BorderLayout.NORTH, serviceList);
serviceList.addActionListener(new MyListListener());
frame.setSize(500,500);
frame.setVisible(true);
}
void loadService(Object serviceSelection) {
try {
Service svc = server.getService(serviceSelection);

mainPanel.removeAll();
mainPanel.add(svc.getGuiPanel());
mainPanel.validate();
mainPanel.repaint();
} catch(Exception ex) {
ex.printStackTrace();
}
}

class 8erviceBrowser {the client}
l: --l- --: l- M| --:l-] |---,
-l: l- :l-, .- :.||: -l--:-|:l|`
|1- .:l-.| --l- : -- l- --l .-`
A l- :--:-: |.- .--.] - 6-:l:` l- l-
)c---B- |l- |:l` 1- )c---B- ---: -- l-
-.- :|.].|- l--: --l - -.: l- - l- .--.]
+---': ---- -- . l- .:l-.| :--:- l- l- 6c|, .l-- l-
-:-- .: :-|-:l- --- |1: --l- : :.||- ] l- ---l
|:l---- -- l- )c---B-` w- :.|| -l--:-|` -- l-
----l- :---- |l- :l- -- --:-----` .- .:: l l-
l-- l.l -.: :|.]- - l- |:l |-: : l- AM!
l-- -- ---.||] -l --- l- :---- --- -- :.||-
-l--:-|:l|`` 1- :---- --l---: l- .:l-.| :--:-
|:--.|--`, -: : .-l--.l:.||] -:--.|-- |l.-: l- M|`
.- -- :-|] :.|| l- -l6-|.--||` -- l- :--:- .- .
l- --:-|l |. )|.--|` l- l- ---:--': -.-|.--|
ServiceBrowser code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 643
Object[] getServicesList() {
Object obj = null;
Object[] services = null;
try {

obj = Naming.lookup(rmi://127.0.0.1/ServiceServer);

}
catch(Exception ex) {
ex.printStackTrace();
}
server = (ServiceServer) obj;


try {

services = server.getServiceList();

} catch(Exception ex) {
ex.printStackTrace();
}
return services;

}
class MyListListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {

Object selection = serviceList.getSelectedItem();
loadService(selection);
}
}
public static void main(String[] args) {
new ServiceBrowser().buildGUI();
}
}



l- l- M| |---, .- -l l- :l-
c.:l l- :l- l- l- ----l- -l--.:- l]-,
:- l.l -- :.- :.|| -l--:-|:l|` -- l
-l--:-|:l|` -: -: l- .--.] - 6-:l:,
l.l -- :|.] - l- )c---B- -- l- -:-- l-
:-|-:l ---
| --'-- ---, l --.-: l- -:-- -.- .
:-|-:l-- --- l- )c---B- |:l -,
l.- l- :-|-:l-- l-] -.- .- |-. l-
.---.l- :--:- |:-- l- |-.--:- --l-
-- l- ----: .-, l.l .:: l- :---- --
l- :--:- l.l :----:--: -l l: :-|-:l--`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
644 chapter 18
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class DiceService implements Service {
JLabel label;
JComboBox numOfDice;
public JPanel getGuiPanel() {
JPanel panel = new JPanel();
JButton button = new JButton(Roll `em!);
String[] choices = {1, 2, 3, 4, 5};
numOfDice = new JComboBox(choices);
label = new JLabel(dice values here);
button.addActionListener(new RollEmListener());
panel.add(numOfDice);
panel.add(button);
panel.add(label);
return panel;
}
public class RollEmListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
// roll the dice
String diceOutput = ;
String selection = (String) numOfDice.getSelectedItem();
int numOfDiceToRoll = Integer.parseInt(selection);
for (int i = 0; i < numOfDiceToRoll; i++) {
int r = (int) ((Math.random() * 6) + 1);
diceOutput += ( + r);
}
label.setText(diceOutput);

}
}
class Dice8ervice {a universal service, implements 8ervice}
+---': l- --- ---l.-l --l-' 1- --l- - l-
--:- -l--.:-~~ l- --- l- :|--l': ---. :.|| ---
l: :--:- : :-|-:l- .- |-.- /-- :.- - -.l--- ]--
-.-l - l- -l6-|.--||` --l-, .: |-- .: ]-- --l--- .
)|.--|, :- l -|: l- .:l-.| :-~--||- 6c|
+,-+ :+ ,-+:.|
Think about ways to improve the DiceService. One
suggestion: using what you learned in the GU| chapters,
make the dice graphical. Use a rectangle, and draw the
appropriate number of circles on each one, corresponding
to the roll for that particular die.
DiceService code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 645
class MiniMusic8ervice {a universal service, implements 8ervice}
import javax.sound.midi.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MiniMusicService implements Service {

MyDrawPanel myPanel;
public JPanel getGuiPanel() {
JPanel mainPanel = new JPanel();
myPanel = new MyDrawPanel();
JButton playItButton = new JButton(Play it);
playItButton.addActionListener(new PlayItListener());
mainPanel.add(myPanel);
mainPanel.add(playItButton);
return mainPanel;
}
public class PlayItListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();

sequencer.addControllerEventListener(myPanel, new int[] {127});
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
for (int i = 0; i < 100; i+= 4) {
int rNum = (int) ((Math.random() * 50) + 1);
if (rNum < 38) { // so now only do it if num <38 (75% of the time)
track.add(makeEvent(144,1,rNum,100,i));
track.add(makeEvent(176,1,127,0,i));
track.add(makeEvent(128,1,rNum,100,i + 2));
}
} // end loop

sequencer.setSequence(seq);
sequencer.start();
sequencer.setTempoInBPM(220);
} catch (Exception ex) {ex.printStackTrace();}
} // close actionperformed
} // close inner class
1: : .|| l- --:: :l- --- l-
c-- rl:-- - :.l-- |i, :- --
---'l .---l.l- l ..- ---
1- :--:- --l-' A|| l
--: : :|.] . -ll-- .-
l- -.-- :--:- |----
l- --:l.-|-: -|| ---l-.||]
- .-l-`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
646 chapter 18
public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);

}catch(Exception e) { }
return event;
}
class MyDrawPanel extends JPanel implements ControllerEventListener {

// only if we got an event do we want to paint
boolean msg = false;
public void controlChange(ShortMessage event) {
msg = true;
repaint();
}
public Dimension getPreferredSize() {
return new Dimension(300,300);
}
public void paintComponent(Graphics g) {
if (msg) {

Graphics2D g2 = (Graphics2D) g;
int r = (int) (Math.random() * 250);
int gr = (int) (Math.random() * 250);
int b = (int) (Math.random() * 250);
g.setColor(new Color(r,gr,b));
int ht = (int) ((Math.random() * 120) + 10);
int width = (int) ((Math.random() * 120) + 10);
int x = (int) ((Math.random() * 40) + 10);
int y = (int) ((Math.random() * 40) + 10);

g.llRect(x,y,ht, width);
msg = false;
} // close if
} // close method
} // close inner class
} // close class
class MiniMusic8ervice, continued...
MiniMusicService code
N-l- --- -- l: --l-- .- /--'-
:--- l .|| - l- -.:: c--rl:--
| ]-- -.-l .--l-- ---::-, l-]
.---l.l- l: :-- ]---:-|, l--
:--.-- l -l l- c--rl:-- -
l- A --] -.: :l--]' :.l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 647
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class DayOfTheWeekService implements Service {
JLabel outputLabel;
JComboBox month;
JTextField day;
JTextField year;
public JPanel getGuiPanel() {
JPanel panel = new JPanel();
JButton button = new JButton(Do it!);
button.addActionListener(new DoItListener());
outputLabel = new JLabel(date appears here);
DateFormatSymbols dateStuff = new DateFormatSymbols();
month = new JComboBox(dateStuff.getMonths());
day = new JTextField(8);
year = new JTextField(8);
JPanel inputPanel = new JPanel(new GridLayout(3,2));
inputPanel.add(new JLabel(Month));
inputPanel.add(month);
inputPanel.add(new JLabel(Day));
inputPanel.add(day);
inputPanel.add(new JLabel(Year));
inputPanel.add(year);
panel.add(inputPanel);
panel.add(button);
panel.add(outputLabel);
return panel;
}
public class DoItListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
int monthNum = month.getSelectedIndex();
int dayNum = Integer.parseInt(day.getText());
int yearNum = Integer.parseInt(year.getText());
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, monthNum);
c.set(Calendar.DAY_OF_MONTH, dayNum);
c.set(Calendar.YEAR, yearNum);
Date date = c.getTime();
String dayOfWeek = (new SimpleDateFormat(EEEE)).format(date);
outputLabel.setText(dayOfWeek);
}
}
}



class DayOfTheWeek8ervice {a universal service, implements 8ervice}
1- --:- -l--.:- --l-
l.l -|: l- 6c|
--- l- :.l-- |o ]-- --- . ------
- -- ----- .- .l- ---.ll- ---:
1: :-- : :|l|] ----l, -----,
-:.-:- l -:-: l- c.|--.- :|.:: A|:-, l-
-|-l.l-|---.l |-l: -: :-:] . .ll---
-- -- l- .l- :--| --l --l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
648 chapter 18
Caag:ata|atiaas!
)aa aJe it ta the eaJ.
WouIdn'f if be
dreomy if fhis were fhe end
of fhe book7 If fhere were no
more buIIef poinfs or pu;;Ies
or code Iisfings or onyfhing eIse7
8uf fhof's probobIy jusf o
fonfosy...
Of course, there's still the two appendices.
And the index.
And then there's the web site...
There's no escape, really.
the end... sort of
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
649
AeaJix A
Iiaa| CaJe kit:hea
Iiaa||y, the :a|ete ve:siaa aI the 5eat5ax!
!t :aaae:ts ta a si|e Kasi:Se:ve: sa that yaa :aa
seaJ aaJ :e:eive leat atte:as vith athe: :|ieats.
/--- --::.- -l: :--l l-
l- -l-- |.]--:, .|--
-l ]--- :-----l -.l
.ll---, --- ]-- l
:--|l'
Andy: groove #2
6hr|s: groove2 rev|sed
N|ge|: dance beat
dance beat
|-:--- --::.-: --- |.]--: c|: --- l- |-.
l- .ll--- l.l --: -l l, .- l-- :|: 'l.-l' l- |.] l
this is a new appendix
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
finaI BeatBox code
650 appendix A
import java.awt.*;
import javax.swing.*;
import java.io.*;
import javax.sound.midi.*;
import java.util.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.event.*;
public class BeatBoxFinal {
JFrame theFrame;
JPanel mainPanel;
JList incomingList;
JTextField userMessage;
ArrayList<JCheckBox> checkboxList;
int nextNum;
Vector<String> listVector = new Vector<String>();
String userName;
ObjectOutputStream out;
ObjectInputStream in;
HashMap<String, boolean[]> otherSeqsMap = new HashMap<String, boolean[]>();
Sequencer sequencer;
Sequence sequence;
Sequence mySequence = null;
Track track;

String[] instrumentNames = {Bass Drum, Closed Hi-Hat, Open Hi-Hat,Acoustic
Snare, Crash Cymbal, Hand Clap, High Tom, Hi Bongo, Maracas, Whistle,
Low Conga, Cowbell, Vibraslap, Low-mid Tom, High Agogo, Open Hi Conga};
int[] instruments = {35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63};

Final BeatBox client program
Most of this code is the same as the code from the CodeKitchens in the previous
chapters, so we don't annotate the whole thing again. The new parts include:
GU - two new components are added for the text area that displays incoming
messages (actually a scrolling list) and the text feld.
NETWORKNG - just like the SimpleChatClient in this chapter, the BeatBox now
connects to the server and gets an input and output stream.
THREADS - again, just like the SimpleChatClient, we start a 'reader' class that
keeps looking for incoming messages from the server. But instead of just text, the
messages coming in include TWO objects: the String message and the serialized
ArrayList (the thing that holds the state of all the checkboxes.)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix A FinaI Code Kitchen
you are here 651
public static void main (String[] args) {
new BeatBoxFinal().startUp(args[0]); // args[0] is your user ID/screen name
}
public void startUp(String name) {
userName = name;
// open connection to the server
try {
Socket sock = new Socket(127.0.0.1, 4242);
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
Thread remote = new Thread(new RemoteReader());
remote.start();
} catch(Exception ex) {
System.out.println(couldn't connect - you'll have to play alone.);
}
setUpMidi();
buildGUI();
} // close startUp
public void buildGUI() {
theFrame = new JFrame(Cyber BeatBox);
BorderLayout layout = new BorderLayout();
JPanel background = new JPanel(layout);
background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
checkboxList = new ArrayList<JCheckBox>();
Box buttonBox = new Box(BoxLayout.Y_AXIS);
JButton start = new JButton(Start);
start.addActionListener(new MyStartListener());
buttonBox.add(start);
JButton stop = new JButton(Stop);
stop.addActionListener(new MyStopListener());
buttonBox.add(stop);
JButton upTempo = new JButton(Tempo Up);
upTempo.addActionListener(new MyUpTempoListener());
buttonBox.add(upTempo);
JButton downTempo = new JButton(Tempo Down);
downTempo.addActionListener(new MyDownTempoListener());
buttonBox.add(downTempo);
JButton sendIt = new JButton(sendIt);
sendIt.addActionListener(new MySendListener());
buttonBox.add(sendIt);
userMessage = new JTextField();
A . :---.-~|-- .-----l -- ]--- ::---- -.--
!.-|- * .. B-.lB-|-.| l-||.:
N-l- --- :-l - l-
--l----, |/6, .- -.- |.-
:l.-l` l- --.-- l--.
6c| :--, --l- --- ---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
finaI BeatBox code
652 appendix A
buttonBox.add(userMessage);
incomingList = new JList();
incomingList.addListSelectionListener(new MyListSelectionListener());
incomingList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane theList = new JScrollPane(incomingList);
buttonBox.add(theList);
incomingList.setListData(listVector); // no data to start with
Box nameBox = new Box(BoxLayout.Y_AXIS);
for (int i = 0; i < 16; i++) {
nameBox.add(new Label(instrumentNames[i]));
}
background.add(BorderLayout.EAST, buttonBox);
background.add(BorderLayout.WEST, nameBox);
theFrame.getContentPane().add(background);
GridLayout grid = new GridLayout(16,16);
grid.setVgap(1);
grid.setHgap(2);
mainPanel = new JPanel(grid);
background.add(BorderLayout.CENTER, mainPanel);
for (int i = 0; i < 256; i++) {
JCheckBox c = new JCheckBox();
c.setSelected(false);
checkboxList.add(c);
mainPanel.add(c);
} // end loop
theFrame.setBounds(50,50,300,300);
theFrame.pack();
theFrame.setVisible(true);
} // close buildGUI
public void setUpMidi() {
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequence = new Sequence(Sequence.PPQ,4);
track = sequence.createTrack();
sequencer.setTempoInBPM(120);
} catch(Exception e) {e.printStackTrace();}
} // close setUpMidi
)|:l : . :------l -- .--'l
-:- ---- 1: : ---- l-
-:--- --::.-: .-- :|.]-
6-|] -:l-. - . ----.| :.l
---- ]-- -:l |66r .l l-
--::.-:, - l: . ]-- :.-
!|!c1 . --::.- --- l- |:l
l- |-. .- |.] l- .ll.:-
-.l .ll---
N-l- -|:- -- l: .- : ---
6-l l- ----:--, -.- .
----:-, .- -.- . 1-.:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix A FinaI Code Kitchen
you are here 653
public void buildTrackAndStart() {
ArrayList<Integer> trackList = null; // this will hold the instruments for each
sequence.deleteTrack(track);
track = sequence.createTrack();
for (int i = 0; i < 16; i++) {
trackList = new ArrayList<Integer>();
for (int j = 0; j < 16; j++) {
JCheckBox jc = (JCheckBox) checkboxList.get(j + (16*i));
if (jc.isSelected()) {
int key = instruments[i];
trackList.add(new Integer(key));
} else {
trackList.add(null); // because this slot should be empty in the track
}
} // close inner loop
makeTracks(trackList);
} // close outer loop
track.add(makeEvent(192,9,1,0,15)); // - so we always go to full 16 beats
try {
sequencer.setSequence(sequence);
sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY);
sequencer.start();
sequencer.setTempoInBPM(120);
} catch(Exception e) {e.printStackTrace();}
} // close method
public class MyStartListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
buildTrackAndStart();
} // close actionPerformed
} // close inner class
public class MyStopListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
sequencer.stop();
} // close actionPerformed
} // close inner class
public class MyUpTempoListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
oat tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((oat)(tempoFactor * 1.03));
} // close actionPerformed
} // close inner class
B-| . l-.: ] -.|- l--- l- :-:--:
l- -l l-- :l.l-, .- -.- l.l l- .-
-:l-----l |.- -.- l- M!--l -- l`
1: : --ll] :--|-, -l l : !xAc1|/ .: l
-.: - l- ----: :.l--:, :- ---- l- ----:
c--rl:--: l- -l l- -|| -|.-.l-- ..-
1- 6c| |:l----:
!.:l|] l- :.-- .: l-
----: :.l--': --:--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
finaI BeatBox code
654 appendix A
public class MyDownTempoListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
oat tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((oat)(tempoFactor * .97));
}
}
public class MySendListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
// make an arraylist of just the STATE of the checkboxes
boolean[] checkboxState = new boolean[256];
for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (check.isSelected()) {
checkboxState[i] = true;
}
} // close loop
String messageToSend = null;
try {
out.writeObject(userName + nextNum++ + : + userMessage.getText());
out.writeObject(checkboxState);
} catch(Exception ex) {
System.out.println(Sorry dude. Could not send it to the server.);
}
userMessage.setText();
} // close actionPerformed
} // close inner class
public class MyListSelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent le) {
if (!le.getValueIsAdjusting()) {
String selected = (String) incomingList.getSelectedValue();
if (selected != null) {
// now go to the map, and change the sequence
boolean[] selectedState = (boolean[]) otherSeqsMap.get(selected);
changeSequence(selectedState);
sequencer.stop();
buildTrackAndStart();
}
}
} // close valueChanged
} // close inner class

1: : --- l': . |-l |- l- -|-c.lc|--l, -:-l
-:l-. - :--- . l-- --::.-, -- :--.|-- l-- --:l:
|l- l-- --::.- .- l- -.l .ll---` .- --l- l-:-
l-- --:l: l- l- :-:-l --l-l :l--.- |l- l- :----`
1: : .|:- --- ~~ . |:l-|-:l--|:l---- l.l l-||: -:
--- l- -:-- -.- . :-|-:l-- -- l- |:l - --::.-:
w-- l- -:-- :-|-:l: . --::.-, -- |M
M
!l|A1!|/
|-. l- .::-:.l- -.l .ll--- |l': - l- +.:M
.
:.||- -l---:M
.` .- :l.-l |.]- l 1---': :---
l-:l: -:.-:- - |ll|- --] l-: .--l -ll-
|:l-|-:l--!--l:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix A FinaI Code Kitchen
you are here 655
public class RemoteReader implements Runnable {
boolean[] checkboxState = null;
String nameToShow = null;
Object obj = null;
public void run() {
try {
while((obj=in.readObject()) != null) {
System.out.println(got an object from server);
System.out.println(obj.getClass());
String nameToShow = (String) obj;
checkboxState = (boolean[]) in.readObject();
otherSeqsMap.put(nameToShow, checkboxState);
listVector.add(nameToShow);
incomingList.setListData(listVector);
} // close while
} catch(Exception ex) {ex.printStackTrace();}
} // close run
} // close inner class
public class MyPlayMineListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
if (mySequence != null) {
sequence = mySequence; // restore to my original
}
} // close actionPerformed
} // close inner class
public void changeSequence(boolean[] checkboxState) {
for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (checkboxState[i]) {
check.setSelected(true);
} else {
check.setSelected(false);
}
} // close loop
} // close changeSequence
public void makeTracks(ArrayList list) {
Iterator it = list.iterator();
for (int i = 0; i < 16; i++) {
Integer num = (Integer) it.next();
if (num != null) {
int numKey = num.intValue();
track.add(makeEvent(144,9,numKey, 100, i));
track.add(makeEvent(128,9,numKey,100, i + 1));
}
} // close loop
} // close makeTracks()

1: : l- l--. - ~~ --. - .l.
--- l- :---- |- l: :--, '.l.' -||
.|-.]: - l-- :--.|-- --:l: l-
l-- --::.- .- l- -.l .ll--- |.-
A--.]|:l - :-:- :l.l- .|--:`
w
-- . --::.- :---: -, -- --.
|-:--.|--` l- l-- --:l: |l-
--::.- .- l- A
--.]|
:l - B
--|-.-
:-:- :l.l- .|--:` .- . l l-
l- )|
:l :------l A
- l- . )|
:l
: . l--~:l- l- ]-- -- . /
-:l--
- l- |:l: .l. |/
-:l-- : .- -|~
.:--- A
--.]|
:l`, .- l-- l-|| l-
)|
:l l- -:- l.l /
-:l-- .: l': :---:-
-- -.l l- :|.] - l- |:l
1: --l- : :.||- --- l- -:-- :-|-:l:
:---l- --- l- |:l w- |MM!l|A1!|/
:.-- l- .ll--- l- l- --- l-] :-|-:l-
A|| l- M|l| :l- : -.:l|] l- :.-- .: l
-.: - l- ----: --:--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
finaI BeatBox code
656 appendix A
public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);
}catch(Exception e) { }
return event;
} // close makeEvent
} // close class





N-l- --- )-:l |- l- |.:l --:--
+,-+ :+ ,-+:.|
what are some of the ways you can improve this programI
Here are a few ideas to get you started:
l) Once you select a pattern, whatever current pattern was playing is blown
away. |f that was a new pattern you were working on (or a modification of
another one), you're out of luck. ou might want to pop up a dialog box that
asks the user if he'd like to save the current pattern.
2) |f you fail to type in a command-line argument, you |ust get an exception
when you run it! Put something in the main method that checks to see if
you've passed in a command-line argument. |f the user doesn't supply one,
either pick a default or print out a message that says they need to run it
again, but this time with an argument for their screen name.
3) |t might be nice to have a feature where you can click a button and it
will generate a random pattern for you. ou might hit on one you really like.
8etter yet, have another feature that lets you load in existing 'foundation'
patterns, like one for |azz, rock, reggae, etc. that the user can add to.
ou can find existing patterns on the Head Pirst 1ava web start.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix A FinaI Code Kitchen
you are here 657
import java.io.*;
import java.net.*;
import java.util.*;
public class MusicServer {
ArrayList<ObjectOutputStream> clientOutputStreams;
public static void main (String[] args) {
new MusicServer().go();
}
public class ClientHandler implements Runnable {
ObjectInputStream in;
Socket clientSocket;

public ClientHandler(Socket socket) {
try {
clientSocket = socket;
in = new ObjectInputStream(clientSocket.getInputStream());

} catch(Exception ex) {ex.printStackTrace();}
} // close constructor
public void run() {
Object o2 = null;
Object o1 = null;
try {
while ((o1 = in.readObject()) != null) {

o2 = in.readObject();

System.out.println(read two objects);
tellEveryone(o1, o2);
} // close while
} catch(Exception ex) {ex.printStackTrace();}
} // close run
} // close inner class
Final BeatBox server program
Most of this code is identical to the SimpleChatServer we made in the
Networking and Threads chapter. The only difference, in fact, is that this server
receives, and then re-sends, two serialized objects instead of a plain String
(although one of the serialized objects happens to a String).
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
finaI BeatBox code
658 appendix A
public void go() {
clientOutputStreams = new ArrayList<ObjectOutputStream>();
try {
ServerSocket serverSock = new ServerSocket(4242);
while(true) {
Socket clientSocket = serverSock.accept();
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
clientOutputStreams.add(out);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println(got a connection);
}
}catch(Exception ex) {
ex.printStackTrace();
}
} // close go
public void tellEveryone(Object one, Object two) {
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()) {
try {
ObjectOutputStream out = (ObjectOutputStream) it.next();
out.writeObject(one);
out.writeObject(two);
}catch(Exception ex) {ex.printStackTrace();}
}
} // close tellEveryone
} // close class
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
we covered a lot of ground, and you're almost finished with this book. we'll miss you, but before
we let you go, we wouldn't feel right about sending you out into 1avaLand without a little more
preparation. we can't possibly fit everything you'll need to know into this relatively small appendix.
Actually, we originally include everything you need to know about 1ava (not already covered by
the other chapters), by reducing the type point size to .00003. |t all fit, but nobody could read it. So,
we threw most of it away, but kept the best bits for this Top Ten appendix.
This really the end of the book. Lxcept for the index (a must-read!).
Appendix B
The Top Ten Topics that almost made it into the Real Book...
You meon, fhere's sfiII
MOPE7 Doesn'f fhis
book EVEP end7
659 this is a new appendix
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
660 appendix B
#10 Bit Manipulation
Why 4e yee rzrc!
Wc`vc ialIcu aloui ihc laci ihai ihcic aic S liis in a lyic,
16 liis in a shoii, anu so on. You mighi havc occasion io
iuin inuiviuual liis on oi oll. Ioi insiancc you mighi hnu
youiscll wiiiing couc loi youi ncw ]ava cnallcu ioasici,
anu icalizc ihai uuc io scvcic mcmoiy limiiaiions, cciiain
ioasici sciiings aic coniiollcu ai ihc lii lcvcl. Ioi casici
icauing, wc`ic showing only ihc lasi S liis in ihc commcnis
iaihci ihan ihc lull S2 loi an ini).
Bitwise NOT Operator: ~
This ociaioi uis all ihc liis` ol a iimiiivc.
int x = 10; // bits are 0000I0I0
x = ~x; // bits are now IIII0I0I
Thc ncxi ihicc ociaiois comaic iwo iimiiivcs on a lii
ly lii lasis, anu iciuin a icsuli lascu on comaiing ihcsc
liis. Wc`ll usc ihc lollowing cxamlc loi ihc ncxi ihicc
ociaiois:
int x = 10; // bits are 0000I0I0
int y = 6; // bits are 00000II0

Bitwise AND Operator: &
This ociaioi iciuins a valuc whosc liis aic iuincu on only
il both oiiginal liis aic iuincu on:
int a = x & y; // bits are 000000I0
Bitwise OR Operator: |
This ociaioi iciuins a valuc whosc liis aic iuincu on only
il either ol ihc oiiginal liis aic iuincu on:
int a = x | y; // bits are 0000III0
Bitwise XOR {exclusive OR} Operator: ^
This ociaioi iciuins a valuc whosc liis aic iuincu on only
il exoctIy one ol ihc oiiginal liis aic iuincu on:
int a = x y; // bits are 0000II00
The 8hift Operators
Thcsc ociaiois iaIc a singlc inicgci iimiiivc anu shili oi
sliuc) all ol iis liis in onc uiicciion oi anoihci. Il you wani
io uusi oll youi linaiy maih sIills, you mighi icalizc ihai
shiliing liis Ie cllcciivcly uI.I.e a numlci ly a owci ol
iwo, anu shiliing liis ..L cllcciivcly J...Je a numlci ly a
owci ol iwo.
Wc`ll usc ihc lollowing cxamlc loi ihc ncxi ihicc ociaiois:
int x = ~11; // bits are IIII0I0I
OI, oI, wc`vc lccn uiiing ii oll, hcic is ihc woilu`s
shoiicsi cxlanaiion ol sioiing ncgaiivc numlcis, anu
wo` oIeer. Rcmcmlci, ihc lclimosi lii ol an inicgci
numlci is callcu ihc sign bit. A ncgaiivc inicgci numlci in
]ava nIwn, has iis sign lii iuincu or i.c. sci io 1). A osiiivc
inicgci numlci always has iis sign lii iuincu o 0). ]ava
uscs ihc wo` oIeer loimula io sioic ncgaiivc numlcis.
To changc a numlci`s sign using iwo`s comlcmcni, ui all
ihc liis, ihcn auu 1 wiih a lyic, loi cxamlc, ihai woulu
mcan auuing 00000001 io ihc uicu valuc).
Right 8hift Operator: >>
This ociaioi shilis all ol a numlci`s liis iighi ly a cciiain
numlci, anu hlls all ol ihc liis on ihc lcli siuc wiih whaicvci
ihc oiiginal lclimosi lii was. Thc sign bit docs not changc:
int y = x >> 2; // bits are IIIIII0I

Unsigned Right 8hift Operator: >>>
]usi liIc ihc iighi shili ociaioi BUT ii AIWAYS hlls ihc
lclimosi liis wiih zcios. Thc sign bit might changc:
int y = x >>> 2; // bits are 00IIII0I
Left 8hift Operator: <<
]usi liIc ihc unsigncu iighi shili ociaioi, lui in ihc oihci
uiicciion, ihc iighimosi liis aic hllcu wiih zcios. Thc sign bit
might changc.
int y = x << 2; // bits are II0I0I00
bit manipuIation
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix B Top Ten Reference
you are here 661
#9 mmutability

Why 4e yee rzrc !hz! 8!r|n]s zrc |mme!z||c!
Whcn youi ]ava iogiams siaii io gci lig, you`ll
incviially cnu u wiih lois anu lois ol Siiing ol|ccis.
Ioi sccuiiiy uioscs, anu loi ihc saIc ol consciving
mcmoiy icmcmlci youi ]ava iogiams can iun on
iccny ]ava-cnallcu ccll honcs), Siiings in ]ava aic
immuiallc. Whai ihis mcans is ihai whcn you say:
String s 0,
for (int x I, x < I0, x++)
s s + x,

Whai`s aciually hacning is ihai you`ic cicaiing icn


Siiing ol|ccis wiih valucs 0", 01", 012", ihiough
012S467S9"). In ihc cnu is iclciiing io ihc Siiing
wiih ihc valuc 012S467S9", lui ai ihis oini ihcic
aic er Siiings in cxisicncc!
Whcncvci you maIc a ncw Siiing, ihc ]VM uis ii
inio a sccial aii ol mcmoiy callcu ihc Siiing Pool`
sounus iclicshing uocsn`i ii.). Il ihcic is alicauy
a Siiing in ihc Siiing Pool wiih ihc samc valuc, ihc
]VM uocsn`i cicaic a uulicaic, ii simly iclcis youi
iclcicncc vaiiallc io ihc cxisiing cniiy. Thc ]VM can
gci away wiih ihis lccausc Siiings aic immuiallc, onc
iclcicncc vaiiallc can`i changc a Siiing`s valuc oui
liom unuci anoihci iclcicncc vaiiallc iclciiing io
ihc samc Siiing.
Thc oihci issuc wiih ihc Siiing ool is ihai ihc
Gailagc Collccioi Joer` o Le.e. So in oui cxamlc,
unlcss ly coinciucncc you laici hacn io maIc a
Siiing callcu 012S4", loi insiancc, ihc hisi ninc
Siiings cicaicu in oui o. loo will |usi sii aiounu
wasiing mcmoiy.
How does this save memory?
Wcll, il you`ic noi caiclul, . Joer`! Bui il you un-
ucisianu how Siiing immuialiliiy woiIs, ihan you
can somciimcs iaIc auvaniagc ol ii io savc mcmoiy.
Il you havc io uo a loi ol Siiing maniulaiions liIc
concaicnaiions, cic.), howcvci, ihcic is anoihci class
SiiingBuiluci, lciici suiicu loi ihai uiosc. Wc`ll
ialI moic aloui SiiingBuiluci in a lcw agcs.
Why 4e yee rzrc !hz! Wrzppcrs zrc
|mme!z||c!
In ihc Maih chaici wc ialIcu aloui ihc iwo main
uscs ol ihc wiaci classcs:
- Wiaing a iimiiivc so ii can icicnu io lc an
ol|cci.
- Using ihc siaiic uiiliiy mcihous loi cxamlc,
Inicgci.aiscIni)).
Ii`s imoiiani io icmcmlci ihai whcn you cicaic a
wiaci ol|cci liIc:
Integer iWrap new Integer(4?),
Thai`s ii loi ihai wiaci ol|cci. Iis valuc will nIwn,
lc 42. There is no setter method [or o wropper object.
You can, ol couisc, iclci .V.n io a J.e.er wiaci
ol|cci, lui ihcn you`ll havc wo ol|ccis. Oncc you
cicaic a wiaci ol|cci, ihcic`s no way io changc
ihc .nIue ol ihai ol|cci!
M
.-
l
l:
koses ote teJ, v|olets ote olue.
5rrings nre immurnble, wrners nre ree.
6 |--' A ---: M.- l l:
l --- - l- .--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
662 appendix B
#8 Assertions
Wc havcn`i ialIcu much aloui how io uclug youi ]ava
iogiam whilc you`ic ucvcloing ii. Wc lclicvc ihai
you shoulu lcain ]ava ai ihc commanu linc, as wc`vc
lccn uoing ihioughoui ihc looI. Oncc you`ic a ]ava
io, il you ucciuc io usc an IDE*, you mighi havc
oihci uclugging iools io usc. In ihc olu uays, whcn
a ]ava iogiammci wanicu io uclug hci couc, shc`u
siicI a lunch ol Sysicm.oui.iiniln ) siaicmcnis
ihioughoui ihc iogiam, iiniing cuiicni vaiiallc
valucs, anu I goi hcic" mcssagcs, io scc il ihc uow
coniiol was woiIing iocily. Thc icauy-laIc couc
in chaici 6 lcli somc uclugging iini` siaicmcnis
in ihc couc.) Thcn, oncc ihc iogiam was woiIing
coiiccily, shc`u go ihiough anu iaIc all ihosc Sysicm.
oui.iiniln ) siaicmcnis lacI oui again. Ii was
icuious anu ciioi ionc. Bui as ol ]ava 1.4 anu .0),
uclugging goi a wholc loi casici. Thc answci.
Assertions
Assciiions aic liIc Sysicm.oui.iiniln ) siaicmcnis
on sicioius. Auu ihcm io youi couc as you woulu
auu iiniln siaicmcnis. Thc ]ava .0 comilci
assumcs you`ll lc comiling souicc hlcs ihai aic .0
comaiillc, so as ol ]ava .0, comiling wiih assciiions
is cnallcu ly uclauli.
Ai iuniimc, il you uo noihing, ihc asscii siaicmcnis
you auucu io youi couc will lc ignoicu ly ihc ]VM,
anu won`i slow uown youi iogiam. Bui il you icll ihc
]VM io ernbIe youi assciiions, ihcy will hcl you uo
youi uclugging, wiihoui changing a linc ol couc!
Somc lolIs havc comlaincu aloui having io lcavc
asscii siaicmcnis in ihcii iouuciion couc, lui
lcaving ihcm in can lc ically valuallc whcn youi
couc is alicauy ucloycu in ihc hclu. Il youi clicni
is having iioullc, you can insiiuci ihc clicni io iun
ihc iogiam wiih assciiions cnallcu, anu havc ihc
clicni scnu you ihc ouiui. Il ihc assciiions wcic
siiicu oui ol youi ucloycu couc, you`u ncvci
havc ihai oiion. Anu ihcic is almosi no uownsiuc,
whcn assciiions aic noi cnallcu, ihcy aic comlcicly
ignoicu ly ihc ]VM, so ihcic`s no ciloimancc hii io
woiiy aloui.
How to make Assertions work
Auu assciiion siaicmcnis io youi couc whcicvci you
lclicvc ihai somcihing u be .ue. Ioi insiancc:
assert (height > 0);
// if true, program continues normally
// if false, throw an AssertionError

You can auu a liiilc moic inloimaiion io ihc siacI
iiacc ly saying:
assert (height > 0) : height = +
height + weight = + weight;
Thc cxicssion alici ihc colon can lc any lcgal
]ava cxicssion thot resoIves to o non-nuII voIue. Bui
whaicvci you uo, don`t creote ossertions thot chonge on
object`s stote: Il you uo, cnalling assciiions ai iuniimc
mighi changc how youi iogiam ciloims.

Compiling and running with
Assertions
To o.Ie wiih assciiions:
javac TestDriveGame.java
Noiicc ihai no commanu linc oiions wcic
ncccssaiy.)
To .ur wiih assciiions:
java -ea TestDriveGame
assertions
* IDE sianus loi Inicgiaicu Dcvclomcni Enviionmcni
anu incluucs iools such as Eclisc, Boilanu`s ]Builuci, oi
ihc ocn souicc NciBcans ncilcans.oig).
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix B Top Ten Reference
you are here 663
In chaici 9, wc ialIcu aloui how local vaiiallcs
livc only as long as ihc mcihou in which ihcy`ic
ucclaicu siays on ihc siacI. Bui somc vaiiallcs can
havc cvcn Lo.e. lilcsans. Insiuc ol mcihous, wc
olicn cicaic bIoI ol couc. Wc`vc lccn uoing ihis
all along, lui wc havcn`i cxliciily nIIeJ in icims ol
bIoI. Tyically, llocIs ol couc occui wiihin mcihous,
anu aic lounucu ly cuily liaccs [ }. Somc common
cxamlcs ol couc llocIs ihai you`ll iccognizc incluuc
loos o., wL.Ie) anu conuiiional cxicssions liIc .
siaicmcnis).
Ici`s looI ai an cxamlc:
void doStuff()
int x = 0;
for(int y = 0; y < 5; y++)

x = x + y;


x = x * y;


In ihc icvious cxamlc, , was a llocI vaiiallc,
ucclaicu insiuc a llocI, anu , wcni oui ol scoc as
soon as ihc loi loo cnucu. Youi ]ava iogiams will
lc moic ucluggallc anu cxanuallc il you usc local
vaiiallcs insicau ol insiancc vaiiallcs, anu llocI
vaiiallcs insicau ol local vaiiallcs, whcncvci ossillc.
Thc comilci will maIc suic ihai you uon`i iiy io usc
a vaiiallc ihai`s gonc oui ol scoc, so you uon`i havc
io woiiy aloui iuniimc mcliuowns.
#7 Block 8cope
|-:.| .-.|- ::-- l- l- --l-- --l-
---- - . -- |-- |-:, .- ] :
::-- l- --|] l- -- |--'
N- --|--, .- ] .-- -l - ::--
A.:' w--'l :--|-' ] : --l - ::-- ---' |l: : --l l- -.] l ---: - :--- -l-- |.--.-:, :- --.--'`
-- - l- -- |-- |-:
-- - l- --l- |-:, --- : .|:- --l - ::--
:l.-l - l- --l- |-:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
664 appendix B
#6 Linked nvocations
Whilc you uiu scc a liiilc ol ihis in ihis looI, wc iiicu io Icc oui syniax as clcan anu
icauallc as ossillc. Thcic aic, howcvci, many lcgal shoiicuis in ]ava, ihai you`ll no uouli
lc cxoscu io, csccially il you havc io icau a loi couc you uiun`i wiiic. Onc ol ihc moic
common consiiucis you will cncounici is Inown as I.rIeJ .r.on.or. Ioi cxamlc:
StringBuffer sb = new StringBuffer(spring);
sb = sb.delete(3,6).insert(2,umme).deleteCharAt(1);
System.out.println(sb = + sb);
// result is sb = summer
Whai in ihc woilu is hacning in ihc scconu linc ol couc. Aumiiiculy, ihis is a coniiivcu
cxamlc, lui you nccu io lcain how io uccihci ihcsc.
1 - WoiI liom lcli io iighi.
2 - Iinu ihc icsuli ol ihc lclimosi mcihou call, in ihis casc sb.delete(3,6). Il you
looI u SiiingBullci in ihc API uocs, you`ll scc ihai ihc delete() mcihou iciuins a
SiiingBullci ol|cci. Thc icsuli ol iunning ihc delete() mcihou is a SiiingBullci ol|cci
wiih ihc valuc si".
S - Thc ncxi lclimosi mcihou insert())is callcu on ihc ncwly cicaicu SiiingBullci
ol|cci si". Thc icsuli ol ihai mcihou call ihc insert() mcihou), is nIo a SiiingBullci
ol|cci alihough ii uocsn`i havc io lc ihc samc iyc as ihc icvious mcihou iciuin), anu so
ii gocs, ihc iciuincu ol|cci is uscu io call ihc ncxi mcihou io ihc iighi. In ihcoiy, you can
linI as many mcihous as you wani in a singlc siaicmcni alihough ii`s iaic io scc moic ihan
ihicc linIcu mcihous in a singlc siaicmcni). Wiihoui linIing, ihc scconu linc ol couc liom
alovc woulu lc moic icauallc, anu looI somcihing liIc ihis:
sb = sb.delete(3,6);
sb = sb.insert(2,umme);
sb = sb.deleteCharAt(1);
Bui hcic`s a moic common, anu usclul cxamlc, ihai you saw us using, lui wc ihoughi
wc`u oini ii oui again hcic. This is loi whcn youi main) mcihou nccus io invoIc an
insiancc mcihou ol ihc main class, lui you uon`i nccu io Icc a .ee.ere io ihc insiancc ol
ihc class. In oihci woius, ihc main) nccus io cicaic ihc insiancc orI, so ihai main) can
invoIc onc ol ihc insiancc`s eLoJ.
class Foo {
public static void main(String [] args) [
new Foo().go();
}
void go() {
// here's what we REALLY want...
}
}
-- -.-l l- :.|| -|`, -l -- --'l :.-- .--l
l- |-- -:l.-:-, :- -- --'l -l-- .::--
l- --- |-- --:l l- . ------:-
Iinked invocations
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix B Top Ten Reference
you are here 665
#5 Anonymous and 8tatic Nested Classes
A :l.l: --:l- :|.:: : -:l l.l-.
:|.:: --:|-:- -l- .--l--, .-
-.-- -l l- :l.l: ----
Nested classes come in many havors
In ihc GUI cvcni-hanuling scciion ol ihc looI, wc siaiicu using innci ncsicu) classcs as a
soluiion loi imlcmcniing lisicnci inicilaccs. Thai`s ihc mosi common, iaciical, anu icau-
allc loim ol an innci class-whcic ihc class is simly ncsicu wiihin ihc cuily liaccs ol anoihci
cnclosing class. Anu icmcmlci, ii mcans you nccu an insiancc ol ihc ouici class in oiuci io gci
an insiancc ol ihc innci class, lccausc ihc innci class is a ebe. ol ihc ouici/cnclosing class.
Bui ihcic aic oihci Iinus ol innci classcs incluuing n. anu nror,ou. Wc`ic noi going
inio ihc uciails hcic, lui wc uon`i wani you io lc ihiown ly siiangc syniax whcn you scc ii in
somconc`s couc. Bccausc oui ol viiiually anyihing you can uo wiih ihc ]ava languagc, cihas
noihing iouuccs moic lizaiic-looIing couc ihan anonymous innci classcs. Bui wc`ll siaii wiih
somcihing simlci-siaiic ncsicu classcs.
8tatic nested classes
You alicauy Inow whai siaiic mcans-somcihing iicu io ihc class, noi a aiiiculai insiancc. A
siaiic ncsicu class looIs |usi liIc ihc non-siaiic classcs wc uscu loi cvcni lisicncis, cxcci ihcy`ic
maiIcu wiih ihc Icywoiu .
public class FooOuter {
static class BarInner {
void sayIt() {
System.out.println(method of a static inner class);
}
}
}
class Test {
public static void main (String[] args) {
FooOuter.BarInner foo = new FooOuter.BarInner();
foo.sayIt();
}
}

B-:.-:- . :l.l: --:l- :|.:: ::l.l:, ]-- --'l
-:- .- -:l.-:- - l- --l-- :|.:: /-- -:l -:- l-
-.-- - l- :|.::, l- :.-- -.] ]-- --- :l.l:
--l-: -- .::-:: :l.l: .-.|-:
Siaiic ncsicu classcs aic moic liIc icgulai non-ncsicu classcs in ihai ihcy uon`i cn|oy a sccial iclaiion-
shi wiih an cnclosing ouici ol|cci. Bui lccausc siaiic ncsicu classcs aic siill consiucicu a ebe. ol
ihc cnclosing/ouici class, ihcy siill gci acccss io any iivaic mcmlcis ol ihc ouici class... lui orI, Le
ore Ln n.e nIo n.. Sincc ihc siaiic ncsicu class isn`i connccicu io an insiancc ol ihc ouici class, ii
uocsn`i havc any sccial way io acccss ihc non-siaiic insiancc) vaiiallcs anu mcihous.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
when arrays aren't enough
666 appendix B
#5 Anonymous and 8tatic Nested Classes, continued
The difference between nested and inner
Any ]ava class ihai`s uchncu wiihin ihc scoc ol anoihci class is Inown as a nested class. Ii
uocsn`i maiici il ii`s anonymous, siaiic, noimal, whaicvci. Il ii`s insiuc anoihci class, ii`s
icchnically consiucicu a reeJ class. Bui ror-n. ncsicu classcs aic olicn iclciicu io as .rre.
classcs, which is whai wc callcu ihcm cailici in ihc looI. Thc loiiom linc: all innci classcs aic
ncsicu classcs, lui noi all ncsicu classcs aic innci classcs.
Anonymous inner classes
Imaginc you`ic wiiiing somc GUI couc, anu suuucnly icalizc ihai you nccu an insiancc
ol a class ihai imlcmcnis AciionIisicnci. Bui you icalizc you uon`i Ln.e an insiancc ol an
AciionIisicnci. Thcn you icalizc ihai you also ncvci wioic a In loi ihai lisicnci. You havc iwo
choiccs ai ihai oini:
1) Wiiic an innci class in youi couc, ihc way wc uiu in oui GUI couc, anu ihcn insianiiaic ii
anu ass ihai insiancc inio ihc luiion`s cvcni icgisiiaiion auuAciionIisicnci)) mcihou.
OR
2) Cicaic an nror,ou innci class anu insianiiaic ii, iighi ihcic, |usi-in-iimc. LiteroIIy right
where you ore ot the point you need the Iistener object. Thai`s iighi, you cicaic ihc class anu ihc
insiancc in ihc lacc whcic you`u noimally lc sulying |usi ihc insiancc. ThinI aloui ihai loi
a momcni-ii mcans you ass ihc cniiic In whcic you`u noimally ass only an .rnre inio a
mcihou aigumcni!
import java.awt.event.*;
import javax.swing.*;
public class TestAnon {
public static void main (String[] args) {
JFrame frame = new JFrame();
JButton button = new JButton(click);
frame.getContentPane().add(button);
// button.addActionListener(quitListener);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
System.exit(0);
}
});

}
}
w- -.- . -.-- .- .- . -ll--, .- --- --
--- l- --:l-- .- .:l-- |:l---- -l l- -ll--
!:-l -- ---- -.- . :|.:: l.l -|----l: l-
A:l--|:l---- -l--.:-
N---.||] --' - :---l- |- l:-.::- -
. ------:- l- .- -:l.-:- - .- ---- :|.:: .-
---- :|.:: l.l -|----l: A:l--|:l---- |.-
l- .:l--|------|` --l-`
B-l --- -:l-. - .::- - .- --:l
------:-, -- .:: - l- --|- ---
:|.:: --l--'' |- -l-- ---:, --
--l- l- :|.:: l.l -|----l: A:~
l--|:l---- |6+1 +!! w+!! w!
N!!l |1 1- :]-l. .|:- :--.l-: .-
-:l.-:- - l- :|.:: .-l--.l:.||]
N-l:- l.l -- :.] --- A:l--|:l----|`' ---
l-- A:l--|:l---- : .- -l--.:- .- :- ]--
:.-'l MAr! .- -:l.-:- - l' B-l l: :]-l.
--.||] --.-:, :--.l- . --- :|.:: |-l -- -.--`
l.l -|----l: l- A:l--|:l---- -l--.:-,
.- ] l- -.], ---': l- -|----l.l-- - l-
-l--.:- --l-: .:l--|------|`
med
1: :l.l----l
--: --- ---'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix B Top Ten Reference
you are here 667
]ava has ou. acccss Ie.eI anu L.ee acccss oJ.e.. Thcic aic only L.ee mouihcis lccausc
ihc JenuI whai you gci whcn you uon`i usc any acccss mouihci) . onc ol ihc loui
acccss lcvcls.
Access Levels in oiuci ol how icsiiiciivc ihcy aic, liom lcasi io mosi icsiiiciivc)
ubI.
.oeeJ
JenuI
...ne
Access modihers
public
protected
private
Mosi ol ihc iimc you`ll usc only ullic anu iivaic acccss lcvcls.
public
Usc ullic loi classcs, consianis siaiic hnal vaiiallcs), anu mcihous ihai you`ic
cxosing io oihci couc loi cxamlc gciicis anu sciicis) anu mosi consiiuciois.
private
Usc iivaic loi viiiually all insiancc vaiiallcs, anu loi mcihous ihai you uon`i wani
ouisiuc couc io call in oihci woius, mcihous ueJ ly ihc ullic mcihous ol youi class).
Bui alihough you mighi noi usc ihc oihci iwo ioiccicu anu uclauli), you siill nccu io
Inow whai ihcy uo lccausc you`ll scc ihcm in oihci couc.
#4 Access Levels and Access Modihers {Who 8ees What}
-|: --.-: .-] :-- .-]---- :.- .::-:: l- -|: l- |]
'l-' -- --.- :|.::, .-.|-, --l-, :--:l--:l--, -l:`
--l-:l- ---: -:l |- -.-|l |:-- - l- :.-- .:.- .: .::-::`, !xc!|1 l
.|:- .||--: :-:|.::-: --l:- l- .:.- l- ---l l- --l-:l- l-
-.-|l .::-:: --.-: l.l --|] :-- -l- l- :.-- .:.- .:
l- :|.:: -l l- -.-|l l- :.- .::-:: l- -.-|l l-
-.l- --.-: l.l --|] :-- -l- l- :.-- :|.:: :.- .::-:: l- -.l- l-
r-- - -- l --.-: -.l- l- l- :|.::, --l -.l- l- l- --:l 6-- l-
:.- :-- .--l-- l- --:l': -.l- :l-, -l . c.l :.-'l :-- . l-': -.l-:
access IeveIs
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
when arrays aren't enough
668 appendix B
default and protected
default
Boih ioiccicu anu uclauli acccss lcvcls aic iicu io acIagcs. Dclauli acccss is simlc-ii
mcans ihai only couc w.L.r Le ne nIne can acccss couc wiih uclauli acccss. So a
uclauli class, loi cxamlc which mcans a class ihai isn`i cxliciily ucclaicu as ubI.) can
lc acccsscu ly only classcs wiihin ihc samc acIagc as ihc uclauli class.
Bui whai uocs ii ically mcan io ne a class. Couc ihai uocs noi havc acccss io a class is
noi allowcu io cvcn L.rI aloui ihc class. Anu ly ihinI, wc mcan ue ihc class in couc.
Ioi cxamlc, il you uon`i havc acccss io a class, lccausc ol acccss icsiiiciion, you aicn`i
allowcu io insianiiaic ihc class oi cvcn ucclaic ii as a iyc loi a vaiiallc, aigumcni, oi
iciuin valuc. You simly can`i iyc ii inio youi couc ai all! Il you uo, ihc comilci will
comlain.
ThinI aloui ihc imlicaiions-a uclauli class wiih ullic mcihous mcans ihc ullic
mcihous aicn`i ically ullic ai all. You can`i acccss a mcihou il you can`i ee ihc class.
Why woulu anyonc wani io icsiiici acccss io couc wiihin ihc samc acIagc. Tyically,
acIagcs aic ucsigncu as a giou ol classcs ihai woiI iogcihci as a iclaicu sci. So ii mighi
maIc scnsc ihai classcs wiihin ihc samc acIagc nccu io acccss onc anoihci`s couc, whilc
as a acIagc, only a small numlci ol classcs anu mcihous aic cxoscu io ihc ouisiuc
woilu i.c. couc ouisiuc ihai acIagc).
OK, ihai`s uclauli. Ii`s simlc-il somcihing has uclauli acccss which, icmcmlci, mcans
no cxlicii acccss mouihci!), only couc wiihin ihc samc acIagc as ihc uclauli L.r
class, vaiiallc, mcihou, innci class) can acccss ihai L.r.
Thcn whai`s .oeeJ loi.
protected
Pioiccicu acccss is almosi iucniical io uclauli acccss, wiih onc cxcciion: ii allows sul-
classcs io .rLe.. ihc ioiccicu ihing, e.er . Loe ubIne n.e ou.Je Le nIne o Le ue.-
In Le, e:erJ. Thai`s ii. Thai`s nII ioiccicu luys you-ihc aliliiy io lci youi sulclasscs
lc ouisiuc youi suciclass acIagc, yci siill .rLe.. icccs ol ihc class, incluuing mcihous
anu consiiuciois.
Many ucvclocis hnu vciy liiilc icason io usc ioiccicu, lui ii is uscu in somc ucsigns,
anu somc uay you mighi hnu ii io lc cxacily whai you nccu. Onc ol ihc inicicsiing ihings
aloui ioiccicu is ihai-unliIc ihc oihci acccss lcvcls-ioiccicu acccss alics only io
.rLe..nre. Il a sulclass-ouisiuc-ihc-acIagc has a .ee.ere io an insiancc ol ihc suciclass
ihc suciclass ihai has, say, a ioiccicu mcihou), ihc sulclass can`i acccss ihc io-
iccicu mcihou using ihai suciclass iclcicncc! Thc only way ihc sulclass can acccss ihai
mcihou is ly .rLe...r ii. In oihci woius, ihc sulclass-ouisiuc-ihc-acIagc uocsn`i havc
ne io ihc ioiccicu mcihou, ii |usi Ln ihc mcihou, ihiough inhciiiancc.
#4 Access Levels and Access Modihers, cont.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix B Top Ten Reference
you are here 669
#3 8tring and 8tringBuffer/8tringBuilder Methods
Two ol ihc mosi commonly uscu classcs in ihc ]ava API aic Siiing anu SiiingBullci icmcmlci liom
#9 a lcw agcs lacI, Siiings aic immuiallc, so a SiiingBullci/SiiingBuiluci can lc a loi moi clhcicni
il you`ic maniulaiing a Siiing). As ol ]ava .0 you shoulu usc ihc SiiingBuiIder class insicau ol
SiiingBu[[er, unlcss youi Siiing maniulaiions nccu io lc ihicau-salc, which is noi common. Hcic`s a
liicl ovcivicw ol ihc mcihous in ihcsc classcs:
Both String ond StringBu[[er,StringBuiIder cIosses hove:
chai chaiAiini inucx), // whai chai is ai a cciiain osiiion
ini lcngih), // how long is ihis
Siiing sulsiiingini siaii, ini cnu), // gci a aii ol ihis
Siiing ioSiiing), // whai`s ihc Siiing valuc ol ihis
To concotenote Strings:
Siiing concaisiiing), // loi ihc Siiing class
Siiing acnuSiiing), // loi SiiingBullci 8 SiiingBuiluci
The String cIoss hos:
Siiing iclaccchai olu, chai ncw), // iclacc all occuicnccs ol a chai
Siiing sulsiiingini lcgin, ini cnu), // gci a oiiion ol a Siiing
chai ]| ioChaiAiiay), // convcii io an aiiay ol chais
Siiing ioIowciCasc), // convcii all chaiacicis io lowci casc
Siiing ioUciCasc), // convcii all chaiacicis io uci casc
Siiing iiim), // icmovc whiicsacc liom ihc cnus
Siiing valucOlchai ]|) // maIc a Siiing oui ol a chai aiiay
Siiing valucOlini i) // maIc a Siiing oui ol a iimiiivc
// oihci iimiiivcs aic suoiicu as wcll
The StringBu[[er c StringBuiIder cIosses hove:
SiiingBxxxx uclcicini siaii, ini cnu), // uclcic a oiiion
SiiingBxxxx insciiini ollsci, any iimiiivc oi a chai ]|), // inscii somcihing
SiiingBxxxx iclaccini siaii, ini cnu, Siiing s), // iclacc ihis aii wiih ihis Siiing
SiiingBxxxx icvcisc), // icvcisc ihc SB liom lioni io lacI
voiu sciChaiAiini inucx, chai ch), // iclacc a givcn chaiacici
Noic: SiiingBxxxx iclcis io ciihci Siiing oi Siiing, as aioiiaic.
String and StringBuffer
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
when arrays aren't enough
670 appendix B
#2 Multidimensional Arrays
In mosi languagcs, il you cicaic, say, a 4 x 2 iwo-uimcnsional aiiay, you woulu visualizc a
iccianglc, 4 clcmcnis ly 2 clcmcnis, wiih a ioial ol S clcmcnis. Bui in ]ava, such an aiiay
woulu aciually lc : aiiays linIcu iogcihci! In ]ava, a iwo uimcnsional aiiay is simly nr n..n,
o n..n,. A ihicc uimcnsional aiiay is an aiiay ol aiiays ol aiiays, lui wc`ll lcavc ihai loi
you io lay wiih.) Hcic`s how ii woiIs
int[][] a2d = new int [4][2];
Thc ]VM cicaics an aiiay wiih 4 clcmcnis. EnL ol ihcsc loui clcmcnis is aciually a iclcicncc
vaiiallc iclciiing io a ncwly cicaicu), ini aiiay wiih 2 clcmcnis.

Working with multidimensional arrays
- To acccss ihc scconu clcmcni in ihc ihiiu aiiay: int x = a2d[2][1]; // remember, 0 based!
- To maIc a onc-uimcnsional iclcicncc io onc ol ihc sul-aiiays: int[] copy = a2d[1];
- Shoii-cui iniiializaiion ol a 2 x S aiiay: int[][] x = { { 2,3,4 }, { 7,8,9 } };
- To maIc a 2u aiiay wiih iiicgulai uimcnsions:
int[][] y = new int [2][]; // makes only the hrst array, with a length of 2
y[0] = new int [3]; // makes the hrst sub-array 3 elements in length
y[1] = new int [5]; // makes the second sub-array 5 elements in length
inf orroy objecf (inf[][])
inf[][]

inf inf
------ l.l l- .--.] l:-| : .- --:l
|.- .--.] -|- ------:-: l- -l .--.]:`
inf[] inf[] inf[] inf[]
inf inf inf inf
inf inf
+
-l|1 ------:- .-.|-:
inf orroy (inf[])
inf orroy (inf[])
inf orroy (inf[])
inf orroy (inf[])
.i|o
1|o
1
.i|o
1||1
.i
|?1|o
1
---|.- -l: - -:- -.:
- l- -l -|----l:
.i|i1||1
.i||1
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix B Top Ten Reference
you are here 671
And the number one topic that didn't quite make it in...
#1 Enumerations {also called Enumerated Types or Enums}
Wc`vc ialIcu aloui consianis ihai aic uchncu in ihc API, loi insiancc,
JFrame.EXIT_ON_CLOSE. You can also cicaic youi own consianis ly
maiIing a vaiiallc static nal. Bui somciimcs you`ll wani io cicaic a sci
ol consiani valucs io icicscni ihc valiu valucs loi a vaiiallc. This sci ol
valiu valucs is commonly iclciicu io as an erue.n.or. Bcloic ]ava .0 you
coulu only uo a hall-laIcu |ol ol cicaiing an cnumciaiion in ]ava. As ol ]ava
.0 you can cicaic lull ucugcu cnumciaiions ihai will lc ihc cnvy ol all youi
ic-]ava .0-using liicnus.
Who's in thc band?
Ici`s say ihai you`ic cicaiing a wclsiic loi youi lavoiiic lanu, anu you wani io
maIc suic ihai all ol ihc commcnis aic uiiccicu io a aiiiculai lanu mcmlci.
Thc old way to Iakc an cnum:
enumerations
public static hnal int JERRY = 1;
public static hnal int BOBBY = 2;
public static hnal int PHIL = 3;
// later in the code
if (selectedBandMember == JERRY) {
// do JERRY related stuff
}
Thc goou ncws aloui ihis icchniquc is ihai ii DOES maIc ihc couc casici io
icau. Thc oihci goou ncws is ihai you can`i cvci changc ihc valuc ol ihc laIc
cnums you`vc cicaicu, JERRY will always lc 1. Thc lau ncws is ihai ihcic`s
no casy oi goou way io maIc suic ihai ihc valuc ol selectedBandMember
will always lc 1, 2, oi 3. Il somc haiu io hnu iccc ol couc scis
selectedBandMember cqual io 812, ii`s iciiy liIcly youi couc will licaI...
w-'-- -- l.l ] l- l-- -- -l ---
:-|-:l-B.-M----' .: . .| .|--'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
when arrays aren't enough
672 appendix B
public enum Members { JERRY, BOBBY, PHIL };
public Members selectedBandMember;
// later in the code
if (selectedBandMember == Members.JERRY) {
// do JERRY related stuff
}
Thc samc siiuaiion using a gcnuinc ]ava .0 cnum. Whilc ihis is a vciy lasic
cnumciaiion, mosi cnumciaiions usually ihis simlc.
A ncw, oIhcial cnum:
#1 Enumerations, cont.
1
: - - |--: |- . :-|- :|.:: --l--
--:-'l l |l l---: --l l.l ----: A
! .
:-:.| - - :|.:: +--- --'- :--.l- . ---
------.l- l]- :.||- M
----:'
1- :-|-:l-B.-M----' .-.|- : - l]-
M----:', .- :.- 6N|/ .- . .|-- -
)!/', B6BB/', -- |+||'
N- --- l- ----] .--l l: .-.|-': .|--'
Whcn you cicaic an cnum, you`ic cicaiing a ncw class, anu you`re impIicitIy extending
java.lang.Enum. You can ucclaic an cnum as iis own sianualonc class, in iis own
souicc hlc, oi as a mcmlci ol anoihci class.
Your enum extends ]ava.lang.Enum
Using if and switch with Enums
Using ihc cnum wc |usi cicaicu, wc can ciloim lianchcs in oui couc using ciihci
ihc if oi switch siaicmcni. Also noiicc ihai wc can comaic cnum insianccs using
ciihci == oi ihc .equals() mcihou. Usually == is consiucicu lciici siylc.
Members n = Members.BOBBY;
if (n.equals(Members.JERRY)) System.out.println(Jerrrry!);
if (n == Members.BOBBY) System.out.println(Rat Dog);
Members ifName = Members.PHIL;
switch (ifName) {
case JERRY: System.out.print(make it sing );
case PHIL: System.out.print(go deep );
case BOBBY: System.out.println(Cassidy! );
}
1- :]-l. l- ---- l- .- ---- -:l.-:-'
B
-l - l-:- --- --'
.l l
-' : --l-
|- 6--' w.l': l- --l-l
- - - c . : : ] '
A-:---
A::-- .- ---- .|-- l- . .-.|-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix B Top Ten Reference
you are here 673
public class HfjEnum {
enum Names {
JERRY(lead guitar) { public String sings() {
return plaintively; }
},
BOBBY(rhythm guitar) { public String sings() {
return hoarsely; }
},
PHIL(bass);
private String instrument;
Names(String instrument) {
this.instrument = instrument;
}
public String getInstrument() {
return this.instrument;
}
public String sings() {
return occasionally;
}
}
public static void main(String [] args) {
for (Names n : Names.values()) {
System.out.print(n);
System.out.print(, instrument: + n.getInstrument());
System.out.println(, sings: + n.sings());
}
}
}
#1 Enumerations, completed
enumerations
You can auu a lunch ol ihings io youi cnum liIc a consiiucioi, mcihous,
vaiiallcs, anu somcihing callcu a consiani-sccihc class louy. Thcy`ic
noi common, lui you mighi iun inio ihcm:
A really tricked-out version of a similar enum
%java HfjEnum
JERRY, instrument: lead guitar, sings: plaintively
BOBBY, instrument: rhythm guitar, sings: hoarsely
PHIL, instrument: bass, sings: occasionally
%
File Edit Window Help Bootleg
1-:- .-- l- :-~:.||-
:--:l.-l~:-:: :|.:: --:'
1- - l-- .: ----- l-
.:: ---- --l- |- l: :.:-
l- :-|`' --l-`, :-|` :
:.||- -- . .-.|- -l .- ----
.|-- - )!/ -- B6BB/
N-l:- l.l l- .:: :-|`'
--l- : --|] :.||- --- l-
---- .|-- .: -- :--:l.-l~
:-:: :|.:: -]
1
: : .- .-----l .::- - l-
l- :--:l--:l-- -:|.-- -|--
1: : l- ----': :--:l--:l-- |l ---:
--:- -- -.: -:|.-- ---- .|-- |-
l: :.:- l ---: l--- l--:`
/--'|| :-- l-:- --l-: -- :.||- --- -.-|`'
!--] ---- :---: -l .
-|l~- .|--:|`' --l-
-: : l]:.||] -:- - .
--' |-- .: :---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
when arrays aren't enough
674 appendix B
Captain Byte oI the Flatland starship 'Traverser had received an urgent, Top Secret transmission
Irom headquarters. The message contained 30 heavily encrypted navigational codes that the
Traverser would need to successIully plot a course home through enemy sectors. The enemy
Hackarians, Irom a neighboring galaxy, had devised a devilish code-scrambling ray that was capable
oI creating bogus objects on the heap oI the Traverser`s only navigational computer. In
addition, the alien ray could alter valid reIerence variables so that they reIerred to these
bogus objects. The only deIense the Traverser crew had against this evil Hackarian ray was
to run an inline virus checker which could be imbedded into the Traverser`s state oI the art
Java 1.4 code.
Captain Byte gave Ensign Smith the Iollowing programming instructions to process the critical
navigational codes:
'Put the frst fve codes in an array oI type ParsecKey. Put the last 25 codes in a fve by fve, two
dimensional array oI type QuadrantKey. Pass these two arrays into the plotCourse() method oI the
public fnal class ShipNavigation. Once the course object is returned run the inline virus checker
against all the programs reIerence variables and then run the NavSim program and bring me the
results.
A Iew minutes later Ensign Smith returned with the NavSim output. 'NavSim output ready Ior
review, sir, declared Ensign Smith. 'Fine, replied the Captain, 'Please review your work. 'Yes
sir!, responded the Ensign, 'First I declared and constructed an array oI type ParsecKey with the
Iollowing code; ParsecKey || p new ParsecKey|5|; , next I declared and constructed an array
oI type QuadrantKey with the Iollowing code: QuadrantKey || || q new QuadrantKey |5| |5|; .
Next, I loaded the frst 5 codes into the ParsecKey array using a Ior` loop, and then I loaded the last
25 codes into the QuadrantKey array using nested Ior` loops. Next, I ran the virus checker against
all 32 reIerence variables, 1 Ior the ParsecKey array, and 5 Ior its elements, 1 Ior the QuadrantKey
array, and 25 Ior its elements. Once the virus check returned with no viruses detected, I ran the
NavSim program and re-ran the virus checker, just to be saIe. Sir ! '
Captain Byte gave the Ensign a cool, long stare and said calmly, 'Ensign, you are confned to
quarters Ior endangering the saIety oI this ship, I don`t want to see your Iace on this bridge again
until you have properly learned your Java! Lieutenant Boolean, take over Ior the Ensign and do this
job correctly!
Why did the captain confne the Ensign to his quarters?
]Jc_Jna[c
_s[ci
A Long Trip Home
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix B Top Ten Reference
you are here 675
]Jc_Jna[c _s[ci [a[Jn
A Long Trip Homc
Caiain Byic Incw ihai in ]ava, muliiuimcnsional aiiays aic aciu-
ally aiiays ol aiiays. Thc hvc ly hvc QuauianiKcy aiiay q`, woulu
aciually nccu a ioial ol S1 iclcicncc vaiiallcs io lc allc io acccss
all ol iis comoncnis:
1 - iclcicncc vaiiallc loi q`
- iclcicncc vaiiallcs loi q]0| - q]4|
2 - iclcicncc vaiiallcs loi q]0|]0| - q]4|]4|
Thc cnsign hau loigoiicn ihc iclcicncc vaiiallcs loi ihc hvc onc
uimcnsional aiiays cmlcuucu in ihc q` aiiay. Any ol ihosc hvc
iclcicncc vaiiallcs coulu havc lccn coiiuicu ly ihc HacIaiian
iay, anu ihc cnsign`s icsi woulu ncvci icvcal ihc iollcm.
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for e.simons@icarin.fiuc.org, Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.

Anda mungkin juga menyukai