Table of Contents (the real thing)

  1. How to Use This Book: 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?

    1. “Who is this book for?”

    2. “We know what you’re thinking”

    3. “Metacognition: thinking about thinking”

    4. “Here’s what WE did:”

    5. “Here’s what YOU can do to bend your brain into submission”

    6. “What you need for this book:”

    7. “Last-minute things you need to know:”

  2. Chapter 1

    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. 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.

    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. “Writing a class with a main()”

    6. “Simple boolean tests”

    7. “Conditional branching”

    8. “Coding a serious business application”

    9. “Phrase-O-Matic”

    10. “Exercise”

    11. “Exercise Solutions”

  3. Chapter 2

    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.

    1. “Chair Wars”

    2. “Making your first object”

    3. “Making and testing Movie objects”

    4. “Quick! Get out of main!”

    5. “Running the Guessing Game”

    6. “Exercise”

    7. “Exercise Solutions”

  4. Chapter 3

    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.

    1. “Declaring a variable”

    2. ““I’d like a double mocha, no, make it an int.””

    3. “Back away from that keyword!”

    4. “Controlling your Dog object”

    5. “An object reference is just another variable value”

    6. “Life on the garbage-collectible heap”

    7. “An array is like a tray of cups”

    8. “A Dog example”

    9. “Exercise”

    10. “Exercise Solutions”

  5. Chapter 4

    State affects behavior, behavior affects state. We know that objects 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!

    1. “Remember: a class describes what an object knows and what an object does”

    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”

    6. “Cool things you can do with parameters and return types”

    7. “Encapsulation”

    8. “How do objects in an array behave?”

    9. “Declaring and initializing instance variables”

    10. “Comparing variables (primitives or references)”

    11. “Exercise”

    12. “Exercise Solutions”

  6. Chapter 5

    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).

    1. “Let’s build a Battleship-style game: “Sink a Startup””

    2. “Developing a Class”

    3. “Writing the method implementations”

    4. “Writing test code for the SimpleStartup class”

    5. “The checkYourself() method”

    6. “Prep code for the SimpleStartupGame class Everything happens in main()”

    7. “The game’s main() method”

    8. “Let’s play”

    9. “More about for loops”

    10. “The enhanced for loop”

    11. “Casting primitives”

    12. “Exercise”

    13. “Exercise Solutions”

  7. Chapter 6

    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.

    1. “In our last chapter, we left you with the cliff-hanger: a bug”

    2. “Wake up and smell the library”

    3. “Some things you can do with ArrayList”

    4. “Comparing ArrayList to a regular array”

    5. “Let’s build the REAL game: “Sink a Startup””

    6. “Prep code for the real StartupBust class”

    7. “The final version of the Startup class”

    8. “Super powerful Boolean expressions”

    9. “Using the Library (the Java API)”

    10. “Exercise”

    11. “Exercise Solutions”

  8. Chapter 7

    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.

    1. “Chair Wars Revisited...”

    2. “Understanding Inheritance”

    3. “Let’s design the inheritance tree for an Animal simulation program”

    4. “Looking for more inheritance opportunities”

    5. “Using IS-A and HAS-A”

    6. “How do you know if you’ve got your inheritance right?”

    7. “When designing with inheritance, are you using or abusing?”

    8. “Keeping the contract: rules for overriding”

    9. “Overloading a method”

    10. “Exercise”

    11. “Exercise Solutions”

  9. Chapter 8

    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...

    1. “Did we forget about something when we designed this?”

    2. “The compiler won’t let you instantiate an abstract class”

    3. “Abstract vs. Concrete”

    4. “You MUST implement all abstract methods”

    5. “Polymorphism in action”

    6. “What about non-Animals? Why not make a class generic enough to take anything?”

    7. “When a Dog won’t act like a Dog”

    8. “Let’s explore some design options for reusing some of our existing classes in a PetShop program”

    9. “Making and implementing the Pet interface”

    10. “Invoking the superclass version of a method”

    11. “Exercise”

    12. “Exercise Solutions”

  10. Chapter 9

    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.

    1. “The Stack and the Heap: where things live”

    2. “Methods are stacked”

    3. “What about local variables that are objects?”

    4. “The miracle of object creation”

    5. “Construct a Duck”

    6. “Doesn’t the compiler always make a no-arg constructor for you? No!”

    7. “Nanoreview: four things to remember about constructors”

    8. “The role of superclass constructors in an object’s life”

    9. “Can the child exist before the parents?”

    10. “What about reference variables?”

    11. Figure 

    12. “Exercise”

    13. “Exercise Solutions”

  11. Chapter 10

    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.

    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. “Initializing a static variable”

    4. “Math methods”

    5. “Wrapping a primitive”

    6. “Autoboxing works almost everywhere”

    7. “And now in reverse...turning a primitive number into a String”

    8. “Number formatting”

    9. “The format specifier”

    10. “Exercise”

    11. “Exercise Solution”

  12. Chapter 11

    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 coworkers by the number of times they’ve stabbed you in the back?

    1. “Exploring the java.util API, List and Collections”

    2. “Generics means more type-safety”

    3. “Revisiting the sort() method”

    4. “The new, improved, comparable Song class”

    5. “Sorting using only Comparators”

    6. “Updating the Jukebox code with lambdas”

    7. “Using a HashSet instead of ArrayList”

    8. “What you MUST know about TreeSet...”

    9. “We’ve seen Lists and Sets, now we’ll use a Map”

    10. “Finally, back to generics”

    11. “Exercise Solution”

  13. Chapter 12

    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.

    1. “Tell the computer WHAT you want”

    2. “When for loops go wrong”

    3. “Introducing the Streams API”

    4. “Getting a result from a Stream”

    5. “Guidelines for working with streams”

    6. “Hello Lambda, my (not so) old friend”

    7. “Spotting Functional Interfaces”

    8. “Lou’s Challenge #1: Find all the “rock” songs”

    9. “Lou’s Challenge #2: List all the genres”

    10. “Exercise”

    11. “Exercise Solutions”

  14. Chapter 13

    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.

    1. “Let’s make a Music Machine”

    2. “First we need a Sequencer”

    3. “An exception is an object... of type Exception”

    4. “Flow control in try/catch blocks”

    5. “Did we mention that a method can throw more than one exception?”

    6. “Multiple catch blocks must be ordered from smallest to biggest”

    7. “Ducking (by declaring) only delays the inevitable”

    8. “Code Kitchen”

    9. “Version 1: Your very first sound player app”

    10. “Version 2: Using command-line args to experiment with sounds”

    11. “Exercise”

    12. “Exercise Solution”

  15. Chapter 14

    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.

    1. “It all starts with a window”

    2. “Getting a user event”

    3. “Listeners, Sources, and Events”

    4. “Make your own drawing widget”

    5. “Fun things to do in paintComponent()”

    6. “GUI layouts: putting more than one widget on a frame”

    7. “Inner class to the rescue!”

    8. “Lambdas to the rescue! (again)”

    9. “Using an inner class for animation”

    10. “An easier way to make messages/events”

    11. “Exercise”

    12. “Exercise Solutions”

  16. Chapter 15

    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.

    1. “Swing components”

    2. “Layout Managers”

    3. “The Big Three layout managers: border, flow, and box”

    4. “Playing with Swing components”

    5. “Code Kitchen”

    6. “Making the BeatBox”

    7. “Exercise”

    8. “Exercise Solutions”

  17. Chapter 16

    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.

    1. “Writing a serialized object to a file”

    2. “If you want your class to be serializable, implement Serializable”

    3. “Deserialization: restoring an object”

    4. “Version ID: A big serialization gotcha”

    5. “Writing a String to a Text File”

    6. “Reading from a text file”

    7. “Quiz Card Player (code outline)”

    8. “Path, Paths, and Files (messing with directories)”

    9. “Finally, a closer look at finally”

    10. “Saving a BeatBox pattern”

    11. “Exercise”

    12. “Exercise Solutions”

  18. Chapter 17

    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?

    1. “Connecting, sending, and receiving”

    2. “The DailyAdviceClient”

    3. “Writing a simple server application”

    4. “Java has multiple threads but only one Thread class”

    5. “The three states of a new thread”

    6. “Putting a thread to sleep”

    7. “Making and starting two threads (or more!)”

    8. “Closing time at the thread pool”

    9. “New and improved SimpleChatClient”

    10. “Exercise”

    11. “Exercise Solutions”

  19. Chapter 18

    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.

    1. “The Ryan and Monica problem, in code”

    2. “Using an object’s lock”

    3. “The dreaded “Lost Update” problem”

    4. “Make the increment() method atomic. Synchronize it!”

    5. “Deadlock, a deadly side of synchronization”

    6. “Compare-and-swap with atomic variables”

    7. “Using immutable objects”

    8. “More problems with shared data”

    9. “Use a thread-safe data structure”

    10. “Exercise”

    11. “Exercise Solution”

  20. Appendix A

    Final Code Kitchen. All the code for the full client-server chat beat box. Your chance to be a rock star.

    1. “Final BeatBox client program”

    2. “Final BeatBox server program”

  21. Appendix B

    The top ten-ish topics that didn’t make it into the rest of the book. We can’t send you out into the world just yet. We have a few more things for you, but this is the end of the book. And this time we really mean it.

    1. “#11 JShell (Java REPL)”

    2. “#10 Packages”

    3. “#9 Immutability in Strings and Wrappers”

    4. “#8 Access levels and access modifiers (who sees what)”

    5. “#7 Varargs”

    6. “#6 Annotations”

    7. “#5 Lambdas and Maps”

    8. “#4 Parallel Streams”

    9. “#3 Enumerations (also called enumerated types or enums)”

    10. “#2 Local Variable Type Inference (var)”

    11. “#1 Records”

Get Head First Java, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.