Learning a complex new language is no easy task especially when it s an object-oriented computer programming language like Java. You might think the problem is your brain. It seems to have a mind of its own, a mind that doesn't always want to take in the dry, technical stuff you're forced to study.
The fact is your brain craves novelty. It's constantly searching, scanning, waiting for something unusual to happen. After all, that's the way it was built to help you stay alive. It takes all the routine, ordinary, dull stuff and filters it to the background so it won't interfere with your brain's real work--recording things that matter. How does your brain know what matters? It's like the creators of the Head First approach say, suppose you're out for a hike and a tiger jumps in front of you, what happens in your brain? Neurons fire. Emotions crank up. Chemicals surge.
That's how your brain knows.
And that's how your brain will learn Java. Head First Java combines puzzles, strong visuals, mysteries, and soul-searching interviews with famous Java objects to engage you in many different ways. It's fast, it's fun, and it's effective. And, despite its playful appearance, Head First Java is serious stuff: a complete introduction to object-oriented programming and Java. You'll learn everything from the fundamentals to advanced topics, including threads, network sockets, and distributed programming with RMI. And the new. second edition focuses on Java 5.0, the latest version of the Java language and development platform. Because Java 5.0 is a major update to the platform, with deep, code-level changes, even more careful study and implementation is required. So learning the Head First way is more important than ever.
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. You'll see why people say it's unlike any other Java book you've ever read.
By exploiting how your brain works, Head First Java compresses the time it takes to learn and retain--complex information. Its unique approach not only shows you what you need to know about Java syntax, it teaches you to think like a Java programmer. If you want to be bored, buy some other book. But if you want to understand Java, this book's for you.
Table of contents
- Head First Java™
- A Note Regarding Supplemental Files
- What they’re saying about Head First
- Praise for Head First Java
- Praise for other Head First books co-authored by Kathy and Bert
- Creators of the Head First series
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 Editors
- Other people to : credit
- Just when you thought there wouldn’t be any more acknowledgements
1. Dive in A Quick Dip: 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
2. Classes and Objects: A Trip to Objectville
Chair Wars: (or How Objects Can Change Your Life)
- In Larry’s cube
- At Brad’s laptop at the cafe
- Back in Larry’s cube
- At Brad’s laptop at the beach
- Back in Larry’s cube
- At Brad’s laptop on his lawn chair at the Telluride Bluegrass Festival
- So, Brad the OO guy got the chair, right?
- What about the Amoeba rotate()?
- The suspense is killing me. Who got the chair?
- When you design a class, think about the objects that will be created from that class type. Think about
- A class is not an object. (but it’s used to construct them)
- Making your first object
- Making and testing Movie objects
- Quick! Get out of main!
- Running the Guessing Game
- Chair Wars: (or How Objects Can Change Your Life)
3. Primitives and References: Know Your Variables
- 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
- An array is like a tray of cups
- Arrays are objects too
- Make an array of Dogs
- Control your Dog (with a reference variable)
- A Dog example
4. Methods Use Instance Variables: 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 to a method
- Java is pass-by-value. That means pass-by-copy
- Cool things you can do with parameters and return types
- 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)
5. Writing a Program: Extra-Strength Methods
- Let’s build a Battleship-style game: “Sink a Dot Com”
- First, a high-level design
- The “Simple Dot Com Game” a gentler introduction
- Developing a Class
- The checkYourself() method
- The game’s main() method
- More about for loops
- Trips through a loop
- The enhanced for loop
- Casting primitives
6. Get to Know the Java API: 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
- Wake up and smell the library
- Some things you can do with ArrayList
- Comparing ArrayList to a regular array
- Comparing ArrayList to a regular array
- Let’s fix the DotCom code
- New and improved DotCom class
- Let’s build the REAL game: “Sink a Dot Com”
- What needs to change?
- Who does what in the DotComBust game (and when)
- Prep code for the real DotComBust class
- The final version of the DotCom class
- Super Powerful Boolean Expressions
- Using the Library (the Java API)
- How to play with the API
7. Inheritance and Polymorphism: Better Living in Objectville
- Chair Wars Revisited...
- 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
- Designing an Inheritance Tree
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
8. Interfaces and Abstract Classes: Serious Polymorphism
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
- 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
- Did we forget about something when we designed this?
9. Constructors and Garbage Collection: 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? 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?
10. Numbers and Statics: 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
- Before Java 5.0, YOU had to do the work...
- Autoboxing: blurring the line between primitive and object
- 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?
- So much for numbers, what about dates?
- Working with Dates
- Moving backward and forward in time
- Getting an object that extends Calendar
- Working with Calendar objects
- Highlights of the Calendar API
- Even more Statics!... static imports
11. Exception Handling: Risky Behavior
- Let’s make a Music Machine
- We’ll start with the basics
- First we need a Sequencer
- 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...
- Ducking (by declaring) only delays the inevitable
- Getting back to our music code...
- Making actual sound
- Your very first sound player app
- Making a MidiEvent (song data)
- MIDI message: the heart of a MidiEvent
- Change a message
12. Getting GUI: 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
- 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
- Using an inner class for animation
- Listening for a non-GUI event
- An easier way to make messages / events
- 13. Using Swing: Work on Your Swing
14. Serialization and File I/O: Saving Objects
- 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
- 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()
- Version ID: A Big Serialization Gotcha
- Using the serialVersionUID
- Saving a BeatBox pattern
- Restoring a BeatBox pattern
15. Networking and Threads: Make a Connection
- Real-time Beat Box Chat
- Connecting, Sending, and Receiving
- Make a network Socket connection
- A TCP port is just a number. A 16-bit number that identifies a specific program on the server
- To read data from a Socket, use a BufferedReader
- To write data to a Socket, use a PrintWriter
- The DailyAdviceClient
- DailyAdviceClient code
- Writing a simple server
- DailyAdviceServer code
- Writing a Chat Client
- Java has multiple threads but only one Thread class
- What does it mean to have more than one call stack?
- Every Thread needs a job to do. A method to put on the new thread stack
- To make a job for your thread, implement the Runnable interface
- The Thread Scheduler
- Putting a thread to sleep
- Using sleep to make our program more predictable
- Making and starting two threads
- What will happen?
- Um, yes. There IS a dark side
- The Ryan and Monica problem, in code
- We need the makeWithdrawal ( ) method to run as one atomic thing
- Using an object’s lock
- The dreaded “Lost Update” problem
- Let’s run this code...
- Make the increment() method atomic. Synchronize it!
- The deadly side of synchronization
- New and improved SimpleChatClient
- The really really simple Chat Server
16. Collections and Generics: Data structures
- Tracking song popularity on your jukebox
- Here’s what you have so far, without the sort:
- But the ArrayList class does NOT have a sort() method!
- ArrayList is not the only collection
- You could use a TreeSet... Or you could use the Collections.sort() method
- Adding Collections.sort() to the Jukebox code
- But now you need Song objects, not just simple Strings
- Changing the Jukebox code to use Songs instead of Strings
- It won’t compile!
- 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
- 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()
- And 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
- Finally, back to generics
- Using polymorphic arguments and generics
- But will it work with ArrayList<Dog> ?
- What could happen if it were allowed...
- Wildcards to the rescue
- Alternate syntax for doing the same thing
17. Package, Jars and Deployment: Release Your Code
- Deploying your application
- Imagine this scenario...
- Separate source code and class files
- Put your Java in a JAR
- Running (executing) the JAR
- Put your classes in packages!
- Preventing package name conflicts
- Compiling and running with packages
- The -d flag is even cooler than we said
- Making an executable JAR with packages
- So where did the manifest file go?
- Java Web Start
- The .jnlp file
18. Remote Deployment with RMI: Distributed Computing
- Method calls are always between two objects on the same heap
- What if you want to invoke a method on an object running on another machine?
- Object A, running on Little, wants to call a method on Object B, running on Big
- But you can’t do that
- The role of the ‘helpers’
- Java RMI gives you the client and service helper objects!
- How does the client get the stub object?
- How does the client get the stub class?
- Be sure each machine has the class files it needs
Yeah, but who really uses RMI?
- What about Servlets?
- A very simple Servlet
- HTML page with a link to this servlet
- Just for fun, let’s make the Phrase-O-Matic work as a servlet
- Phrase-O-Matic code, servlet-friendly
- Enterprise JavaBeans: RMI on steroids
- For our final trick... a little Jini
- Adaptive discovery in action
- Self-healing network in action
- Final Project: the Universal Service browser
- A. Final Code Kitchen
B. The Top Ten Topics that almost made it into the Real Book...
- #10 Bit Manipulation
- #9 Immutability
- #8 Assertions
- #7 Block Scope
- #6 Linked Invocations
- #5 Anonymous and Static Nested Classes
- #4 Access Levels and Access Modifiers (Who Sees What)
- #3 String and StringBuffer/StringBuilder Methods
- #2 Multidimensional Arrays
- And the number one topic that didn’t quite make it in...
- #1 Enumerations (also called Enumerated Types or Enums)
- C. This isn’t goodbye
- About the Authors
- Title: Head First Java, 2nd Edition
- Release date: February 2005
- Publisher(s): O'Reilly Media, Inc.
- ISBN: 9780596009205
You might also like
Designing Data-Intensive Applications
Data is at the center of many challenges in system design today. Difficult issues need to …
Generative Deep Learning, 2nd Edition
Generative AI is the hottest topic in tech. This practical book teaches machine learning engineers and …
Effective Java, 3rd Edition
Since this Jolt-award winning classic was last updated in 2008, the Java programming environment has changed …
Spring Boot: Up and Running
With over 75 million downloads per month, Spring Boot is the most widely used Java framework …