Head First Java A Brain-Friendly Guide 3rd Edition

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Find the original Textbook (PDF) in the link below:

CLICK HERE
Contents

Table of Contents (summary) Intro 1 xxi Breaking


the Surface: dive in: a quick dip 2 3 4 5 6 7 8 9 A
Trip to Objectville: classes and objects Know Your
Variables: primitives and references How Objects
Behave: methods use instance variables Extra-
Strength Methods: writing a program Using the Java
Library: get to know the Java API Better Living in
Objectville: inheritance and polymorphism Serious
Polymorphism: interfaces and abstract classes Life
and Death of an Object: constructors and garbage
collection 10 Numbers Matter: numbers and statics
11 Data Structures: collections and generics 12
What, Not How: lambdas and streams 13 Risky
Behavior: exception handling 14 A Very Graphic
Story: intro to GUI, event handling, and inner
classes 15 Work on Your Swing: using swing 16
Saving Objects (and Text): serialization and file I/O
17 Make a Connection: networking and threads 18
Dealing with Concurrency Issues: race conditions
and immutable data A Appendix A: final code
kitchen B Appendix B: the top ten-ish topics that
didn’t make it into the rest of the book Index 1 27 49
71 95 125 167 199 237 275 309 369 421 461 509
539 587 639 673 683 701 Table of Contents (the
real thing) i Intro 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? We know what you’re thinking.
Metacognition: thinking about thinking. Here’s what
WE did Here’s what YOU can do to bend your brain
into submission What you need for this book Last-
minute things you need to know xxvi xxvii xxix xxx
xxxi xxxii xii xxxiii table of contents 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 fea tures, 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. The Way Java Works Virtual Machines
Method Party() 0 aload_0 1 invokespecial #1 4
return Compiled bytecode What you’ll do in Java A
Very Brief History of Java Code structure in Java
Writing a class with a main() Simple boolean tests
Conditional branching Coding a Serious Business
Phrase-O-Matic Exercises Exercise Solutions 2 3 4
7 9 13 15 16 19 20 25 2 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 (OO) 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. Chair Wars Making your first object Making and
testing Movie objects Quick! Get out of main!
Running the Guessing Game Exercises Exercise
Solutions 28 36 37 38 40 42 47 xiii table of contents
3 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. 24 size D o int fido g
Dog reference Declaring a variable “I’d like a double
mocha, no, make it an int.” Back away from that
keyword! Controlling your Dog object An object
reference is just another variable value. Life on the
garbage-collectible heap o An array is like a tray of
cups A Dog example Exercises Exercise Solutions b
50 51 53 54 55 57 59 62 63 68 4How Objects
Behave State affects behavior, behavior affects
state. We know that objects j 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! e pass-by-value means pass-by-copy
copy of x X int Z int foo.go(x); void go(int z){ }
00000111 Remember: a class describes what an
object knows and what an object does The size
affects the bark You can send things to a method
You can get things back from a method. You can
send more than one thing to a method Cool things
you can do with parameters and return types
Encapsulation How do objects in an array behave?
Declaring and initializing instance variables
Comparing variables (primitives or references)
Exercises Exercise Solutions 72 ct 73 74 75 76 79
80 83 84 86 88 93 xiv 00000111 5Extra-Strength
Methods table of contents 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 Startup (similar
to Battleship). Let’s build a Battleship-style game:
“Sink a Startup” Developing a Class We’re gonna
build the Sink a Startup game Writing the method
implementations Writing test code for the
SimpleStartup class The checkYourself() method
Prep code for the SimpleStartupGame class The
game’s main() method Let’s play More about for
loops The enhanced for loop Casting primitives
Exercises Exercise Solutions 96 99 101 102 104
108 110 113 114 116 117 118 122 6Using the Java
Library Java ships with hundreds of prebuilt 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. In our last chapter, we left you with the cliff-
hanger. A bug. “Good to know there’s an ArrayList in
the java. util package. But by myself, how would I
have f igured that out?”- Julia, 31, hand model Wake
up and smell the library Some things you can do
with ArrayList Comparing ArrayList to a regular array
Let’s build the REAL game: “Sink a Startup” Prep
code for the real StartupBust class The final version
of the Startup class Super Powerful Boolean
Expressions Using the Library (the Java API)
Exercises Exercise Solutions 126 132 133 137 140
144 150 151 154 163 165 xv xvi Did we forget about
something when we designed this? 200 The
compiler won’t let you instantiate an abstract class
203 Abstract vs. Concrete 204 You MUST
implement all abstract methods 206 Polymorphism
in action 208 Why not make a class generic enough
to take anything? 210 When a Dog won’t act like a
Dog 214 Let’s explore some design options 221
Making and Implementing the Pet interface 227
Invoking the superclass version of a method 230
Exercises 232 Exercise Solutions 235 7Better 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. 8Serious
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... Make it
Stick Roses are red, violets are blue. Square IS-A
Shape, the reverse isn’t true. Roses are red, violets
are dear. Beer IS-A Drink, but not all drinks are beer.
OK, your turn. Make one that shows the one way-
ness of the IS-A relationship. And remem ber, if X
extends Y, X IS-A Y must make sense. Object o =
al.get(id); Dog d = (Dog) o; d.bark(); Object o Dog
object Dog d cast the Object back to a Dog we know
is there. Object Chair Wars Revisited... 168
Understanding inheritance 170 Let’s design the
inheritance tree for an Animal simulation program
172 Looking for more inheritance opportunities 175
Using IS-A and HAS-A 179 How do you know if
you’ve got your inheritance right? 181 When
designing with inheritance, are you using or
abusing? 183 Keeping the contract: rules for
overriding 192 Overloading a method 193 Exercises
194 Exercise Solutions 197 table of contents 9Life
and Death of an Object table of contents 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 things live Methods
are stacked c u D D u k c k d ‘d’ is assigned a new
Duck object, leaving the original (first) Duck object
abandoned. That first Duck is toast. What about
local variables that are objects? When someone
calls The miracle of object creation Construct a Duck
Doesn’t the compiler always make a no-arg
constructor for you? the go() method, this Duck is
abandoned. His only reference has been
reprogrammed for a different Duck. Nanoreview: four
things to remember about constructors o The role of
superclass constructors in an object’s life Can the
child exist before the parents? What about reference
variables? I don’t like where this is headed. o b
Exercises Exercise Solutions Heap b e 238 239 240
242 244 248 251 253 256 262 263 268 272 j
10Numbers Matter Static variables are shared by all
instances of a class. e j c 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. c static variable:
iceCream kid instance one kid instance two MATH
methods: as close as you’ll ever get to a global
method The difference between regular (non-static)
and static methods instance variables: one per
instance static variables: one per class Initializing a
static variable Math methods Wrapping a primitive
Autoboxing works almost everywhere Turning a
primitive number into a String Number formatting
The format specifier Exercise Exercise Solutions 276
277 283 288 290 292 295 t t 296 300 306 308 xvii
table of contents 11 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 0 1 2 Set 3 Map “Ball” “Ball1”
“Ball2” “Fish” “Car” “Fish” “Car” Exploring the
java.util API, List and Collections Generics means
more type-safety Revisiting the sort() method The
new, improved, comparable Song class Sorting
using only Comparators Updating the Jukebox code
with Lambdas Using a HashSet instead of ArrayList
What you MUST know about TreeSet... We’ve seen
Lists and Sets, now we’ll use a Map Finally, back to
generics Exercise Solutions 314 320 327 330 336
342 347 353 355 358 364 12 Lambdas and
Streams: What, Not How What if...you didn’t need to
tell the computer HOW to do something? In this
chapter we’ll look at the Streams API. You’ll see how
helpful lambda expressions can be when you’re
using streams, and you’ll learn how to use the
Streams API to query and transform the data in a
collection. Songs Only let certain songs pass to
Output results as a
List .stream() .filter( ) .collect(toList) Tell the
computer WHAT you want When for loops go wrong
Introducing the Streams API Getting a result from a
Stream Guidelines for working with streams Hello
Lambda, my (not so) old friend Spotting Functional
Interfaces Lou’s Challenge #1: Find all the “rock”
songs Lou’s Challenge #2: List all the genres
Exercises Exercise Solutions 370 372 375 378 384
368 396 400 404 415 417 xviii the next stage
13Risky Behavior table of contents o ba c k n p t i
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. e c x class
Bar { void go() { moo(); your code class MyOuter
{ class MyInner { void go() { } } } The outer and inner
objects are now intimately linked. These two objects
on the heap have a special bond. The inner can use
the outer’s variables (and vice versa). Let’s make a
Music Machine e a class Cow { 1 calls risky method
void moo() { if (serverDown){ class with a risky
method First we need a Sequencer 2 n An exception
is an object...of type Exception Flow control in
try/catch blocks s explode(); Did we mention that a
method can throw more than one exception?
Multiple catch blocks must be ordered from smallest
to biggest w Ducking (by declaring) only delays the
inevitable Code Kitchen o Version 1: Your very first
sound player app Version 2: Using command-line
args to experiment with sounds Exercises Exercise
Solutions r 422 424 428 432 435 438 442 445 448
452 454 457 h 14A 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, we’ll paint on the screen, we’ll
display a JPEG image, and we’ll even do some
animation. t It all starts with a window Getting a user
event Listeners, Sources, and Events i n Make your
own drawing widget Fun things to do in
paintComponent() n e r GUI layouts: putting more
than one widget on a frame Inner class to the
rescue! lambdas to the rescue! (again) Using an
inner class for animation o An easier way to make
messages/events Exercises u Exercise Solutions t e
r 462 465 469 472 473 478 484 490 492 498 502
507 xix table of contents 15 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. Components in the east and west get
their preferred width. Things in the north and south
get their preferred height. The center gets
whatever’s left. Swing components Layout
Managers The Big Three layout managers: border,
flow, and box. Playing with Swing components Code
Kitchen Making the BeatBox Exercises Exercise
Solutions 510 511 513 523 526 529 534 537 16
Saving Objects (and Text) 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.
serialized Any questions? deserialized Writing a
serialized object to a file If you want your class to be
serializable, implement Serializable Deserialization:
restoring an object Version ID: A Big Serialization
Gotcha Writing a String to a Text File Reading from
a Text File Quiz Card Player (code outline) Path,
Paths, and Files (messing with directories) Finally, a
closer look at finally Saving a BeatBox pattern
Exercises Exercise Solutions 542 547 551 556 559
566 567 573 574 579 580 xx 584 xxi 17Make 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? Connection to port 5000 on the
server at 196.164.1.103 Connection back to the
client at 196.164.1.100, port 4242 Server Client
Connecting, Sending, and Receiving 590 The
DailyAdviceClient 598 Writing a simple server
application 601 Java has multiple threads but only
one Thread class 610 The three states of a new
thread 616 Putting a thread to sleep 622 Making and
starting two threads (or more!) 626 Closing time at
the thread pool 629 New and improved
SimpleChatClient 632 Exercises 631 Exercise
Solutions 636 A 18Dealing with Concurrency Issues
Doing two or more things at once is hard. Writing
multithreaded code is easy. Writing multithreaded
code that works the way you expect can be much
harder. In this final chapter, we’re going to show you
some of the things that can go wrong when two or
more threads are working at the same time. You’ll
learn about some of the tools in java.util.concurrent
that can help you to write multithreaded code that
works correctly. You’ll learn how to create immutable
objects (objects that don’t change) that are safe for
multiple threads to use. By the end of the chapter,
you’ll have a lot of different tools in your toolkit for
working with concurrency. The Ryan and Monica
problem, in code 642 Using an object’s lock 647 The
dreaded “Lost Update” problem 650 Make the
increment() method atomic. Synchronize it! 652
Deadlock, a deadly side of synchronization 654
Compare-and-swap with atomic variables 656 Using
immutable objects 659 More problems with shared
data 662 Use a thread-safe data structure 664
Exercises 668 Exercise Solutions 670

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. The lure of
write-once/run-anywhere is just too strong.
A devoted following exploded, as
programmers fought against bugs, limita
tions, and, oh yeah, the fact that it was dog
slow. But that was ages ago. If you’re just
starting in Java, you’re lucky. Some of us
had to walk five miles in the snow, uphill
both ways (barefoot), to get even the most
trivial application to work. But you, why, you
get to ride the sleeker, faster, easier-to-
read-and-write Java of today.
A very brief history of Java Java was
initially released (some would say
“escaped”), on January 23, 1996. It’s over
25 years old! In the first 25 years, Java as a
language evolved, and the Java API grew
enormously. The best estimate we have is
that over 17 gazillion lines of Java code
have been written in the last 25 years. As
you spend time programming in Java, you
will most certainly come across Java code
that’s quite old, and some that’s much
newer. Java is famous for its backward
compatibility, so old code can run quite
happily on new JVMs. In this book we’ll
generally start off by using older coding
styles (remember, you’re likely to encounter
such code in the “real world”), and then
we’ll introduce newer-style code. In a
similar fashion, we will sometimes show
you older classes in the Java API, and then
show you newer alternatives. I’ve heard
that Java isn’t very fast compared to
compiled languages like C and Rust.
chapter 1 Speed and memory usage When
Java was first released, it was slow. But
soon after, the HotSpot VM was created, as
were other performance enhanc ers. While
it’s true that Java isn’t the fastest language
out there, it’s considered to be a very fast
language—almost as fast as languages like
C and Rust, and much faster than most
other languages out there. Java has a
magic super-power—the JVM. The Java
Virtual Machine can optimize your code
while it’s running, so it’s possible to create
very fast applications without having to
write special ized high-performance code.
But—full disclosure—compared to C and
Rust, Java uses a lot of memory.

Find the original Textbook (PDF) in the link below:

CLICK HERE

You might also like