Head First Java, 2nd Edition

Book description

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.

Publisher resources

View/Submit Errata

Table of contents

  1. Head First Java™
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. What they’re saying about Head First
  5. Praise for Head First Java
  6. Praise for other Head First books co-authored by Kathy and Bert
  7. Creators of the Head First series
  8. How to Use This Book: Intro
    1. Who is this book for?
      1. Who should probably back away from this book?
    2. We know what you’re thinking
    3. And we know what your brain is thinking
    4. Metacognition: thinking about thinking
    5. Here’s what WE did
    6. Here’s what YOU can do to bend your brain into submission
    7. What you need for this book
    8. Last-minute things you need to know
    9. Technical Editors
    10. Other people to : credit
    11. Just when you thought there wouldn’t be any more acknowledgements
  9. 1. Dive in A Quick Dip: Breaking the Surface
    1. The Way Java Works
    2. What you’ll do in Java
    3. A very brief history of Java
    4. Code structure in Java
    5. Anatomy of a class
    6. Writing a class with a main
      1. What can you say in the main method?
    7. Looping and looping and...
      1. Simple boolean tests
      2. Example of a while loop
    8. Conditional branching
    9. Coding a Serious Business Application
      1. Monday morning at Bob’s
    10. Phrase-O-Matic
      1. How it works
  10. 2. Classes and Objects: A Trip to Objectville
    1. Chair Wars: (or How Objects Can Change Your Life)
      1. In Larry’s cube
      2. At Brad’s laptop at the cafe
        1. Larry thought he’d nailed it. He could almost feel the rolled steel of the Aeron beneath his...
        2. But wait! There’s been a spec change
      3. Back in Larry’s cube
      4. At Brad’s laptop at the beach
        1. Larry snuck in just moments ahead of Brad
      5. Back in Larry’s cube
      6. At Brad’s laptop on his lawn chair at the Telluride Bluegrass Festival
      7. So, Brad the OO guy got the chair, right?
      8. What about the Amoeba rotate()?
      9. The suspense is killing me. Who got the chair?
      10. When you design a class, think about the objects that will be created from that class type. Think about
        1. Things an object knows about itself are called
        2. Things an object can do are called
      11. A class is not an object. (but it’s used to construct them)
    2. Making your first object
    3. Making and testing Movie objects
    4. Quick! Get out of main!
      1. The two uses of main:
      2. The Guessing Game
    5. Running the Guessing Game
  11. 3. Primitives and References: Know Your Variables
    1. Declaring a variable
    2. “I’d like a double mocha, no, make it an int.”
    3. You really don’t want to spill that...
    4. Back away from that keyword!
    5. This table reserved
    6. Controlling your Dog object
    7. An object reference is just another variable value
      1. Life on the garbage-collectible heap
      2. Life and death on the heap
    8. An array is like a tray of cups
    9. Arrays are objects too
    10. Make an array of Dogs
      1. What’s missing?
    11. Control your Dog (with a reference variable)
      1. What happens if the Dog is in a Dog array?
    12. A Dog example
  12. 4. Methods Use Instance Variables: How Objects Behave
    1. Remember: a class describes what an object knows and what an object does
      1. Can every object of that type have different method behavior?
    2. The size affects the bark
    3. You can send things to a method
    4. You can get things back from a method
    5. You can send more than one thing to a method
      1. Calling a two-parameter method, and sending it two arguments
      2. You can pass variables into a method, as long as the variable type matches the parameter type
    6. Java is pass-by-value. That means pass-by-copy
    7. Cool things you can do with parameters and return types
    8. Encapsulation
      1. Do it or risk humiliation and ridicule
      2. Hide the data
    9. Encapsulating the GoodDog class
    10. How do objects in an array behave?
    11. Declaring and initializing instance variables
    12. The difference between instance and local variables
    13. Comparing variables (primitives or references)
  13. 5. Writing a Program: Extra-Strength Methods
    1. Let’s build a Battleship-style game: “Sink a Dot Com”
      1. part of a game interaction
    2. First, a high-level design
    3. The “Simple Dot Com Game” a gentler introduction
    4. Developing a Class
      1. The three things we’ll write for each class:
      2. Writing the method implementations
        1. let’s write the real method code now, and get this puppy working
      3. Writing test code for the SimpleDotCom class
      4. Based on this prepcode:
      5. Here’s what we should test:
      6. Test code for the SimpleDotCom class
    5. The checkYourself() method
      1. Just the new stuff
        1. Final code for SimpleDotCom and SimpleDotComTester
      2. Prepcode for the SimpleDotComGame class
        1. Everything happens in main()
    6. The game’s main() method
      1. random() and getUserInput()
      2. One last class: GameHelper
      3. Let’s play
        1. A complete game interaction
      4. What’s this? A bug?
        1. Gasp!
        2. A different game interaction
    7. More about for loops
      1. Regular (non-enhanced) for loops
    8. Trips through a loop
      1. Difference between for and while
    9. The enhanced for loop
    10. Casting primitives
  14. 6. Get to Know the Java API: Using the Java Library
    1. In our last chapter, we left you with the cliff-hanger. A bug
      1. How it’s supposed to look
        1. A complete game interaction
      2. How the bug looks
        1. A different game interaction
    2. So what happened?
    3. How do we fix it ?
    4. Option one is too clunky
    5. Option two is a little better, but still pretty clunky
    6. Wake up and smell the library
    7. Some things you can do with ArrayList
    8. Comparing ArrayList to a regular array
    9. Comparing ArrayList to a regular array
    10. Let’s fix the DotCom code
    11. New and improved DotCom class
    12. Let’s build the REAL game: “Sink a Dot Com”
      1. part of a game interaction
    13. What needs to change?
    14. Who does what in the DotComBust game (and when)
    15. Prep code for the real DotComBust class
    16. The final version of the DotCom class
    17. Super Powerful Boolean Expressions
    18. Using the Library (the Java API)
    19. How to play with the API
  15. 7. Inheritance and Polymorphism: Better Living in Objectville
    1. Chair Wars Revisited...
      1. What about the Amoeba rotate()?
      2. Understanding Inheritance
      3. An inheritance example:
    2. Let’s design the inheritance tree for an Animal simulation program
    3. Using inheritance to avoid duplicating code in subclasses
    4. Do all animals eat the same way?
      1. Which methods should we override?
    5. Looking for more inheritance opportunities
      1. Which method is called?
    6. Designing an Inheritance Tree
      1. Using IS-A and HAS-A
      2. But wait! There’s more!
      3. How do you know if you’ve got your inheritance right?
        1. Who gets the Porsche, who gets the porcelain?
    7. When designing with inheritance, are you using or abusing?
      1. So what does all this inheritance really buy you?
      2. Inheritance lets you guarantee that all classes grouped under a certain supertype have all the methods that the supertype has.
        1. In other words, you define a common protocol for a set of classes related through inheritance
        2. With polymorphism, you can write code that doesn’t have to change when you introduce new subclass types into the program
    8. Keeping the contract: rules for overriding
    9. Overloading a method
  16. 8. Interfaces and Abstract Classes: Serious Polymorphism
    1. Did we forget about something when we designed this?
      1. The compiler won’t let you instantiate an abstract class
      2. Abstract vs. Concrete
      3. Abstract methods
      4. You MUST implement all abstract methods
      5. Polymorphism in action
      6. Uh-oh, now we need to keep Cats, too
      7. What about non-Animals? Why not make a class generic enough to take anything?
      8. So what’s in this ultra-super-megaclass Object?
      9. Using polymorphic references of type Object has a price...
      10. When a Dog won’t act like a Dog
      11. Objects don’t bark
      12. Get in touch with your inner Object
      13. What if you need to change the contract?
      14. Let’s explore some design options for reusing some of our existing classes in a PetShop program
    2. Interface to the rescue!
    3. Making and Implementing the Pet interface
  17. 9. Constructors and Garbage Collection: Life and Death of an Object
    1. The Stack and the Heap: where things live
    2. Methods are stacked
      1. A stack scenario
    3. What about local variables that are objects?
    4. If local variables live on the stack, where do instance variables live?
    5. The miracle of object creation
    6. Construct a Duck
    7. Initializing the state of a new Duck
    8. Using the constructor to initialize important Duck state
    9. Make it easy to make a Duck
      1. Be sure you have a no-arg constructor
    10. Doesn’t the compiler always make a no-arg constructor for you? No!
    11. Nanoreview: four things to remember about constructors
    12. Wait a minute... we never DID talk about superclasses and inheritance and how that all fits in with constructors
    13. The role of superclass constructors in an object’s life
    14. Making a Hippo means making the Animal and Object parts too...
    15. How do you invoke a superclass constructor?
    16. Can the child exist before the parents?
    17. Superclass constructors with arguments
    18. Invoking one overloaded constructor from another
    19. Now we know how an object is born, but how long does an object live?
    20. What about reference variables?
  18. 10. Numbers and Statics: Numbers Matter
    1. MATH methods: as close as you’ll ever get to a global method
    2. The difference between regular (non-static) and static methods
    3. What it means to have a class with static methods
    4. Static methods can’t use non-static (instance) variables!
    5. Static methods can’t use non-static methods, either!
    6. Static variable: value is the same for ALL instances of the class
    7. Initializing a static variable
    8. static final variables are constants
    9. final isn’t just for static variables...
    10. Math methods
    11. Wrapping a primitive
    12. Before Java 5.0, YOU had to do the work...
    13. Autoboxing: blurring the line between primitive and object
    14. Autoboxing works almost everywhere
    15. But wait! There’s more! Wrappers have static utility methods too!
    16. And now in reverse... turning a primitive number into a String
    17. Number formatting
    18. Formatting deconstructed...
    19. The percent (%) says, “insert argument here” (and format it using these instructions)
    20. The format String uses its own little language syntax
    21. The format specifier
    22. The only required specifier is for TYPE
    23. What happens if I have more than one argument?
    24. So much for numbers, what about dates?
    25. Working with Dates
    26. Moving backward and forward in time
    27. Getting an object that extends Calendar
    28. Working with Calendar objects
    29. Highlights of the Calendar API
    30. Even more Statics!... static imports
  19. 11. Exception Handling: Risky Behavior
    1. Let’s make a Music Machine
      1. The finished BeatBox looks something like this:
    2. We’ll start with the basics
      1. The JavaSound API
    3. First we need a Sequencer
      1. Something’s wrong!
      2. What happens when a method you want to call (probably in a class you didn’t write) is risky?
      3. Methods in Java use exceptions to tell the calling code, “Something Bad Happened. I failed.”
    4. The compiler needs to know that YOU know you’re calling a risky method
    5. An exception is an object... of type Exception
    6. If it’s your code that catches the exception, then whose code throws it?
    7. Flow control in try/catch blocks
    8. Finally: for the things you want to do no matter what
    9. Did we mention that a method can throw more than one exception?
      1. Catching multiple exceptions
    10. Exceptions are polymorphic
    11. Multiple catch blocks must be ordered from smallest to biggest
    12. You can’t put bigger baskets above smaller baskets
    13. When you don’t want to handle an exception...
    14. Ducking (by declaring) only delays the inevitable
    15. Getting back to our music code...
      1. Exception Rules
    16. Making actual sound
    17. Your very first sound player app
    18. Making a MidiEvent (song data)
    19. MIDI message: the heart of a MidiEvent
    20. Change a message
      1. Version 2: Using command-line args to experiment with sounds
  20. 12. Getting GUI: A Very Graphic Story
    1. It all starts with a window
      1. Put widgets in the window
    2. Your first GUI: a button on a frame
    3. But nothing happens when I click it...
    4. Getting a user event
    5. Listeners, Sources, and Events
    6. Getting back to graphics...
    7. Make your own drawing widget
    8. Fun things to do in paintComponent()
    9. Behind every good Graphics reference is a Graphics2D object
    10. Because life’s too short to paint the circle a solid color when there’s a gradient blend waiting for you
    11. We can get an event. We can paint graphics. But can we paint graphics when we get an event?
    12. GUI layouts: putting more than one widget on a frame
    13. Let’s try it with TWO buttons
    14. So now we need FOUR widgets
    15. And we need to get TWO events
      1. How do you get action events for two different buttons, when each button needs to do something different?
      2. How do you get action events for two different buttons, when each button needs to do something different?
    16. Inner class to the rescue!
    17. An inner class instance must be tied to an outer class instance
    18. How to make an instance of an inner class
    19. Using an inner class for animation
    20. Listening for a non-GUI event
    21. An easier way to make messages / events
      1. Example: how to use the new static makeEvent() method
        1. Version Two: registering and getting ControllerEvents
        2. Version Three: drawing graphics in time with the music
  21. 13. Using Swing: Work on Your Swing
    1. Swing components
      1. Components can be nested
    2. Layout Managers
    3. How does the layout manager decide?
      1. Different layout managers have different policies
    4. The Big Three layout managers: border, flow, and box
    5. Playing with Swing components
    6. Making the BeatBox
  22. 14. Serialization and File I/O: Saving Objects
    1. Capture the Beat
    2. Saving State
    3. Writing a serialized object to a file
    4. Data moves in streams from one place to another
    5. What really happens to an object when it’s serialized?
    6. But what exactly IS an object’s state? What needs to be saved?
    7. If you want your class to be serializable, implement Serializable
    8. Deserialization: restoring an object
    9. What happens during deserialization?
    10. Saving and restoring the game characters
      1. The GameCharacter class
    11. Writing a String to a Text File
    12. Text File Example: e-Flashcards
    13. Quiz Card Builder (code outline)
    14. The java.io.File class
    15. Reading from a Text File
    16. Quiz Card Player (code outline)
    17. Parsing with String split()
    18. Version ID: A Big Serialization Gotcha
    19. Using the serialVersionUID
    20. Saving a BeatBox pattern
    21. Restoring a BeatBox pattern
  23. 15. Networking and Threads: Make a Connection
    1. Real-time Beat Box Chat
    2. Connecting, Sending, and Receiving
    3. Make a network Socket connection
    4. A TCP port is just a number. A 16-bit number that identifies a specific program on the server
    5. To read data from a Socket, use a BufferedReader
    6. To write data to a Socket, use a PrintWriter
    7. The DailyAdviceClient
    8. DailyAdviceClient code
    9. Writing a simple server
    10. DailyAdviceServer code
    11. Writing a Chat Client
    12. Java has multiple threads but only one Thread class
    13. What does it mean to have more than one call stack?
    14. Every Thread needs a job to do. A method to put on the new thread stack
    15. To make a job for your thread, implement the Runnable interface
    16. The Thread Scheduler
    17. Putting a thread to sleep
    18. Using sleep to make our program more predictable
    19. Making and starting two threads
    20. What will happen?
    21. Um, yes. There IS a dark side
      1. Threads can lead to concurrency ‘issues’
    22. The Ryan and Monica problem, in code
      1. The Ryan and Monica example
    23. We need the makeWithdrawal ( ) method to run as one atomic thing
    24. Using an object’s lock
    25. The dreaded “Lost Update” problem
    26. Let’s run this code...
    27. Make the increment() method atomic. Synchronize it!
    28. The deadly side of synchronization
    29. New and improved SimpleChatClient
    30. The really really simple Chat Server
  24. 16. Collections and Generics: Data structures
    1. Tracking song popularity on your jukebox
    2. Here’s what you have so far, without the sort:
    3. But the ArrayList class does NOT have a sort() method!
    4. ArrayList is not the only collection
    5. You could use a TreeSet... Or you could use the Collections.sort() method
    6. Adding Collections.sort() to the Jukebox code
    7. But now you need Song objects, not just simple Strings
    8. Changing the Jukebox code to use Songs instead of Strings
    9. It won’t compile!
      1. The sort() method declaration
    10. Generics means more type-safety
    11. Learning generics
    12. Using generic CLASSES
    13. Using type parameters with ArrayList
    14. Using generic METHODS
    15. Here’s where it gets weird...
    16. Revisiting the sort( ) method
    17. In generics, “extends” means “extends or implements”
    18. Finally we know what’s wrong...
      1. The Song class needs to implement Comparable
    19. The new, improved, comparable Song class
    20. We can sort the list, but...
    21. Using a custom Comparator
    22. Updating the Jukebox to use a Comparator
    23. Uh-oh. The sorting all works, but now we have duplicates...
    24. We need a Set instead of a List
    25. The Collection API (part of it)
    26. Using a HashSet instead of ArrayList
    27. What makes two objects equal?
    28. How a HashSet checks for duplicates: hashCode() and equals()
    29. The Song class with overridden hashCode() and equals()
    30. And if we want the set to stay sorted, we’ve got TreeSet
    31. What you MUST know about TreeSet...
    32. TreeSet elements MUST be comparable
    33. We’ve seen Lists and Sets, now we’ll use a Map
    34. Finally, back to generics
    35. Using polymorphic arguments and generics
    36. But will it work with ArrayList<Dog> ?
    37. What could happen if it were allowed...
    38. Wildcards to the rescue
    39. Alternate syntax for doing the same thing
  25. 17. Package, Jars and Deployment: Release Your Code
    1. Deploying your application
    2. Imagine this scenario...
    3. Separate source code and class files
    4. Put your Java in a JAR
    5. Running (executing) the JAR
    6. Put your classes in packages!
      1. Packages prevent class name conflicts
    7. Preventing package name conflicts
    8. Compiling and running with packages
    9. The -d flag is even cooler than we said
    10. Making an executable JAR with packages
    11. So where did the manifest file go?
    12. Java Web Start
    13. The .jnlp file
  26. 18. Remote Deployment with RMI: Distributed Computing
    1. Method calls are always between two objects on the same heap
    2. What if you want to invoke a method on an object running on another machine?
    3. Object A, running on Little, wants to call a method on Object B, running on Big
    4. But you can’t do that
    5. The role of the ‘helpers’
    6. Java RMI gives you the client and service helper objects!
    7. How does the client get the stub object?
    8. How does the client get the stub class?
    9. Be sure each machine has the class files it needs
    10. Yeah, but who really uses RMI?
      1. What about Servlets?
      2. A very simple Servlet
      3. HTML page with a link to this servlet
      4. Just for fun, let’s make the Phrase-O-Matic work as a servlet
      5. Phrase-O-Matic code, servlet-friendly
      6. Enterprise JavaBeans: RMI on steroids
      7. For our final trick... a little Jini
      8. Adaptive discovery in action
      9. Self-healing network in action
      10. Final Project: the Universal Service browser
  27. A. Final Code Kitchen
    1. Final BeatBox client program
    2. Final BeatBox server program
  28. B. The Top Ten Topics that almost made it into the Real Book...
    1. #10 Bit Manipulation
      1. Why do you care?
    2. #9 Immutability
      1. Why do you care that Strings are Immutable?
      2. Why do you care that Wrappers are Immutable?
    3. #8 Assertions
    4. #7 Block Scope
    5. #6 Linked Invocations
    6. #5 Anonymous and Static Nested Classes
    7. #4 Access Levels and Access Modifiers (Who Sees What)
    8. #3 String and StringBuffer/StringBuilder Methods
    9. #2 Multidimensional Arrays
    10. And the number one topic that didn’t quite make it in...
    11. #1 Enumerations (also called Enumerated Types or Enums)
  29. C. This isn’t goodbye
  30. Index
  31. About the Authors
  32. Copyright

Product information

  • Title: Head First Java, 2nd Edition
  • Author(s): Kathy Sierra, Bert Bates
  • Release date: February 2005
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9780596009205