Log In
Or create an account -> 
Imperial Library
  • Home
  • About
  • News
  • Upload
  • Forum
  • Help
  • Login/SignUp

Index
Head First Java™ Dedication 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?
Who should probably back away from this book?
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
What can you say in the main method?
Looping and looping and...
Simple boolean tests Example of a while loop
Conditional branching Coding a Serious Business Application
Monday morning at Bob’s
Phrase-O-Matic
How it works
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
Larry thought he’d nailed it. He could almost feel the rolled steel of the Aeron beneath his... But wait! There’s been a spec change
Back in Larry’s cube At Brad’s laptop at the beach
Larry snuck in just moments ahead of Brad
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
Things an object knows about itself are called Things an object can do are called
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!
The two uses of main: The Guessing Game
Running the Guessing Game
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
Life on the garbage-collectible heap Life and death on the heap
An array is like a tray of cups Arrays are objects too Make an array of Dogs
What’s missing?
Control your Dog (with a reference variable)
What happens if the Dog is in a Dog array?
A Dog example
4. Methods Use Instance Variables: How Objects Behave
Remember: a class describes what an object knows and what an object does
Can every object of that type have different method behavior?
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
Calling a two-parameter method, and sending it two arguments You can pass variables into a method, as long as the variable type matches the parameter type
Java is pass-by-value. That means pass-by-copy Cool things you can do with parameters and return types Encapsulation
Do it or risk humiliation and ridicule Hide the data
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”
part of a game interaction
First, a high-level design The “Simple Dot Com Game” a gentler introduction Developing a Class
The three things we’ll write for each class: Writing the method implementations
let’s write the real method code now, and get this puppy working
Writing test code for the SimpleDotCom class Based on this prepcode: Here’s what we should test: Test code for the SimpleDotCom class
The checkYourself() method
Just the new stuff
Final code for SimpleDotCom and SimpleDotComTester
Prepcode for the SimpleDotComGame class
Everything happens in main()
The game’s main() method
random() and getUserInput() One last class: GameHelper Let’s play
A complete game interaction
What’s this? A bug?
Gasp! A different game interaction
More about for loops
Regular (non-enhanced) for loops
Trips through a loop
Difference between for and while
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
How it’s supposed to look
A complete game interaction
How the bug looks
A different game interaction
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”
part of a game interaction
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...
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?
Which methods should we override?
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?
Who gets the Porsche, who gets the porcelain?
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.
In other words, you define a common protocol for a set of classes related through inheritance With polymorphism, you can write code that doesn’t have to change when you introduce new subclass types into the program
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
9. Constructors and Garbage Collection: Life and Death of an Object
The Stack and the Heap: where things live Methods are stacked
A stack scenario
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
Be sure you have a no-arg constructor
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
The finished BeatBox looks something like this:
We’ll start with the basics
The JavaSound API
First we need a Sequencer
Something’s wrong! 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?
Catching multiple exceptions
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...
Exception Rules
Making actual sound 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
12. Getting GUI: A Very Graphic Story
It all starts with a window
Put widgets in the 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
How do you get action events for two different buttons, when each button needs to do something different? How do you get action events for two different buttons, when each button needs to do something different?
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
Example: how to use the new static makeEvent() method
Version Two: registering and getting ControllerEvents Version Three: drawing graphics in time with the music
13. Using Swing: Work on Your Swing
Swing components
Components can be nested
Layout Managers How does the layout manager decide?
Different layout managers have different policies
The Big Three layout managers: border, flow, and box Playing with Swing components Making the BeatBox
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
The GameCharacter class
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
Threads can lead to concurrency ‘issues’
The Ryan and Monica problem, in code
The Ryan and Monica example
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!
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 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!
Packages prevent class name conflicts
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
Final BeatBox client program Final BeatBox server program
B. The Top Ten Topics that almost made it into the Real Book...
#10 Bit Manipulation
Why do you care?
#9 Immutability
Why do you care that Strings are Immutable? Why do you care that Wrappers are Immutable?
#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 Index About the Authors Copyright
  • ← Prev
  • Back
  • Next →
  • ← Prev
  • Back
  • Next →

Chief Librarian: Las Zenow <zenow@riseup.net>
Fork the source code from gitlab
.

This is a mirror of the Tor onion service:
http://kx5thpx2olielkihfyo4jgjqfb7zx7wxr3sd4xzt26ochei4m6f7tayd.onion