Head First Java, 2nd Edition

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

Author(s): Kathy Sierra, Bert Bates
Edition: 2nd
Year: 2005

Language: English
Pages: 722
Tags: Библиотека;Компьютерная литература;Java;

Table of Contents......Page 11
Intro.: How to Use This Book......Page 23
Who is this book for?......Page 24
And we know what your brain is thinking.......Page 25
Metacognition: thinking about thinking.......Page 27
Here’s what WE did:......Page 28
Here’s what YOU can do to bend your brain into submission.......Page 29
What you need for this book:......Page 30
Last-minute things you need to know:......Page 31
Technical Editors......Page 32
Other people to credit......Page 33
Just when you thought there wouldn’t be anymore acknowledgements*.......Page 34
Chapter 1. Dive in A Quick Dip: Breaking the Surface......Page 35
The Way Java Works......Page 36
What you’ll do in Java......Page 37
Code structure in Java......Page 41
Anatomy of a class......Page 42
Writing a class with a main......Page 43
Conditional branching......Page 47
Coding a Serious Business Application......Page 48
Phrase-O-Matic......Page 51
Chapter 2. Classes and Objects: A Trip to Objectville......Page 61
Chair Wars......Page 62
Making your first object......Page 70
Making and testing Movie objects......Page 71
Quick! Get out of main!......Page 72
Running the Guessing Game......Page 74
Chapter 3. Primitives and References: Know Your Variables......Page 83
Declaring a variable......Page 84
“I’d like a double mocha, no, make it an int.”......Page 85
You really don’t want to spill that.........Page 86
This table reserved.......Page 87
Controlling your Dog object......Page 88
An object reference is justanother variable value.......Page 89
Arrays are objects too......Page 93
Make an array of Dogs......Page 94
Control your Dog......Page 95
A Heap o’ Trouble......Page 100
Chapter 4. Methods Use Instance Variables: How Objects Behave......Page 105
Remember: a class describes what an object knows and what an object does......Page 106
The size affects the bark......Page 107
You can send things to a method......Page 108
You can get things back from a method.......Page 109
You can send more than one thing to a method......Page 110
Cool things you can do with parameters and return types......Page 113
Encapsulation......Page 114
Encapsulating the GoodDog class......Page 116
How do objects in an array behave?......Page 117
Declaring and initializing instance variables......Page 118
The difference bet ween instance and local variables......Page 119
Comparing variables (primitives or references)......Page 120
Chapter 5. Writing a Program: Extra-Strength Methods......Page 129
Let’s build a Battleship-style game: “Sink a Dot Com”......Page 130
First, a high-level design......Page 131
The “Simple Dot Com Game” a gentler introduction......Page 132
Developing a Class......Page 133
The checkYourself() method......Page 138
The game’s main() method......Page 144
More about for loops......Page 148
Trips through a loop......Page 149
The enhanced for loop......Page 150
Chapter 6. Get to Know The Java API: Using the Java Library......Page 159
In our last chapter, we left you with the cliff-hanger. A bug.......Page 160
So what happened?......Page 161
How do we fix it ?......Page 162
Option t wo is a little better, but still pretty clunky......Page 163
Wake up and smell the library......Page 166
Some things you can do with ArrayList......Page 167
Comparing ArrayList to a regular array......Page 170
Let’s fix the DotCom code.......Page 172
New and improved DotCom class......Page 173
Let’s build the REAL game: “Sink a Dot Com”......Page 174
What needs to change?......Page 175
Who does what in the DotComBust game (and when)......Page 176
Prep code for the real DotComBust class......Page 178
The final version of the DotCom class......Page 184
Super Powerful Boolean Expressions......Page 185
Using the Library (the Java API)......Page 188
You have to know the full name* of the class you want to use in your code.......Page 189
How to play with the API......Page 192
Chapter 7. Inheritance and Polymorphism: Better Living in Objectville......Page 199
Chair Wars Revisited.........Page 200
Understanding Inheritance......Page 202
Let’s design the inheritance tree for an Animal simulation program......Page 204
Using inheritance to avoid duplicating code in subclasses......Page 205
Do all animals eat the same way?......Page 206
Looking for more inheritance opportunities......Page 207
Which method is called?......Page 209
Designing an Inheritance Tree......Page 210
Using IS-A and HAS-A......Page 211
But wait! There’s more!......Page 212
How do you know if you’ve got your inheritance right?......Page 213
When designing with inheritance, are you using or abusing?......Page 215
Keeping the contract: rules for overriding......Page 224
Overloading a method......Page 225
Chapter 8. Interfaces and Abstract Classes......Page 231
Did we forget about something when we designed this?......Page 232
What does a new Animal() object look like?......Page 234
The compiler won’t let you instantiate an abstract class......Page 235
Abstract vs. Concrete......Page 236
Abstract methods......Page 237
You MUST implement all abstract methods......Page 238
Polymorphism in action......Page 240
Uh-oh, now we need to keep Cats, too.......Page 241
What about non-Animals? Why not make a class generic enough to take anything?......Page 242
So what’s in this ultra-super-megaclass Object?......Page 243
Using polymorphic references of type Object has a price.........Page 245
When a Dog won’t act like a Dog......Page 246
Objects don’t bark.......Page 247
Get in touch with your inner Object.......Page 248
What if you need to change the contract?......Page 252
Let’s explore some design options for reusing some of our existing classes in a PetShop program.......Page 253
Interface to the rescue!......Page 258
Making and Implementing the Pet interface......Page 259
Chapter 9. Constructors and Garbage Collection: Life and Death of an Object......Page 269
The Stack and the Heap: where things live......Page 270
Methods are stacked......Page 271
What about local variables that are objects?......Page 272
If local variables live on the stack, where do instance variables live?......Page 273
The miracle of object creation......Page 274
Construct a Duck......Page 276
Initializing the state of a new Duck......Page 277
Using the constructor to initialize important Duck state*......Page 278
Make it easy to make a Duck......Page 279
Doesn’t the compiler always make a no-arg constructor for you?......Page 280
Nanoreview: four things to remember about constructors......Page 283
Wait a minute... we never DID talk about superclasses and inheritance and how that all fits in with constructors.......Page 284
The role of superclass constructors in an object’s life.......Page 285
Making a Hippo means making the Animal and Object parts too.........Page 286
How do you invoke a superclass constructor?......Page 287
Can the child exist before the parents?......Page 288
Superclass constructors with arguments......Page 289
Invoking one overloaded constructor from another......Page 290
Now we know how an object is born, but how long does an object live ?......Page 292
What about reference variables?......Page 294
Chapter 10. Numbers and Statics: Numbers Matter......Page 307
MATH methods: as close as you’ll ever get to a global method......Page 308
The difference between regular (non-static) and static methods......Page 309
What it means to have a class with static methods.......Page 310
Static methods can’t use non-static (instance) variables!......Page 311
Static methods can’t use non-static methods, either!......Page 312
Static variable: value is the same for ALL instances of the class......Page 313
Initializing a static variable......Page 315
static final variables are constants......Page 316
final isn’t just for static variables.........Page 317
Math methods......Page 320
Wrapping a primitive......Page 321
Before Java 5.0, YOU had to do the work.........Page 322
Autoboxing: blurring the line between primitive and object......Page 323
Autoboxing works almost everywhere......Page 324
But wait! There’s more! Wrappers have static utility methods too!......Page 326
And now in reverse... turning a primitive number into a String......Page 327
Number formatting......Page 328
Formatting deconstructed.........Page 329
The percent (%) says, “insert argument here”......Page 330
The format String uses its own little language syntax......Page 331
The format specifier......Page 332
The only required specifier is for TYPE......Page 333
What happens if I have more than one argument?......Page 334
So much for numbers, what about dates?......Page 335
Moving backward and forward in time......Page 337
Getting an object that extends Calendar......Page 338
Working with Calendar objects......Page 339
Highlights of the Calendar API......Page 340
Even more Statics!... static imports......Page 341
Chapter 11. Exception Handling: Risky Behavior......Page 349
Let’s make a Music Machine......Page 350
We’ll start with the basics......Page 351
First we need a Sequencer......Page 352
What happens when a method you want to call (probably in a class you didn’t write) is risky?......Page 353
Methods in Java use exceptions to tell the calling code, “Something Bad Happened. I failed.”......Page 354
The compiler needs to know that YOU know you’re calling a risky method.......Page 355
An exception is an object... of type Exception.......Page 356
If it’s your code that catches the exception, then whose code throws it?......Page 357
Flow control in try/catch blocks......Page 360
Finally: for the things you want to do no matter what.......Page 361
Did we mention that a method can throw more than one exception?......Page 363
Exceptions are polymorphic......Page 364
Multiple catch blocks must be ordered from smallest to biggest......Page 366
You can’t put bigger baskets above smaller baskets.......Page 367
When you don’t want to handle an exception.........Page 369
Ducking (by declaring) only delays the inevitable......Page 370
Getting back to our music code.........Page 372
Making actual sound......Page 374
Your very first sound player app......Page 376
Making a MidiEvent (song data)......Page 377
MIDI message: the heart of a MidiEvent......Page 378
Change a message......Page 379
Chapter 12. Getting GUI: A Very Graphic Story......Page 387
It all starts with a window......Page 388
Your first GUI: a button on a frame......Page 389
But nothing happens when I click it.........Page 390
Getting a user event......Page 391
Listeners, Sources, and Events......Page 395
Getting back to graphics.........Page 397
Make your own drawing widget......Page 398
Fun things to do in paintComponent()......Page 399
Behind every good Graphics reference is a Graphics2D object.......Page 400
Because life’s too short to paint the circle a solid color when there’s a gradient blend waiting for you.......Page 401
We can get an event. We can paint graphics. But can we paint graphics when we get an event?......Page 403
GUI layouts: putting more than one widget on a frame......Page 404
Let’s try it with TWO buttons......Page 406
Inner class to the rescue!......Page 410
An inner class instance must be tied to an outer class instance*.......Page 411
How to make an instance of an inner class......Page 412
Using an inner class for animation......Page 416
Listening for a non-GUI event......Page 421
An easier way to make messages / events......Page 422
Example: how to use the new static makeEvent() method......Page 423
Version Two: registering and getting ControllerEvents......Page 424
Version Three: drawing graphics in time with the music......Page 425
Chapter 13. Using Swing: Work on Your Swing......Page 433
Swing components......Page 434
Layout Managers......Page 435
How does the layout manager decide?......Page 436
The Big Three layout managers: border, flow, and box.......Page 437
Playing with Swing components......Page 447
Making the BeatBox......Page 453
Chapter 14. Serialization and File I/O: Saving Objects......Page 463
Capture the Beat......Page 464
Saving State......Page 465
Writing a serialized object to a file......Page 466
Data moves in streams from one place to another.......Page 467
What really happens to an object when it’s serialized?......Page 468
But what exactly IS an object’s state?What needs to be saved?......Page 469
If you want your class to be serializable, implement Serializable......Page 471
Deserialization: restoring an object......Page 475
What happens during deserialization?......Page 476
Saving and restoring the game characters......Page 478
Writing a String to a Text File......Page 481
Text File Example: e-Flashcards......Page 482
Quiz Card Builder (code outline)......Page 483
The java.io.File class......Page 486
Reading from a Text File......Page 488
Quiz Card Player (code outline)......Page 489
Parsing with String split()......Page 492
Version ID: A Big Serialization Gotcha......Page 494
Using the serialVersionUID......Page 495
Saving a BeatBox pattern......Page 497
Restoring a BeatBox pattern......Page 498
Chapter 15. Networking and Threads: Make a Connection......Page 505
Real-time Beat Box Chat......Page 506
Connecting, Sending, and Receiving......Page 508
Make a net work Socket connection......Page 509
A TCP port is just a number.......Page 510
To read data from a Socket, use a BufferedReader......Page 512
To write data to a Socket, use a PrintWriter......Page 513
The DailyAdviceClient......Page 514
DailyAdviceClient code......Page 515
Writing a simple server......Page 517
DailyAdviceServer code......Page 518
Writing a Chat Client......Page 520
Java has multiple threads but only one Thread class......Page 524
What does it mean to have more than one call stack?......Page 525
Every Thread needs a job to do. A method to put on the new thread stack.......Page 527
To make a job for your thread, implement the Runnable interface......Page 528
The Thread Scheduler......Page 531
Putting a thread to sleep......Page 535
Using sleep to make our program more predictable.......Page 536
What will happen?......Page 537
Um, yes. There IS a dark side. Threads can lead to concurrency 'issues'.......Page 538
The Ryan and Monica problem, in code......Page 540
We need the makeWithdrawal ( ) method to run as one atomic thing.......Page 544
Using an object’s lock......Page 545
The dreaded “Lost Update” problem......Page 546
Let’s run this code.........Page 547
Make the increment() method atomic. Synchronize it!......Page 548
The deadly side of synchronization......Page 550
New and improved SimpleChatClient......Page 552
The really really simple Chat Server......Page 554
Chapter 16. Collections and Generics: Data Structures......Page 563
Tracking song popularity on your jukebox......Page 564
Here’s what you have so far, without the sort:......Page 565
But the ArrayList class does NOT have a sort() method!......Page 566
ArrayList is not the only collection......Page 567
You could use a TreeSet... Or you could use the Collections.sort() method......Page 568
Adding Collections.sort() to the Jukebox code......Page 569
But now you need Song objects, not just simple Strings.......Page 570
Changing the Jukebox code to use Songs instead of Strings......Page 571
It won’t compile !......Page 572
Generics means more type-safety......Page 574
Learning generics......Page 575
Using generic CLASSES......Page 576
Using type parameters with ArrayList......Page 577
Using generic METHODS......Page 578
Here’s where it gets weird.........Page 579
Revisiting the sort( ) method......Page 581
In generics, “extends” means“ extends or implements”......Page 582
Finally we know what’s wrong... The Song class needs to implement Comparable......Page 583
The new, improved, comparable Song class......Page 584
We can sort the list, but.........Page 585
Using a custom Comparator......Page 586
Updating the Jukebox to use a Comparator......Page 587
Uh-oh. The sorting all works, but now we have duplicates.........Page 590
We need a Set instead of a List......Page 591
The Collection API (part of it)......Page 592
Using a HashSet instead of ArrayList......Page 593
What makes t wo objects equal?......Page 594
How a HashSet checks for duplicates: hashCode() and equals()......Page 595
The Song class with overridden hashCode() and equals()......Page 596
And if we want the set to stay sorted, we’ve got TreeSet......Page 598
What you MUST know about TreeSet.........Page 599
TreeSet elements MUST be comparable......Page 600
We’ve seen Lists and Sets, now we’ll use a Map......Page 601
Finally, back to generics......Page 602
Using polymorphic arguments and generics......Page 603
But will it work with ArrayList ?......Page 604
What could happen if it were allowed.........Page 605
Wildcards to the rescue......Page 608
Alternate syntax for doing the same thing......Page 609
Chapter 17. Package, Jars and Deployment: Release Your Code......Page 615
Deploying your application......Page 616
Separate source code and class files......Page 618
Put your Java in a JAR......Page 619
Running (executing) the JAR......Page 620
Put your classes in packages!......Page 621
Preventing package name conflicts......Page 622
Compiling and running with packages......Page 624
The -d flag is even cooler than we said......Page 625
Making an executable JAR with packages......Page 626
So where did the manifest file go?......Page 627
Java Web Start......Page 631
The .jnlp file......Page 633
Chapter 18. Remote Deployment with RMI: Distributed Computing......Page 641
Method calls are always between two objects on the same heap.......Page 642
What if you want to invoke a method on an object running on another machine?......Page 643
But you can’t do that.......Page 644
The role of the ‘helpers’......Page 646
Java RMI gives you the client and service helper objects!......Page 648
How does the client get the stub object?......Page 654
How does the client get the stub class?......Page 655
Be sure each machine has the class files it needs.......Page 656
Yeah, but who really uses RMI?......Page 658
What about Servlets?......Page 659
Just for fun, let’s make the Phrase-O-Matic work as a servlet......Page 663
Phrase-O-Matic code, servlet-friendly......Page 664
Enterprise JavaBeans: RMI on steroids......Page 665
For our final trick... a little Jini......Page 666
Final Project: the Universal Service browser......Page 670
Appendix A:Final Code Kitchen......Page 683
Final BeatBox client program......Page 684
Final BeatBox server program......Page 691
Appendix B: The Top Ten Topics that almost made it into the Real Book.........Page 693
#10 Bit Manipulation......Page 694
#9 Immutability......Page 695
#8 Assertions......Page 696
#7 Block Scope......Page 697
#6 Linked Invocations......Page 698
#5 Anonymous and Static Nested Classes......Page 699
#5 Anonymous and Static Nested Classes, continued......Page 700
#4 Access Levels and Access Modifiers (Who Sees What)......Page 701
#4 Access Levels and Access Modifiers, cont.......Page 702
#3 String and StringBuffer/StringBuilder Methods......Page 703
#2 Multidimensional Arrays......Page 704
#1 Enumerations (also called Enumerated Types or Enums)......Page 705
A......Page 711
C......Page 712
E......Page 713
G......Page 714
I......Page 715
L......Page 716
O......Page 717
P......Page 718
S......Page 719
W......Page 721