Sign up
Forgot password?
FAQ: Login

Sierra K., Bates B., Gee T. Head First Java: A Brain-Friendly Guide

  • pdf file
  • size 155,95 MB
  • added by
  • info modified
Sierra K., Bates B., Gee T. Head First Java: A Brain-Friendly Guide
Sebastopol: O’Reilly Media, 2022. — 716 p. — ISBN: 978-149-191077-1.
What will you learn from this book?
Head First Java is a complete learning experience in Java and object-oriented programming. With this book, you'll learn the Java language with a unique method that goes beyond how-to manuals and helps you become a great programmer. Through puzzles, mysteries, and soul-searching interviews with famous Java objects, you'll quickly get up to speed on Java's fundamentals and advanced topics including lambdas, streams, generics, threading, networking, and the dreaded desktop GUI. If you have experience with another programming language, Head First Java will engage your brain with more modern approaches to coding--the sleeker, faster, and easier to read, write, and maintain Java of today.
What's so special about this book?
If you've read a Head First book, you know what to expect--a visually rich format designed for the way your brain works. If you haven't, you're in for a treat. With Head First Java, you'll learn Java through a multisensory experience that engages your mind, rather than using a text-heavy approach that puts you to sleep.
Who is this book for?
Metacognition: thinking about thinking.
Here’s what WE did.
Here’s what YOU can do to bend your brain into submission.
What do you need for this book?
Last-minute things you need to know.
Chapter 1: Breaking the Surface.
The way Java works.
What you’ll do in Java.
A very brief history of Java.
Code structure in Java.
Anatomy of a class.
Writing a class with a main().
Looping and looping and...
Conditional branching.
Coding a serious business application.
Phrase-O-Matic.
Chapter 2: A Trip to Objectville.
Chair Wars (or How Objects Can Change Your Life).
What’s the difference between class and an object?
Making your first object.
Making and testing Movie objects.
Quick! Get out of the main!
Running the Guessing Game.
Chapter 3: Know Your Variables.
Declaring a variable.
“I’d like a double mocha, no, make it an int.”.
You don’t want to spill that...
Back away from that keyword!
Controlling your Dog object.
An object reference is just another variable value.
Life on the garbage-collectible heap.
An array is like a tray of cups.
Make an array of Dogs.
Control your Dog(with a reference variable).
Chapter 4: How Objects Behave.
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 a method.
Java is pass-by-value. That means pass-by-copy.
Cool things you can do with parameters and return types.
Encapsulation.
Encapsulating the GoodDog class.
How do objects in an array behave?
Declaring and initializing instance variables.
The difference between instance and local variables.
Comparing variables (primitives or references).
Chapter 5: Extra-Strength Methods.
Let’s build a Battleship-style game: “Sink a Startup”.
The first, is a high-level design.
The “Simple Startup Game” is a gentler introduction.
Developing a Class.
Writing the method implementations.
Writing test code for the SimpleStartup class.
The checkYourself() method.
Just the new stuff.
Final code for SimpleStartup and SimpleStartupTestDrive.
Prep code for the SimpleStartupGame class.
The game’s main() method.
random() and getUserInput().
One last class: GameHelper.
Let’s play.
More about for loops.
Trips through a loop.
The enhanced for loop.
Casting primitives.
Chapter 6: Using the Java Library.
In our last chapter, we left you with the cliff-hanger: a bug.
So what happened?
How do we fix it?
Option one is too clunky.
Option two is a little better, but still pretty clunky.
Option three.
Wake up and smell the library.
Some things you can do with ArrayList.
Comparing ArrayList to a regular array.
Let’s fix the Startup code.
New and improved Startup class.
Let’s build the REAL game: “Sink a Startup”.
What needs to change?
Who does what in the StartupBust game (and when)?
Prep code for the real StartupBust class.
The final version of the Startup class.
Super powerful Boolean expressions.
Ready-BakeCode.
Using the Library (the Java API).
How to discover the API.
Using the class documentation.
Chapter 7: Better Living in Objectville.
Chair Wars Revisited...
Understanding Inheritance.
Let’s design the inheritance tree for an Animal simulation program.
Using inheritance to avoid duplicating code in subclasses.
Do all animals eat the same way?
Looking for more inheritance opportunities.
Which method is called?
Designing an Inheritance Tree.
Using IS-A and HAS-A.
How do you know if you’ve got your inheritance right?
When designing with inheritance, are you using or abusing it?
So what does all this inheritance buy you?
Inheritance lets you guarantee that all classes grouped under a certain supertype have all the methods that the supertype has*.
polymorphism in action.
Keeping the contract: rules for overriding.
Overloading a method.
Chapter 8: Serious Polymorphism.
Did we forget about something when we designed this?
What does a new Animal() object look like?
The compiler won’t let you instantiate an abstract class.
Abstract vs. Concrete.
Abstract methods.
You MUST implement all abstract methods.
Polymorphism in action.
Uh-oh, now we need to keep Cats, too.
What about non-Animals? Why not make a class generic enough to take anything?
So what’s in this ultra-super-megaclass Object?
Using polymorphic references of type Object has a price...
When a Dog won’t act like a Dog.
Objects don’t bark.
Get in touch with your inner Object.
What if you need to change the contract?
Let’s explore some design options for reusing some of our existing classes in a PetShop program.
Interface to the rescue!
Making and implementing the Pet interface.
Invoking the superclass version of a method.
Chapter 9: Life and Death of an Object.
The Stack and the Heap: where things live.
Methods are stacked.
What about local variables that are objects?
If local variables live on the stack, where do instance variables live?
The miracle of object creation.
Construct a Duck.
Initializing the state of a new Duck.
Using the constructor to initialize important Duck state.
Make it easy to make a Duck.
Doesn’t the compiler always make a no-arg constructor for you?
Nano review: four things to remember about constructors.
Wait a minute...we never DID talk about superclasses and inheritance and how that all fits in with constructors.
The role of superclass constructors in an object’s life.
Making a Hippo means making the Animal and Object parts too...
How do you invoke a superclass constructor?
Can the child exist before the parents?
Superclass constructors with arguments.
Invoking one overloaded constructor from another.
Now we know how an object is born, but how long does an object live?
What about reference variables?
Chapter 10: Numbers Matter.
MATH methods: as close as you’ll ever get to a global method.
The difference between regular (non-static) and static methods.
What it means to have a class with static methods.
Static methods can’t use non-static (instance) variables!
Static methods can’t use non-static methods, either!
Static variable: value is the same for ALL instances of the class.
Initializing a static variable.
static final variables are constants.
final isn’t just for static variables...
Math methods.
Wrapping a primitive.
Java will Autobox primitives for you.
Autoboxing works almost everywhere.
But wait! There’s more! Wrappers have static utility methods too!
And now in reverse...turning a primitive number into a String.
Number formatting.
Formatting deconstructed...
The percent (%) says, “insert argument here”.
The formatted String uses its little language syntax.
The format specifier.
The only required specifier is for TYPE.
What happens if I have more than one argument?
Just one more thing...static imports.
Chapter 11: Data Structures.
Tracking song popularity on your jukebox.
Your first job, sort the songs in alphabetical order.
Great question! You spotted the diamond operator.
Exploring java.util API, List, and Collections.
“Natural Ordering,” what Java means by alphabetical.
But now you need Song objects, not just simple Strings.
Changing the Jukebox code to use Songs instead of Strings.
It won’t compile!
The sort() method declaration.
Generics means more type-safety.
Learning generics.
Using generic CLASSES.
Using type parameters with ArrayList.
Using generic METHODS.
Here’s where it gets weird...
Revisiting the sort() method.
In generics, “extends” means “extends or implements”.
Finally, we know what’s wrong... The Song class needs to implement Comparable.
The new, improved, comparable Song class.
We can sort the list, but...
Using a custom Comparator.
Updating the Jukebox to use a Comparator.
But wait! We’re sorting in two different ways!
Sorting using only Comparators.
Just the code that matters.
What do we REALLY need to sort?
Enter lambdas! Leveraging what the compiler can infer.
Where did all that code go?
Updating the Jukebox code with lambdas.
Uh-oh. The sorting all works, but now we have duplicates...
We need a Set instead of a List.
The Collection API (part of it).
Using a HashSet instead of ArrayList.
What makes two objects equal?
How a HashSet checks for duplicates: hashCode() and equals().
The Song class with overridden hashCode() and equals().
If we want the set to stay sorted, we’ve got TreeSet.
What you MUST know about TreeSet...
TreeSet elements MUST be comparable.
We’ve seen Lists and Sets, now we’ll use a Map.
Creating and filling collections.
Convenience Factory Methods for Collections.
Finally, back to generics.
But will it work with List?
What could happen if it were allowed...?
We can do this with wildcards.
Using the method’s generic type parameter.
Chapter 12: Lambdas and Streams: What, Not How.
Tell the computer WHAT you want.
When loops go wrong.
Small errors in common code can be hard to spot.
Building blocks of common operations.
Introducing the Streams API.
Getting started with Streams.
Streams are like recipes: nothing’s going to happen until someone cooks them.
Getting a result from a Stream.
Stream operations are building blocks.
Building blocks can be stacked and combined.
Customizing the building blocks.
Create complex pipelines block by block.
Yes, because Streams are lazy.
Terminal operations do all the work.
Collecting to a List.
Guidelines for working with streams.
Hello Lambda, my (not so) old friend.
Passing behavior around.
Lambda expressions are objects, and you run them by calling their Single Abstract Method.
The shape of lambda expressions.
Anatomy of a lambda expression.
Variety is the spice of life.
How can I tell if a method takes a lambda?
Spotting Functional Interfaces.
Functional interfaces in the wild.
Lou’s back!
Ready-Bake Code.
Lou’s Challenge #1: Find all the “rock” songs.
Filter a stream to keep certain elements.
Let’s Rock!
Getting clever with filters.
Lou’s Challenge #2: List all the genres.
Mapping from one type to another.
Removing duplicates.
Only one of every genre.
Sometimes you don’t even need a lambda expression.
Collecting results in different ways.
But wait, there’s more!
Optional is a wrapper.
Don’t forget to talk to the Optional wrapper.
Chapter 13: Risky Behavior.
Let’s make a Music Machine.
We’ll start with the basics.
First, we need a Sequencer.
What happens when a method you want to call (probably in a class you didn’t write) is risky?
Methods in Java use exceptions to tell the calling code, “Something Bad Happened. I failed.”.
The compiler needs to know that YOU know you’re calling a risky method.
An exception is an object...of type Exception.
If it’s your code that catches the exception, then whose code throws it?
Flow control in try/catch blocks.
Finally: for the things you want to do no matter what.
Did we mention that a method can throw more than one exception?
Exceptions are polymorphic.
Multiple catch blocks must be ordered from smallest to biggest.
You can’t put bigger baskets above smaller baskets.
When you don’t want to handle an exception…just duck it.
Ducking (by declaring) only delays the inevitable.
Handle or Declare. It’s the law.
Getting back to our music code...
Code Kitchen.
Making actual sound.
Version 1: Your very first sound player app.
Making a MidiEvent (song data).
MIDI message: the heart of a MidiEvent.
Change a message.
Version 2: Using command-line args to experiment with sounds.
Where we’re headed with the rest of the Code Kitchens.
Chapter 14: A Very Graphic Story.
It all starts with a window.
Your first GUI: a button on a frame.
But nothing happens when I click it...
Getting a user event.
Getting a button’s ActionEvent.
Listeners, Sources, and Events.
Getting back to graphics...
Make your drawing widget.
Fun things to do in paintComponent().
Behind every good Graphics reference is a Graphics2D object.
Because life’s too short to paint the circle a solid color when there’s a gradient blend waiting for you.
We can get an event. We can paint graphics. But can we paint graphics when we get an event?
GUI layouts: putting more than one widget on a frame.
Let’s try it with TWO buttons.
Inner class to the rescue!
An inner class instance must be tied to an outer class instance.
How to make an instance of an inner class.
Lambdas to the rescue! (again).
ActionListener is a Functional Interface.
Using an inner class for animation.
The complete simple animation code.
Code Kitchen.
Listening for a non-GUI event.
An easier way to make messages/events.
Version One: using the new static makeEvent() method.
Version Two: registering and getting ControllerEvents.
Version Three: drawing graphics in time with the music.
Chapter 15: Work on Your Swing.
Swing components.
Layout Managers.
How does the layout manager decide?
The Big Three layout managers: border, flow, and box.
FlowLayout cares about the flow of the components.
BoxLayout to the rescue!
Playing with Swing components.
Code Kitchen.
Making the BeatBox.
Chapter 16: Saving Objects (and Text).
Capture the beat.
Saving state.
Writing a serialized object to a file.
Data moves in streams from one place to another.
What happens to an object when it’s serialized?
But what exactly IS an object’s state? What needs to be saved?
If you want your class to be serializable, implement Serializable.
Deserialization: restoring an object.
What happens during deserialization?
Saving and restoring the game characters.
The GameCharacter class.
Version ID: A big serialization gotcha.
Using the serialVersionUID.
Writing a String to a Text File.
Text file example: e-Flashcards.
Quiz Card Builder (code outline).
The java.io.File class.
The beauty of buffers.
Reading from a text file.
Quiz Card Player (code outline).
Parsing with String split().
NIO.2 and the java.nio.file package.
Path, Paths, and Files (messing with directories).
Finally, a closer look at finally.
The try-with-resources (TWR), statement.
Autocloseable, the very small catch.
Code Kitchen.
Saving a BeatBox pattern.
Restoring a BeatBox pattern.
Chapter 17: Make a Connection.
Real-time BeatBox chat.
Chat program overview.
Connecting, sending, and receiving.1. Connect.
A TCP port is just a number...a 16-bit number that identifies a specific program on the server.2. Receive.3. Send.
There’s more than one way to make a connection.
The DailyAdviceClient.
DailyAdviceClient code.
Writing a simple server application.
DailyAdviceServer code.
Writing a Chat Client.
Ready-Bake Code.
Java has multiple threads but onlyone the Thread class.
What does it mean to have more than one call stack?
To create a new call stack you need a job to run.
To make a job for your thread, implement the Runnable interface.
How we used to launch a new thread.
A better alternative: don’t manage the Threads at all.
The three states of a new thread.
The thread scheduler.
How did we end up with different results?
Putting a thread to sleep.
Using sleep to make our program more predictable.
There are downsides to forcing the thread to sleep.
Counting down until ready.
Making and starting two threads (or more!).
Pooling Threads.
Running multiple threads.
Closing time at the thread pool.
Um, yes. There IS a dark side. Multithreading can lead to concurrency “issues.”.
New and improved SimpleChatClient.
Code Kitchen.
Chapter 18: Dealing with Concurrency Issues.
What could go wrong?
Marriage in Trouble. Can this couple be saved?
The Ryan and Monica problem, in code.
They need a lock for account access!
We need to check the balance and spend the money as one atomic thing.
Using an object’s lock.
Using synchronized methods.
It’s important to lock the correct object.
The dreaded “Lost Update” problem.
Let’s run this code...
Make the increment() method atomic. Synchronize it!
Deadlock is a deadly side of synchronization.
You don’t always have to use synchronized.
Compare and swap with atomic variables.
Ryan and Monica, going atomic.
Writing a class for immutable data.
Using immutable objects.
Changing immutable data.
More problems with shared data.
Reading from a changing data structure causes an Exception.
Use a thread-safe data structure.
CopyOnWriteArrayList.
Appendix A: Final Code Kitchen.
Final BeatBox client program.
Final BeatBox server program.
Appendix B: The top ten-ish topics that didn't make it into the rest of the book...
#11 JShell (Java REPL).
#10 Packages.
#9 Immutability in Strings and Wrappers.
#8 Access levels and access modifiers (who sees what).
#7 Varargs.
#6 Annotations.
#5 Lambdas and Maps.
#4 Parallel Streams.
#3 Enumerations (also called enumerated types or enums).
#2 Local Variable Type Inference (var).
#1 Records.
  • Sign up or login using form at top of the page to download this file.
  • Sign up
Up