Termes les plus recherchés
[PDF](+65👁️) Télécharger head-first-java-2nd-edition pdf
head first java for beginners
Télécharger gratuit head-first-java-2nd-edition pdf
Your Brain on Java — A Learner’s Guide
Learn how threads
can change your life
2nd Edition - Covers Java 5.0
Head First
Avoid embarassing
00 mistakes
Bend your mind
around 42
Java puzzles
_ h l'i
4 j rcj-i/ Wt
Make Java concepts
stick to your brain
Fool around in
the Java Library
Make attractive
and useful GUIs
O REILLY’
Kathy Sierra & Bert Bates
XXI
Table of Contents (summary)
Intro
1 Breaking the Surface: a quick dip 1
2 A Trip to Objectville: yes, there will be objects 27
3 Know Your Variables: primitives and references 49
4 How Objects Behave: object state effects method behavior 1 1
5 Extra-Strength Methods: flow control, operations, and more 95
6 Using the Java Library: so you don’t have to write it all yourself 125
7 Better Living in Objectville: planning for the future 165
8 Serious Polymorphism: exploiting abstract classes and inte faces 197
9 Life and Death of an Object: constructors and memory management 235
10 Numbers Matter: math, formatting wrappers, and statics 273
1 1 Risky Behavior: exception handling 315
12 A Very Graphic Story: intro to GUI, event handling and inner classes 353
13 Work on Your Swing: layout managers and components 399
14 Saving Objects: serialization and I/O 429
15 Make a Connection: networking sockets and multithreading 47 1
16 Data Structures: collections and generics 529
1 7 Release Your Code: packaging and deployment 58 1
18 Distributed Computing: RMIwith a dash of servlets, EJB, andjini 607
A Appendix A: Final code kitchen 649
B Appendix B: Top Ten Things that didn’t make it into the rest of the book 659
Index 677
Table of Contents (the full version)
t Intro
I Your brain on Java. Here you are trying to learn something, while here your brain
is doing you a favor by making sure the learning doesn't stick. Your brain's thinking, "Better
leave room for more important things, like which wild animals to avoid and whether naked
snowboarding is a bad idea." So how do you trick your brain into thinking that your life
depends on knowing Java?
Who is this book for? xxii
What your brain is thinking xxiii
Metacognition xxv
Bend your brain into submission xxvii
What you need for this book xxviii
Technical editors xxx
Acknowledgements xxxi
ix
1
Breaking the Surface
Java takes you to new places. From its humble release to the public as the
(wimpy) version 1.02, Java seduced programmers with its friendly syntax, object-oriented
features, memory management, and best of all — the promise of portability. We'll take a quick
dip and write some code, compile it, and run it. We're talking syntax, loops, branching, and what
makes Java so cool. Dive in.
Virtual
Machines
Method Party()
0 aload_0
1 invokespe-
cial #1 <Method
java.lang.Object()>
4 return
Compiled
bytecode
The way Java works
Code structure in Java
Anatomy of a class
The mainQ method
Looping
Conditional branching (if tests)
Coding the “99 bottles of beer” app
Phrase-o-matic
Fireside chat: compiler vs. JVM
Exercises and puzzles
2
7
8
9
11
13
14
16
18
20
A Trip to Objectville
I was told there would be objects. In Chapter 1, we put all of our code
in the main() method. That's not exactly object-oriented. So now we've got to leave that
procedural world behind and start making some objects of our own. We'll look at what
makes object-oriented (00) development in Java so much fun. We'll look at the difference
between a class and an object. We'll look at how objects can improve your life.
many objects
one class
DOG
Chair Wars (Brad the OO guy vs. Larry the procedural guy)
Inheritance (an introduction)
Overriding methods (an introduction)
What’s in a class? (methods, instance variables)
Making your first object
Using mainQ
Guessing Game code
Exercises and puzzles
28
31
32
34
36
38
39
42
X
Know Your Variables
Variables come in two flavors: primitive and reference.
There's gotta be more to life than integers. Strings, and arrays. What if you have a PetOwner
object with a Dog instance variable? Or a Car with an Engine? In this chapter we'll unwrap
the mysteries of Java types and look at what you can declare as a variable, what you can put
in a variable, and what you can do with a variable. And we'll finally see what life is truly like
on the garbage-collectible heap.
Dog reference
Declaring a variable (Java cares about type)
Primitive types (“I J d like a double with extra foam, please”)
Java keywords
Reference variables (remote control to an object)
Object declaration and assignment
Objects on the garbage-collectible heap
Arrays (a first look)
Exercises and puzzles
50
51
53
54
55
57
59
63
How Objects Behave
State affects behavior, behavior affects state. We know that objects
have state and behavior, represented by instance variables and methods. Now we'll look
at how state and behavior are related. An object's behavior uses an object's unique state.
In other words, methods use instance variable values. Like, "if dog weight is less than 14
pounds, make yippy sound, else..." Let's go change some state!
pass-by -value means
pass-by -copy
int int
foo.go(x); void go (int z) { }
Methods use object state (bark different)
Method arguments and return types
Pass-by-value (the variable is always copied)
Getters and Setters
Encapsulation (do it or risk humiliation)
Using references in an array
Exercises and puzzles
73
74
77
79
80
83
88
xi
5
saves*
E
o
u
(N
yj
P<
sts.cc
>m
Ask
JVIe.c
om
Extra-Strength Methods
Let’s put some muscle in our methods. You dabbled with variables,
played with a few objects, and wrote a little code. But you need more tools. Like
operators. And loops. Might be useful to generate random numbers. And turn
a String into an int, yeah, that would be cool. And why don't we learn it all by building
something real, to see what it's like to write (and test) a program from scratch. Maybe a
game, like Sink a Dot Com (similar to Battleship).
Building the Sink a Dot Com game 96
Starting with the Simple Dot Com game (a simpler version) 98
Writing prepcode (pseudocode for the game) 1 00
Test code for Simple Dot Com 102
Coding the Simple Dot Com game 103
Final code for Simple Dot Com 106
Generating random numbers with Math.randomQ 1 1 1
Ready-bake code for getting user input from the command-line 112
Looping with for loops 1 1 4
Casting primitives from a large size to a smaller size 117
Converting a String to an int with Integer.parselnt() 1 1 7
Exercises and puzzles 1 18
Using the Java Library
Java ships with hundreds of pre-built classes. You don't have to
reinvent the wheel if you know how to find what you need from the Java library, commonly
known as the Java API. You've got better things to do. If you're going to write code, you
might as well write only the parts that are custom for your application. The core Java library
is a giant pile of classes just waiting for you to use like building blocks.
“ Good to know there’s an Array List in
the java, util package. But by myself, how
would I have figured that out?”
Analying the bug in the Simple Dot Com Game
Array List (taking advantage of the Java API)
Fixing the DotCom class code
Building the real game (Sink a Dot Com)
Prepcode for the real game
Code for the real game
boolean expressions
Using the library Java API)
Using packages (import statements, fully-qualified names)
Using the HTML API docs and reference books
Exercises and puzzles
126
132
138
140
144
146
151
154
155
158
161
xii
7
Better Living in Objectville
Plan your programs with the future in mind. What if you could write
code that someone else could extend, easily? What if you could write code that was flexible,
for those pesky last-minute spec changes? 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 now — a bonus lesson on the 4 tips for exploiting inheritance.
is
Pass
' by value
**** <i Stid?
s WarZsTsfy'a /etS ®’ <? b ' Ue '
S A s hape, the reverse isn't true
stows fte one .
make
sense.
Understanding inheritance (superclass and subclass relationships) 168
Designing an inheritance tree (the Animal simulation) 170
Avoiding duplicate code (using inheritance) 171
Overriding methods 1 7 2
IS-A and HAS-A (bathtub girl) 177
What do you inherit from your superclass? 180
What does inheritance really buy you? 182
Polymorphism (using a supertype reference to a subclass object) 183
Rules for overriding (don’t touch those arguments and return types!) 190
Method overloading (nothing more than method name re-use) 191
Exercises and puzzles 192
Serious Polymorphism
Inheritance is just the beginning. To exploit polymorphism, we need
interfaces. We need to go beyond simple inheritance to flexibility you can get only by
designing and coding to interfaces. What's an interface? A 100% abstract class. What's an
abstract class? A class that can't be instantiated. What's that good for? Read the chapter...
Object o = al.get(id);
Dog d = (Dog) o;
d . bark ( ) ;
Some classes just should not be instantiated
Abstract classes ( can’t be instantiated)
Abstract methods (must be implemented)
Polymorphism in action
Class Object (the ultimate superclass of everything )
Taking objects out of an Array List (they come out as type Object)
Compiler checks the reference type (before letting you call a method)
Get in touch with your inner object
Polymorphic references
Casting an object reference (moving lower on the inheritance tree)
Deadly Diamond of Death (multiple inheritance problem)
Using interfaces (the best solution!)
Exercises and puzzles
200
201
203
206
208
211
213
214
215
216
223
224
230
xiii
Life and Death of an Object
Objects are born and objects die. You're in charge. You decide when and
how to construct them. You decide when to abandon them. The Garbage Collector (gc)
reclaims the memory. We'll look at how objects are created, where they live, 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 gc eligibility.
The stack and the heap, where objects and variables live
Methods on the stack
Where local variables live
Where instance variables live
The miracle of object creation
Constructors (the code that runs when you say new)
Initializing the state of a new Duck
Overloaded constructors
Superclass constructors (constructor chaining)
Invoking overloaded constructors using this()
Life of an object
Garbage Collection (and making objects eligible)
Exercises and puzzles
236
237
238
239
240
241
243
247
250
256
258
260
266
10
Static variables
are shared by
all instances of
a class.
Numbers Matter
Do the Math . The Java API has methods for absolute value, rounding, min/max, etc.
But what about formatting? You might want numbers to print exactly two decimal points,
or with commas in all the right places. And you might want to print and manipulate dates,
too. And what about parsing a String into a number? Or turning a number into a String?
We'll start by learning what it means for a variable or method to be static.
s-tatid variable:
ideCrear*
instande variables:
one per insjande
s-ta-fcid variables:
one per dlass
kid irstardC one
kid ins-tande "two
Math class (do you really need an instance of it?) 274
static methods 275
static variables 277
Constants (static final variables) 282
Math methods (randomQ, roundQ, abs(), etc.) 286
Wrapper classes (Integer, Boolean, Character, etc.) 287
Autoboxing 289
Number formatting 294
Date formatting and manipulation 30 1
Static imports 307
Exercises and puzzles 310
xiv
Risky Behavior
Stuff happens. The file isn't there.The server is down. No matter how good a
programmer you are, you can't control everything. When you write a risky method, you need
code to handle the bad things that might happen. But how do you know when a method is
risky? Where do you put the code to handle the exceptional situation? In this chapter, we're
going to build a MIDI Music Player, that uses the risky JavaSound API, so we better find out.
risky method
Making a music machine (the BeatBox)
What if you need to call risky code?
Exceptions say “something bad may have happened...”
The compiler guarantees (it checks) that you’re aware of the risks
Catching exceptions using a try /catch (skateboarder)
Flow control in try /catch blocks
The finally block (no matter what happens, turn off the oven!)
Catching multiple exceptions (the order matters)
Declaring an exception (just duck it)
Handle or declare law
Code Kitchen (making sounds)
Exercises and puzzles
316
319
320
321
322
326
327
329
335
337
339
348
12
A Very Graphic Story
Face it, you need to make GUIs. Even if you believe that for the rest of your
life you'll write only server-side code, sooner or later you'll need to write tools, and you'll
want a graphical interface. We'll spend two chapters on GUIs, and learn more language
features including Event Handling and Inner Classes. We'll put a button on the screen,
Exercises and puzzles
394
XV
Work on your Swing
Swing is easy. Unless you actually care where everything goes. Swing code looks
easy, but then compile it, run it, look at it and think, "hey, that's not supposed to go there."
The thing that makes it easy to code is the thing that makes it hard to control — the Layout
Manager. But with a little work, you can get layout managers to submit to your will. In
this chapter, we'll work on our Swing and learn more about widgets.
•the east a*d
pv-e-fcvv-ed Wth-
Things in the
boirfch and
south get their
f referred height-
eoo
(
North
)
' 1
/ \
West
Center
East
-i
he Canter aei
L
haicvcir s le${
South
\
Swing Components
Layout Managers (they control size and placement)
Three Layout Managers (border, flow, box)
BorderLayout (cares about five regions)
FlowLayout (cares about the order and preferred size)
BoxLayout (like flow, but can stack components vertically)
JTextField (for single-line user input)
JTextArea (for multi-line, scrolling text)
JCheckBox (is it selected?)
JList (a scrollable, selectable list)
Code Kitchen (The Big One - building the BeatBox chat client)
Exercises and puzzles
400
401
403
404
408
411
413
414
416
417
418
424
Saving Objects
Objects can be flattened and inflated. Objects have state and behavior.
Behavior lives in the class, but state lives within each individual object. If your program
needs to save state, you can do it the hard way, interrogating each object, painstakingly
writing the value of each instance variable. Or, you can do it the easy OO way — you simply
freeze-dry the object (serialize it) and reconstitute (deserialize) it to get it back.
Saving object state 43 1
Writing a serialized object to a file 432
Java input and output streams (connections and chains) 433
Object serialization 434
Implementing the Serializable interface 437
Using transient variables 439
Deserializing an object 441
Writing to a text file 447
java.io.File 452
Reading from a text file 454
Splitting a String into tokens with split() 458
CodeKitchen 462
Exercises and puzzles 466
XVI
15
; I We
Make a Connection
Connect with the outside world, it s easy. All the low-level networking
details are taken care of by classes in the java.net library. One of Java's best features is
that sending and receiving data over a network is really just I/O with a slightly different
connection stream at the end of the chain. In this chapter we'll make client sockets. We'll
make server sockets. We'll make clients and servers. Before the chapter's done, you'll have a
fully-functional, multithreaded chat client. Did we just say multithreaded ?
Ghat program overview 473
Connecting, sending, and receiving 474
Network sockets 475
TCP ports 476
Reading data from a socket (using BufferedReader) 478
Writing data to a socket (using PrintWriter) 479
Writing the Daily Advice Client program 480
Writing a simple server 483
Daily Advice Server code 484
Writing a chat client 486
Multiple call stacks 490
Launching a new thread (make it, start it) 492
The Runnable interface (the thread’s job) 494
Three states of a new Thread object (new, runnable, running) 495
The runnable-running loop 496
Thread scheduler (it’s his decision, not yours) 497
Putting a thread to sleep 501
Making and starting two threads 503
Concurrency issues: can this couple be saved? 505
The Ryan and Monica concurrency problem, in code 506
Locking to make things atomic 510
Every object has a lock 5 1 1
The dreaded “Lost Update” problem 5 1 2
Synchronized methods (using a lock) 514
Deadlock! 5 1 6
Multithreaded ChatClient code 518
Ready-bake SimpleChatServer 520
Exercises and puzzles 524
xvii
Data Structures
Sorting is a snap in Java. You have all the tools for collecting and manipulating
your data without having to write your own sort algorithms The Java Collections
Framework 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 to? Want to find something by
name? Want to create a list that automatically takes out all the duplicates? Sort your co-
workers by the number of times they've stabbed you in the back?
List
Set
Map
Collections
Sorting an ArrayList with Collections. sortO
Generics and type-safety
Sorting things that implement the Comparable interface
Sorting things with a custom Comparator
The collection API — lists, sets, and maps
Avoiding duplicates with HashSet
Overriding hashCodeO and equals0
HashMap
Using wildcards for polymorphism
Exercises and puzzles
533
534
540
547
552
557
559
560
567
574
576
MyApp.class
Release Your Code
It’s time to let go. You wrote your code. You tested your code. You refined your code.
You told everyone you know that if you never saw a line of code again, that'd be fine. But in
the end, you've created a work of art. The thing actually runs! But now what? In these final
two chapters, we'll explore how to organize, package, and deploy your Java code. We'll look
at local, semi-local, and remote deployment options including executable jars, Java Web
Start, RMI, and Servlets. Relax. Some of the coolest things in Java are easier than you think.
Deployment options 582
Keep your source code and class files separate 584
Making an executable JAR Java ARchives) 585
Running an executable JAR 586
Put your classes in a package! 587
Packages must have a matching directory structure 589
Compiling and running with packages 590
Compiling with -d 591
Making an executable JAR (with packages) 592
Java Web Start JWS) for deployment from the web 597
How to make and deploy a JWS application 600
Exercises and puzzles 60 1
xviii
Distributed Computing
Being remote doesn’t have to be a bad thing. Sure, things ore easier
when all the parts of your application are in one place, in one heap, with one JVM to rule
them all. But that's not always possible. Or desirable. What if your application handles
powerful computations? What if your app needs data from a secure database? In this
chapter, we'll learn to use Java's amazingly simple Remote Method Invocation (RMI). We'll
also take a quick peek at Servlets, Enterprise Java Beans (EJB) , and Jini.
Java Remote Method Invocation (RMI), hands-on, very detailed
Servlets (a quick look)
Enterprise JavaBeans (EJB), a very quick look
Jini, the best trick of all
Building the really cool universal service browser
The End
614
625
631
632
636
648
Appendix A
The final Code Kitchen project.
beat box. Your chance to be a rock star.
All the code for the full client-server chat
BeatBoxFinal (client code) 650
MusicServer (server code) 657
Appendix B
The Top Ten Things that didn’t make it into the book. We can't send
you out into the world just yet. We have a few more things for you, but this is the end of the
book. And this time we really mean it.
Top Ten List
660
Index
677
xix
how to use this book
xxi
how to use this book
Who is this book for?
If you can answer "yes” to al l of these;
0’ Have you done some programming?
(2) Do you want to learn Java?
0 Do you prefer stimulating dinner party
conversation to dry, dull, technical
lectures?
this book is for you.
This is NOT a reference
book. Head First Java is a
book designed for learning,
not an encyclopedia of
Java facts.
Who should probably back away from this book?
If you can answer 'yes” to any one of these:
0 Ib your programming background limited
to HTML only, with no acrlptlng language
experience?
(If you’ve done anything with looping; or if/ then
logic* you’11 do fine with this book, but HTML
tagging alone might not be enough.)
(2) Are you a kick-butt C++ programmer
looking for a reference book?
0 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?
this book is not for you.
xxil intro
We know what you're thinking.
u How can this be a serious Java programming book?”
“What's with all the graphics?”
"Can I actually team it this way?”
"Do I smell pfrza?”
And we know what your brain is thinking.
Your brain craves novelty. It’s always searching, scanning, waiting for
something unusual. It was built that way, and it helps you stay alive.
Today, you're less likely to be a tiger snacL But your brain's still
looking. You just never know.
So what does your brain do with all the routine, ordinary, normal .
things you encounter? Everything it canto stop them from I
interfering with the brain 's realjob — recording things that matter . It
doesn't bother saving the boring things; they never make it past the
"this is obviously not important” filter
How does your brain know what's important? Suppose you're out for
a day hike and a tiger jumps in front of you, what happens inside your
head?
Neurons fire. Emotions crank up. Chemicals surge
And that’s how your brain knows...
This must be Important! Don't forget Itl
But imagine you're at home, or in a library. It’s a safe, warm, tiger-free
zone. You're studying. Getting ready for an exam. Or trying to learn
some cough technical topic your boss thinks will take a week, ten days
at the most
Just one problem. Your brain's trying to do you a big favor. It’s
trying to make sure that this obviously non-important content
doesn't clutter up scarce resources. Resources that are better \ mmm
spent storing the really toothings. Like tigers. Like the danger of
fire. Like how you should never again snowboard in short s. gw
And there’s no simple way to tell your brain, “Hey brain, thank wA
you very much, btit no matter how dull this book is, and how t
little I’m registering on the emotional richter scale right now, I m
really do want you to keep this stuff around.” m
the intro
Great. Only
637 more dull, dry,
boring pages.
you are here ► xxili
how to use this book
We fexk of a “Head First Java” reader as a learner.
So what does It take to /earn 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
latest research In cognitive science, neurobiology, and educational psychology,
learning takes a lot more than text on a page. We know what turns your brain on.
doCoJcO
abstract
vi
Get — and keep — the reader's attention- WeVe all
had the "I really want to learn this but l can't stay awake past
page one' experience. Your 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. Your brain will learn much more quickly if it's not.
Some of the Head First learning principles:
Make It visual. Images are far more memorable than words
alone, and make learning much more effective (Up to 89%
Improvement in recall and transfer studies). It also makes
things more understandable. Put the words within
or near the graphics they relate to, rather than on the
bottom or on another page, and learners will be up to twice
as likely to solve problems related to the content.
Use a conversational and personalized style. In recent studies,
students performed up to 40% better on post-learning tests if the content spoke
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 lecture?
Get the learner to think more deeply. In other words, unless
you actively flex your neurons, nothing much happens in your head.
A reader has to be motivated, engaged, curious, and inspired to
solve problems, draw conclusions, and generate new knowledge.
And for that, you need challenges, exercises, and thought-
roam ( ) ; provoking questions, and activities that involve both sides
^ of the brain, and multiple senses.
RMl vcwotc
i
Touch their emotions. We now know that your ability to remember something Is largely
dependent on Its emotional content You remember what you care about You remember when
you feel something. No we're not talking heart -wrenching stories about a boy and his dog.
We're talking emotions like surprise, curiosity, fun/what the...?', and the feeling of "I Rule!'
that comes when you solve a puzzle, learn something everybody else thinks Is hard, or realize
you know something that 'I'm more technical than thou' Bob from engineering doesn't.
ICM
xxlv intro
4
the intro
Metacognitiow: thinking about thinking.
If you really want to learn, and you want to learn more qtiickly and more deeply,
pay attention to how you pay attention. Think about how you think. Learn how
you learn.
Most of us did not take courses on metacognition or learning theory when we were
growing up. We were expected to learn, but rarely taught to learn.
But we assume that if you're holding this book, you want to learn Java. And you
probably don't want to spend a lot of time.
To get the most from this book, or any book or learning experience, take
responsibility for your brain. Your brain on that content.
The trick is to get your brain to see the new material you’re learning
as Really Important. Crucial to your well-being. As important as
a tiger. Otherwise, you’re in for a constant battle, with your brain
doing its best to keep the new content from sticking.
So Just how DO you got your brain to treat Java like It
was a hungry tiger?
There’s the slow, tedious way, or die faster, more effective way. The
slow way is about sheer repetition. You obviously know that you are
able to learn and remember even the dullest of topics, if you keep pounding
on the same thing. With enough repetition, your brain says, ‘This doesn't feel
important to him, but he keeps looking at the same thing over and m/erand over, so
I suppose it must be."
The faster way is to do anything that increases brain activity, especially different types
of brain activity. The things on the previous page are a big part of the solution,
and they're all things that have been proven to help your brain work in your favor.
For example, studies show that putting words within the pictures they describe (as
opposed to somewhere else in the page, like a caption or in the body text) causes
vour brain to try to makes sense of how the words and picture relate, and this
causes more neurons to fire. More neurons firing = more chances for your brain
to get that this is something worth paying attention to, and possibly recording.
A conversational style helps because people tend to pay more attention when they
perceive that they’re jn a conversation, since they’re expected to follow along and
hold up their end. The amazing thing is, your brain doesn’t necessarily care that
the * conversation" is between you and a book! On the other hand, if the writing
style is formal and dry, your brain perceives it the same way you experience being
lectured to while sitting in a roomful of passive attendees. No need to stay awake.
But pictures and conversational style are just the beginning.
you are here *
XXV
how to use this book
i
Here's what WE did:
We used pictures , because your brain is tuned for visuals, not text As far as your
brain's concerned, a picture really is worth 1024 words. And when text and pictures
work together, we embedded the text in the pictures because your brain works
more effectively when the text is within the thing the text refers to, as opposed to in
a caption or buried in the text somewhere.
We used repetition, saying the same thing in different ways and with different media
types, and multiple senses , to increase the chance that the content gets coded coded
into more than one area of your brain.
We used concepts and pictures in unexpected ways because your brain is tuned for
novelty, and we used pictures and ideas with at least some emotional content because
your brain is tuned to pay attention to the biochemistry of emotions. That which
causes you to /^/something is more likely to be remembered, even if that feeling is
nothing more than a little humor ; surprise , or interest
We used a personalized, conversational style, because your brain is tuned to pay more
attention when it believes you're in a conversation than if it thinks you're passively
listening to a presentation. Your brain does this even when you're reading.
We included more than 50 exercises , because your brain is tuned to learn and
remember more when you do things than when you read about things. And we
made the exercises challenging-yet-do-able, because that's what most people prefer.
We used multiple learning styles , because you might prefer step-by-step procedures,
while someone else wants to understand the big picture first, while someone else
just wants to see a code example. But regardless of your own learning preference,
everyone benefits from seeing the same content represented in multiple ways.
We include content for both sides of your brain, because the more of your brain you
engage, the more likely you are to learn and remember, and the longer you can
stay focused. Since working one side of the brain often means giving the other side
a chance to rest, you can be more productive at learning for a longer period of
time.
And we included stories and exercises that present more than one point of view,
because your brain is tuned to learn more deeply when it's forced to make
evaluations and judgements.
We included chaBenges , with exercises, and by asking questions that don't always have
a straight answer, because your brain is tuned to learn and remember when it has
to work at something (just as you can't get your body in shape by watching people
at the gym). But we did our best to make sure that when you're working hard, it's
on the right things. Thai you’re not spending one extra dendrite processing a hard- to-
understand example, or parsing difficult, jargon-laden, or extremely terse text.
We used an 80/20 approach. We assume that if you're going for a PhD in Java,
this won’t be your only book. So we don't talk about everything. Just the stuff you’ll
actually use
BULLET POINTS
xxvi Intro
the intro
Here's what YOU can do to bend your
brain into submission.
So, we did our part The rest is up to you. These tips are a
starting point; Listen to your brain and figure out what works
for you and what doesn't Try new things.
Ui ^
i
0 Slow down. Tho more you understand,
the less you have to memorize.
Don’tjust read. Stop and think. When the
book asks you a question, don't just skip to
the answer. Imagine that someone really is
asking the question. The more deeply you
force your brain to think, the better chance
you have of learning and remembering.
0 Do the exercises. Write your own notes.
We put them in, but if we did them for you,
that would be like having someone else
do your workouts for you. And don't just
look at the exercises. Use a pencil* There’s
plenty of evidence that physical activity
while learning can increase the learning.
0 Read the ‘'There are No Dumb Questions”
That means all of them. They’re not
optional side-bars — diey're part of the core
content! Sometimes die questions are more
useful than the answers.
^ Drink water. Lots of it.
Your brain works best in a nice bath of fluid*
Dehydration (which can happen before you
ever feel thirsty) decreases cognitive function.
|| Talk about it. Out loud.
Speaking activates a different part of
the brain. If you’re trying to understand
something, or increase your chance of
remembering it later, say it out loud. Better
still, try to explain it out loud to someone
else. You’ll learn more quickly, and you might
uncover ideas you hadn’t known were there
when you were reading about it.
^ Listen to your brain.
Pay attention to whether your brain is getting
overloaded. If you find yourself starting to skim
die surface or forget what you just read, it’s
time for a break. Once you go past a certain
point, you won't learn faster by trying to shove
more in, and you might even hurt die process.
^ Don’t do all your reading in one place.
Stand-up, stretch, move around, change
chairs, change rooms. It’ll help your brain
/^/something, and keeps your learning from
being too connected to a particular place.
^ Feel something!
Your brain needs to know that this matters * Get
involved with the stories. Make up your own
captions for the photos. Groaning over a bad
joke is still better than feeling nothing at all*
@ Make this the last thing you read before
bed. Or at least the last challenging thing.
Part of the learning (especially the transfer
to long-term memory) happens after you put
the book down. Your brain needs time on
its own, to do more processing. If you put in
something new during that processing-time,
some of what you just learned will be lost.
^ Type and run the code.
Type and run the code examples. Then you
can experiment with changing and improving
the code (or breaking it, which is sometimes
the best way to figure out what's really
happening). For long examples or Ready-bake
code, you can download die source files from
headfirstjava.com
you are here ► xxvil
how to use this book
What you need for this book:
You do not need any other development tool, such as an Integrated
Development Environment (IDE). We strongly recommend that you not
use anything but a basic text editor until you complete this book (and
especially not until after chapter 16) . An IDE can protect you from some of
the details that really matter, so you're much better off learning from the
command-line and then, once you really understand what's happening,
move to a tool that automates some of the process.
I SETTING UP JAVA
■ If you don't already have a 1 .5 or greater Java 2 Standard Edition SDK (Software
Development Kit), you need if. If you’re on Linux, Windows, or Solaris, you can gel it for free
from java.sun.com (Sun's website for Java developers). It usually takes no more than two clicks
from the main page to get to the J2SE downloads page. Get the latest non-beta version posted.
Die SDK includes everything you need to compile and run Java.
If you're running Mac OS X 10.4, the Java SDK is already installed. It's part of OS X, and you
don’t have to do anything else. If you're on an earlier version of OS X, you have an earlier
version of Java that will work for 95% of the code in this book.
Note: This book is based on Java 1 .5, but for stunningly unclear marketing reasons, shortly
before release, Sun renamed It Java 5, while still keeping "1.5" as the version number for the
developer's kit So, if you see Java 1.5 or Java 5 or Java 5.0, or 'Tiger' (version 5’s original
code-name), they all mean the same thing. There was never a Java 3.0 or 4.0— it jumped from
version 1 .4 to 5.0, but you will still find places where it’s called 1 .5 instead of 5. Don't ask.
(Oh, and just to make it more entertaining, Java 5 and the Mac OS X 10.4 were both given the
same code-name of 'Tiger’, and since OS X 10.4 is the version of the Mac OS you need to run
Java 5, you'll hear people talk about “Tiger on Tiger’. It just means Java 5 on OS X 10,4).
B The SDK does not include the API documentation, and you need that! Go back to java.sun .
com and get the J2SE API documentation. You can also access the API docs online, without
downloading them, but that's a pain. Trust us, ifs worth the download.
■ You need a text editor. Virtually any text editor will do (vi, emacs, pico), including the GUI ones
that come with most operating systems. Notepad, Wordpad, TextEdit, etc. all work, as long as
you make sure they don’t append a “.bd” on to the end of your source code.
■ Once you've downloaded and unpacked/zipped/whatever (depends on which version and for
which OS), you need to add an entry to your PATH environment variable that points to the /bin
directory inside the main Java directory. For example, if the J2SDK puts a directory on your
drive called ‘j2sdk1.5.0’, look inside that directory and you'll find the "bin" directory where the
Java binaries (the tools) live. Tha bin directory is the one you need a PATH to, so that when you
type:
% javac
at the command-line, your terminal will know how to find the javac compiler,
Note: if you have trouble with you installation, we recommend you go to javaranch.com, and join
the Java-Beginning forum! Actually, you should do that whether you have trouble or not.
Note: much of the code from this book Is available at wlckedlysmart.com
XXVlil intro
the intro
last-minute things you need to know:
This is a learning experience, not a reference book. We deliberately
stripped out everything that might get in the way of learning whatever it
is we’re working on at that point in the book. And the first time through,
you need to begin at the beginning, because the book makes assumptions
about what you’ve already seen and learned.
We use simple UML-fffre diagrams.
If we’d used pure\JML> you’d be seeing something that looks like Java, but
with syntax that’s just plain wrong. So we use a simplified version of UML
that doesn’t conflict with Java syntax. If you don’t already know UML, you
won't have to worry about leamingjava and UML at the same dme.
We don't worry about organizing and packaging your own
code until the end of the book.
In this book, you can get on with the business of leamingjava, without
stressing over some of the organizational or administrative details of
developingjava programs. You willy in the real world, need to know — and
use — these details, so we cover them in depth. But we save them for the end
of the book {chapter 17). Relax while you ease into Java, gently
The end-of-chapter exercises are mandatory; puzzles are
optional. Answers for both are at the end of each chapter.
One thing you need to know about the puzzles — they 're puzzles . As in logic
puzzles, brain teasers, crossword puzzles, etc. The exercises are here to help
you practice what you’ve learned, and you should do them all. The puzzles
are a different story, and some of them are quite challenging in a puzzle
way These puzzles are meant for puzzlers y and you probably already know if
you are one. If you’re not sure, we suggest you give some of them a try, but
whatever happens, don’t be discouraged if you can't solve a puzzle or if you
simply can't be bothered to take the time to work them out.
The ‘Sharpen Your Pencil” exercises don't have answers.
Not printed in the book, anyway. For some of them, there is no right
answer, and for the others, part of the learning experience for the Sharpen
activities is for you to decide if and when your answers are right. (Some of
our suggested answers are available on wickedlysman.com)
The code examples are as lean as possible
It’s frustrating to wade through 200 lines of code looking for the two lines
you need to understand. Most examples in this book are shown within the
smallest possible context, so that the pan you’re trying to learn is clear and
simple. So don’t expect the code to be robust, or even complete. That's
your assignment for after you finish the book. The book examples are
written specifically for learning and aren’t always fully-functional.
Dog
size
barkQ
eatQ
chaseCatQ
v/*» Should A° AU-
if the “Sharp
^tirpen your pencil
3 *L Josi-
you are here > xxix
*
tech editing: Jessica and Valentin
Technical Editors
"Credit goes to all, but mistakes are the sole reponsibility of the
author...”. Does anyone really believe that? See the two people on
this page? If you find technical problems, it's probably *A^rfault- :
)
Jess\M
Jessica
Jess works at Hewlett-Packard on the Self-
Healing Services Team. She has a Bachelor s
in Computer Engineering from Villanova
University, has her SCPj 1.4 and SCWCD
certifications, and is literally months away
from receiving her Masters in Software
Engineering at Drexel University (whew!)
When she’s not working, studying or
motoring in her MINI Cooper S, Jess can
be found fighting her cat for yam as she
completes her latest knitting or crochet
project (anybody want a hat?) She is
originally from SaJtLake City, Utah (no,
she s not Mormon... yes, you were too
going to ask) and is currently living near
Philadelphia with her husband, Mendra, and
two cats: Chai and Sake.
You can catch her moderating technical
forums atjavaranch.com.
Valentin Valentin Crettaz has a Masters degree
in Information and Computer Science from
the Swiss Federal Institute of Technology in
Lausanne (EPFL). He has worked as a software
engineer with SRI International (Menlo Park,
CA) and as a principal engineer in the Software
Engineering Laboratory of EPFL.
Valentin is the co-founder and CTO of Condris
Technologies, a company specializing in the
development of software architecture solutions.
His research and development interests
include aspect-oriented technologies, design
and architectural patterns, web services, and
software architecture. Besides taking care of
his wife, gardening, reading, and doing some
sport, Valentin moderates the SCBCD and
SCDJWS forums atjavaranch.com. He holds
the SCJP, SCJD, SCBCD, SCWCD, and SCDJWS
certifications. He has also had the opportunity
to serve as a co-author for Whizlabs SCBCD
Exam Simulator.
(WeTe still in shock from seeing him in a tit.)
XXX
intro
the intro
credit
Wo odruff
Other people to bWie;
Ai O'Reilly:
Our biggest thanks to Mike Loukides at O'Reilly, for taking a
chance on this, and helping to shape the Head First concept into
a book (and series ) . As this second edition goes to print there
are now five Head First books, and he's been with us all the way.
To Tim CPReilly, for his willingness to launch into something
completely new and different. Thanks to the clever Kyle Hart for
figuring out how Head First fits into the world, and for launching
the series- Finally, to Edie Freedman for designing the Head First
“emphasize die head” cover.
Our intrepid beta testers and reviewer team:
Our top honors and thanks go to the director of our javaranch
tech review team, Johannes de Jong. This is your fifth time around
with us on a Head First book, and we're thrilled you’re still speaking
to us. Jeff Cumps is on his third book with us now and relentless
about finding areas where we needed to be more clear or correct.
Corey McGlone, you rock. And we think you give the clearest
explanations on javaranch. You’ll probably notice we stole one or
two of them. Jason Menard saved our technical butts on more
than a few details, and Thomas Paul, as always, gave us expert
feedback and found the subtle Java issues the rest of us missed.
Jane Griscti has her Java chops (and knows a thing or two about
writing) and it was great to have her helping on the new edition
along with long-time javarancher Barry Gaunt
Marilyn de Queiroz gave us excellent help on both editions of the
book. Chris Jones, John Nyquist, James Cubeta, Terri Cubeta,
and Ira Becker gave us a ton of help on the first edition.
Special thanks to a few of the Head Firsters who've been helping
us from the beginning: Angelo Celeste, Mikalai Zaikin, and
Thomas Duff (twdufif.com). And th
Lire la suite
- 33.97 MB
- 15
Vous recherchez le terme ""

65

60

45