Book description
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 by means of a text-heavy approach that puts you to sleep.
Publisher resources
Table of contents
- Other books in OâReillyâs Head First series
- Table of Contents (the real thing)
-
How to Use This Book: Intro
- Who is this book for?
- We know what youâre thinking
- And we know what your brain is 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:
- Technical Reviewers for the 3rd Edition
- Other people to acknowledge for the 3rd Edition
- Technical Editors for the 2nd Edition
- Other people to credit, for the 2nd Edition
- Just when you thought there wouldnât be any more acknowledgments*
-
1. Breaking the Surface: Dive In: A Quick Dip
- 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()
- What can you say in the main method?
- Looping and looping and...
- Conditional branching
- Coding a serious business application
- Monday morning at Bobâs Java-enabled house
- Phrase-O-Matic
- Exercise
- Exercise Solutions
-
2. A Trip to Objectville: Classes and Objects
-
Chair Wars
- (or How Objects Can Change Your Life)
- At Lauraâs desk
- At Bradâs laptop at the cafe
- Back at Lauraâs desk
- At Bradâs laptop at the beach
- Back at Lauraâs desk
- At Bradâs laptop on his lawn chair at the Telluride Bluegrass Festival
- So, Brad the OO guy got the chair and desk, right?
- What about the Amoeba rotate()?
- The suspense is killing me. Who got the chair and desk?
- When you design a class, think about the objects that will be created from that class type. Think about:
- Whatâs the difference between a class and an object?
- Making your first object
- Making and testing Movie objects
- Quick! Get out of main!
- Running the Guessing Game
- Exercise
- Exercise Solutions
-
Chair Wars
-
3. Know Your Variables: Primitives and References
- Declaring a variable
- âIâd like a double mocha, no, make it an int.â
- You really donât want to spill that...
- Back away from that keyword!
- This table reserved
- Controlling your Dog object
- An object reference is just another variable value
- Java Exposed
- An array is like a tray of cups
- Arrays are objects too
- Make an array of Dogs
- Control your Dog (with a reference variable)
- What happens if the Dog is in a Dog array?
- A Dog example
- Exercise
- Exercise Solutions
-
4. How Objects Behave: Methods Use Instance Variables
- 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
- Java is pass-by-value. That means pass-by-copy.
- Reminder: Java cares about type!
- Cool things you can do with parameters and return types
- Encapsulation
- Java Exposed
- 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)
- Exercise
- Exercise Solutions
-
5. Extra-Strength Methods: Writing A Program
- Letâs build a Battleship-style game: âSink a Startupâ
- First, a high-level design
- The âSimple Startup Gameâ a gentler introduction
- Developing a Class
- Writing the method implementations
- Writing test code for the SimpleStartup class
- 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 Everything happens in main()
- The gameâs main() method
- random() and getUserInput()
- One last class: GameHelper
- Letâs play
- Whatâs this? A bug ?
- More about for loops
- Trips through a loop
- The enhanced for loop
- Casting primitives
- Exercise
- Exercise Solutions
-
6. Using the Java Library: Get to Know the Java API
- 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
- Wake up and smell the library
- Some things you can do with ArrayList
- Java Exposed
- Solution
- 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-Bake Code
- Using the Library (the Java API)
- You have to know the full name* of the class you want to use in your code.
- How to discover the API
- Browse a book
- Use the HTML API docs
- Using the class documentation
- Exercise
- Exercise Solutions
-
7. Better Living in Objectville: Inheritance and Polymorphism
- Chair Wars Revisited...
- What about the Amoeba rotate()?
- Understanding Inheritance
- An inheritance example:
- 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
- But wait! Thereâs more!
- How do you know if youâve got your inheritance right?
- When designing with inheritance, are you using or abusing?
- So what does all this inheritance really buy you?
- Inheritance lets you guarantee that all classes grouped under a certain supertype have all the methods that the supertype has*
- Keeping the contract: rules for overriding
- Overloading a method
- Exercise
- Exercise Solutions
-
8. Serious Polymorphism: Interfaces and Abstract Classes
- Did we forget about something when we designed this?
- 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
- Polymorphism means âmany forms.â
- 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
- Exercise
- Exercise Solutions
-
9. Life and Death of an Object: Constructors and Garbage Collection
- 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? No!
- Nanoreview: 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?
- Exercise
- Exercise Solutions
-
10. Numbers Matter: Numbers and Statics
- 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
- 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â (and format it using these instructions)
- The format String uses its own 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
- Fireside Chats
- Exercise
- Exercise Solution
-
11. Data Structures: Collections and Generics
- Tracking song popularity on your jukebox
- Your first job, sort the songs in alphabetical order
- Great question! You spotted the diamond operator
- Exploring the java.util API, List and Collections
- In the âReal-Worldâ⢠there are lots of ways to sort
- â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 new, improved, comparable Song class
- We can sort the list, but...
- Using a custom Comparator
- Updating the Jukebox to use a Comparator
- Fill-in-the-blanks
- But wait! Weâre sorting in two different ways!
- Sorting using only Comparators
- Just the code that matters
- What do we REALLY need in order to sort?
- Enter lambdas! Leveraging what the compiler can infer
- Where did all that code go?
- Some interfaces have only ONE method to implement
- Updating the Jukebox code with lambdas
- Reverse Engineer
- 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<Dog>?
- What could happen if it were allowed...?
- We can do this with wildcards
- Using the methodâs generic type parameter
- Exercise
- Exercise Solution
-
12. Lambdas and Streams: What, Not How: Lambdas and Streams
- Tell the computer WHAT you want
- Fireside Chats
- When for 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 actually 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
- Exercise
- Hello Lambda, my (not so) old friend
- 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?
- Exercise
- Spotting Functional Interfaces
- Functional interfaces in the wild
- Louâs back!
- Exercise
- 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
- Just keep building!
- 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
- Exercise Solutions
-
13. Risky Behavior: Exception Handling
- 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
- Flow Control
- 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...
- Ducking (by declaring) only delays the inevitable
- 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
- Exercise
- Exercise Solution
-
14. A Very Graphic Story: Getting Gui
- 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
- Listeners, Sources, and Events
- Getting back to graphics...
- Make your own 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
- So now we need FOUR widgets
- And we need to get TWO events
- 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
- Lambdas, clearer and more concise
- Using an inner class for animation
- 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
- Exercise
- Exercise Solutions
- 15. Work on Your Swing: Using Swing
-
16. Saving Objects (and Text): Serialization and File I/O
- Capture the beat
- Saving state
- Writing a serialized object to a file
- Data moves in streams from one place to another
- What really 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
- Version ID: A big serialization gotcha
- Using the serialVersionUID
- Object Serialization
- Writing a String to a Text File
- Text file example: e-Flashcards
- Quiz Card Builder (code outline)
- The java.io.File class
- 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
- Remember, finally ALWAYS runs!!
- Finally, a closer look at finally, cont.
- There IS a better way!
- The try-with-resources (TWR), statement
- Autocloseable, the very small catch
- Autocloseable, itâs everywhere you do I/O
- Code Kitchen
- Saving a BeatBox pattern
- Restoring a BeatBox pattern
- Can they be saved?
- Exercise
- Exercise Solutions
-
17. Make a Connection: Networking and Threads
- Real-time BeatBox chat
- Connecting, sending, and receiving
- 1. Connect
- 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
- The really, really simple Chat Server
- Java has multiple threads but only one 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 NOT to run the Runnable
- How we used to launch a new thread
- A better alternative: donât manage the Threads at all
- Running one job
- The thread scheduler
- 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
- What will happen?
- Closing time at the thread pool
- Um, yes. There IS a dark side. Multithreading can lead to concurrency âissues.â
- Exercise
- New and improved SimpleChatClient
- Exercise
- Exercise Solutions
-
18. Dealing with Concurrency Issues: Race Conditions and Immutable Data
- What could possibly go wrong?
- The Ryan and Monica problem, in code
- The Ryan and Monica example
- 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, 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
- Exercise
- Exercise Solution
- A. Final Code Kitchen
-
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
- Index
- Authors of Head First Java and Creators of the Head First series
- Co-author of Head First Java, 3rd Edition
Product information
- Title: Head First Java, 3rd Edition
- Author(s):
- Release date: May 2022
- Publisher(s): O'Reilly Media, Inc.
- ISBN: 9781491910771
You might also like
book
Head First Java, 2nd Edition
Learning a complex new language is no easy task especially when it s an object-oriented computer …
book
Effective Java, 3rd Edition
Since this Jolt-award winning classic was last updated in 2008, the Java programming environment has changed …
book
Learning Java, 6th Edition
Ideal for working programmers new to Java, this best-selling book guides you through the language features …
book
Java in a Nutshell, 7th Edition
This updated edition of Java in a Nutshell not only helps experienced Java programmers get the …