• Tidak ada hasil yang ditemukan

A Brain-Friendly guide

N/A
N/A
Sáng Võ

Academic year: 2023

Membagikan "A Brain-Friendly guide"

Copied!
722
0
0

Teks penuh

Amazon named Head First Java a Top Ten Editor's Choice for Computer Books of 2003 (First Edition). A few days ago I received my copy of Head First Java from Kathy Sierra and Bert Bates.

2 A Trip to Objectville

1 Breaking the Surface

3 Know Your Variables

4 How Objects Behave

5 Extra-Strength Methods

6 Using the Java Library

7 Better Living in Objectville

8 Serious Polymorphism

9 Life and Death of an Object

10 Numbers Matter

11 Risky Behavior

12 A Very Graphic Story

13 Work on your Swing

Saving Objects

15 Make a Connection

17 Release Your Code

16 Data Structures

18 Distributed Computing

Intro

If you've done anything with looping, or if/then logic, you'll be fine with this book, but HTML tags alone may not be enough.). Do you believe that a technical book cannot be serious if there is a picture of a duck in the memory management section?

This is NOT a reference book. Head First Java is a

So what does your brain do with all the routine, ordinary, normal things you encounter. Your brain pays attention to things that are unusual, interesting, strange, striking, unexpected.

We think of a “Head First Java” reade r as a learner

The trick is to get your brain to see the new material you're learning as really important. Otherwise, you are in a constant battle where your brain does its best to prevent the new content from sticking.

If you are using Java 6, don’t worry!

If you do not already have a 1.5 or later Java 2 Standard Edition SDK (Software Development Kit), you will need it. If you are on an earlier version of OS X, you have an earlier version of Java that will work for 95% of the code in this book.

What goes in a

No matter how large your program is (in other words, no matter how many classes your program uses), there must be a main() method to get the ball rolling. Variables are declared with a name and a type (you'll learn about all the Java types in Chapter 3).

Syntax Fun

In Java, an if test is basically the same as the Boolean test in a while loop, except that instead of saying, "while there's still beer....", you say, "if there's still beer. ...". We need to force the result to be an integer (decimals are not allowed!) so we've introduced a cast (the details can be found in Chapter 4).

The Java Virtual Machine

The Compiler

Who’s more important?”

Remember that Java is a strongly typed language and this means that you cannot allow variables to hold data of the wrong type. And yes, there are some data type exceptions that can be raised at runtime, but some of them must be allowed to support one of the other important features of Java—dynamic binding.

Each of the Java files on this page represents a complete source file

Your job is to play compiler and determine whether each of these files

BE the compiler

Not all output lines will be used and some of the output lines may be used more than once. Your goal is to make a class that will compile and run and produce the specified output.

CCode Magnets

Exercise Solutions

Now we need to leave this procedural world behind, get rid of main() and start making some objects of our own. We'll take a look at what makes object-oriented (OO) development in Java so much fun.

A Trip to Objectville

When the user clicks on the amoeba, that character rotates. e others and play the .hif f sound. Okay, technically you were first, Larry,” said the manager, “but we just need to add one little thing to the program. It is common for an object to have methods that read or write the values ​​of instance variables.

What’s the difference between a class and an object?

Number to guess is 7 I guess 1 I guess 9 I guess 9 Player one guess 1 Player two guess 9 Player three guess 9. Number to guess is 7 I guess 3 I guess 0 I'm guessing 9 Player one guess 3 Player two guess 0 Player three guess 9.

Java takes out the Garbage

Number to guess is 7 I guess 7 I guess 5 I guess 0 Play one guess 7 Play two guess 5 Play three guess 0 We have a winner. An object can take care of itself; you don't need to know or care about how the object does it.

Your job is to play compiler and determine whether each of

If they won’t compile, how would you fix them,

Your task is to take pieces of code from the pool and place them in the pool. Your goal is to create classes that will compile and run and produce the output listed.

Who am I?

BCode Magnets

Puzzle Solutions

Later, we will use variables as arguments (values ​​sent back to a method by the calling code) and as return types (values ​​returned to the method caller). And we will finally see what life is really like on the garbage mountain.

Know Your Variables

It won't let you do something weird and dangerous like inject a Giraffe reference into a Rabbit variable - what happens when someone tries to ask the so-called Rabbit to hop(). We'll look at primitives first and then move on to what an object reference actually means.

And it won't let you put a floating point number into an integer variable unless you admit to the compiler that you know you might lose precision (like everything after the decimal point). Primitives hold fundamental values ​​(think: simple bit patterns) including integers, booleans, and floating point numbers.

For all this type-safety to work, you must declare the type of your variable.

In this chapter we will first look at the variables (cups) that contain primitives, then a little later we will look at cups that contain references to objects. So it's actually, "I'd like an int please, with the value of 2486, and call the variable height." Each primitive variable has a fixed number of bits (cup size).

Primitive Types

Each cup has a value, so for Java primitives, instead of saying, "I want a tall French fry," you tell the compiler, "I want an int variable with the number 90." Except for one small difference. While you don't need to know what they mean, you still need to know that you can't use them.

Dog d = new Dog();

Or: "The method returns a Dog", or: "I put a new Foo object in the variable called myFoo.". While a primitive variable is full of bits that represent the actual value of the variable, an object reference variable is full of bits that represent a way to get to the object.

Dog myDog = new Dog();

I can talk about one Dog and then five minutes later another Dog. Well, unless you are definitive, you can approach one dog and then the other dog later.

Book b = new Book();

Book c = new Book();

Book d = c;

Anything you put in a variable of that type can be assigned to an array element of that type. Notice one important thing in the image above: the array is an object, even though it is an array of primitives.

Java cares about type

We know we can access Dog instance variables and methods using the dot operator, but so what. Using the dot (.) operator on a reference variable is like pressing a button on the remote control to access a method or instance variable.

Your job is to play compiler and determine whether each of these

Can you reconstruct the code snippets to make a working Java program that produces the results below. Not all reference variables will be used, and some objects may be referenced more than once.

The case of the pilfered references

It's true that he didn't use as many reference variables as Bob, but there was no way to access any but the last of the Contact objects that his method created. We already know that each instance of a class (each object of a specific type) can have its own unique values ​​for its instance variables.

How Objects Behave

And if the Dog class has a makeNoise() method, well, don't you think that a 70-pound dog barks a little deeper than a little 9-pound one. (Assuming that an annoying yip sound can count as barking.) Fortunately, that's the point of the object - it has a behavior that affects its state. When you write a class, you describe how the JVM should create an object of that type.

You already know that each object of that type can have different instance variable values. The play() method plays a song, but the instance on which you call play() will play the song represented by the value of the title instance variable for that instance.

Each instance of a given class has the same methods, but the methods can behave differently based on the value of the instance variables. So if you call the play() method on one instance, you hear the song.

As you would expect from any programming language, you can pass values ​​to your methods.

Whatever you say you’ll give back, you

You can pass variables to a method, as long as the type of the variable matches the type of the parameter. It's the same result you'd get if you added foo + bar at the time you passed them to o.

And remember, you don't stuff objects into variables; the variable is a remote—a reference to an object. So if you pass a reference to an object in a method, you're passing a copy of the remote.

Reminder: Java cares about type!

The value you pass as an argument to the method can be a literal value (2, 'c', etc.) or a variable of a declared parameter type (for example, x, where x is an int variable). There are other things you can pass as arguments, but we're not there yet.). Also, Getters and Setters conform to Java's naming convention, so we'll call them that.

That way, the setter method can validate the parameter and decide whether it is feasible. Maybe the method will reject it and do nothing, or maybe it will throw an exception (for example, if it's a zero social security number for a credit card application), or maybe the method will round the parameter sent to the nearest acceptable value.

Any place where a particular value can

Even though the methods don't really add any new functionality, the nice thing is that you can change your mind later. In other words, what is the value of an instance variable before you initialize it.

Instance variables always get a

But when you don't initialize an instance variable, what happens when you call a getter method.

Local variables do NOT get a default

The == operator can be used to compare two variables of any type and simply compares bits. To check if two references are equal (meaning they refer to the same object on the heap), use the == operator. Remember that the == operator only cares about the bit pattern in the variable.

For example, if two different String objects have the same characters (say, "quick"), they are meaningfully equivalent, regardless of whether they are two different objects on the heap. Do you want to treat two Dogs as equal if they happen to be the same size and weight.

Use == to compare two primitives,

We'll revisit the notion of object equality in later chapters (and Appendix B), but for now, we should understand that the == operator is only used to compare bits in two variables. In that case, we don't know what the bit pattern is (because it depends on the JVM and is hidden from us), but we do know that whatever it looks like, it will be the same for two references to a single object.

Use the equals() method to see

Sometimes you want to know if two reference variables refer to a single object on the heap. So whether two different objects should be treated as equal depends on what makes sense for that particular object type.

What’s legal?

Your job is to play compiler and determine whether each of these files determines whether each of these files. Your challenge is to match the candidate code blocks (below) with the output you would see if the blocks were inserted.

Fast Times in Stim-City

What did Jai suspect?

Will he get out of Leveler’s skimmer with all his bones intact?

Jai suspected that Buchanan was actually handling his methods correctly, not making his instance variables private. And why don't we learn everything by building something real to see what it's like to write (and test) a program from scratch.

Extra-Strength Methods

You're against the computer, but unlike a real Battleship game, you don't build your own ships in this one. In response to your guess, you will see the result in the command line, either “Hit”, “Miss” or “You sunk Pets.

You’re going to build the Sink a Dot Com game, with

Setup: When the game program starts, the computer places three Dot Coms on a virtual 7 x 7 grid. When you send all three Dot Coms to that big 404 in the sky, the game ends by printing your score.

In the real world, of course, you will follow the approach dictated by your personal preferences, the project or the employer. And when we create a Java class as a learning experiences", we usually do it like this:

Our sequence is designed to help you see (and learn) what we're thinking as we work through the coding of the class.

METHOD: String checkYourself(String userGuess) GET userGuess as string parameter CONVERT userGuess to int. REPEAT with each location cell in the int array // COMPARE the user's guess to the location cell IF the user's guess matches.

Extreme Programming (XP)

The concept of writing test code first is one of the practices of Extreme Programming (XP), and it can make it easier (and faster) for you to write your own code. Why not wait until the code is written, and then remove the test code.

Integer.parseInt(“3”)

If you try to analyze something like that. two" or "confuse", the code will explode at runtime. WHILE dot com is still alive (isAlive == true) : GET user input from command line // CHECK user guess.

CREATE a SimpleDotCom object CREATE a random number between 0 and 4 CREATE an int array with the 3 cell locations and INVOKE setLocationCells on the dot com object DECLARE a boolean is Alive. WHILE the dot com is still alive GET user input // CHECK it INVOKE checkYourself() on dot com INCREASE numOfGuesses IF result is "kill".

When you see the logo, you see code that you have to type as is and take faith. We know how much you enjoy typing, but for those rare moments when you'd rather be doing something else, we made this.

It’s a cliff-hanger!

Again, don't worry about other collection types other than arrays - you'll see them in the next chapter. We'll revisit the enhanced for loop in the next chapter when we talk about collections other than arrays.

The Java file on this page represents a complete source

Some of the curling irons fell on the floor and they were too small to pick up, so feel free to add as many as you need. You don't have to reinvent the wheel if you know how to find what you need in the Java library, known as the Java API.

Using the Java Library

A 'true' at a particular index in the array means that the cell location at the same index in the O THER t array (Cells location) has been hit. We can make a second array, and every time the user makes a hit, we store that hit in the second array, and then we check that array every time we get a hit, to see if that cell was hit before.

We have a virtual row of 7 cells and DotCom will occupy three consecutive cells somewhere in that row. DotCom has an instance variable – an array of int – that contains the cell locations of this DotCom object.

Returns the object currently at the index parameter Removes this object (if it is in the ArrayList). Find out if the user's guess is in the ArrayList by asking for i ts index.

3 Classes

Place the DotComs in a grid rather than just one row, and do this for all three DotComs. Since we're not here to dabble in math, we put the DotComs location allocation algorithm in the GameHelper (Ready-bake) class.

5 Objects

DECLARE a startPlaying() method that prompts the player for guesses and calls the checkUserGuess() method until all the DotCom objects are removed from the game. DECLARE a checkUserGuess() method that loops through all remaining DotCom objects and calls each DotCom object's checkYourself() method.

Variable Declarations

DECLARE a finishGame() method that prints a message about the user's performance based on how many guesses it took to sink all the DotCom objects. CALL the placeDotCom() method on the helper object to get a randomly selected location for this DotCom (three cells, aligned vertically or horizontally, on a 7 X 7 grid).

Declarations

DECLARE an int variable that holds the number of guesses made by the user (so we can give the user a score at the end of the game). The DotComBust class has three main tasks: setting up the game, playing the game until the DotComs are dead, and ending the game.

Implementations

You will only use each note once, and you will need all the notes. If the user guess is one of the entries in the ArrayList, indexOf( ) will return its ArrayList location.

Perhaps you can choose cameras ranging from $50 to $1000, but in some cases you want to narrow down the price range more precisely. If you want to get really technical, you might wonder about the precedence of these operators.

Non Short Circuit Operators ( & , | )

We'll be using more powerful boolean expressions in some of the Ready-Bake code you'll see, and although we know you won't be watching, we thought this would be a good time to discuss how to enable them. your expressions. Let's say you're writing a SelectCamera ( ) method, with lots of rules about which camera to select.

In the Java API, classes are grouped into packages

To use a class in the API, you have to know which package

You have to know the full name*

IMPORT

TYPE

In the first and second versions of Java (1.02 and 1.1), all classes shipped with Java (in other words, the standard library) were in packages that started with java. You must tell Java the full name of every class you use, unless that class is in the java.lang package.

In the manual you will find the indexOf() method that we used in the DotCom class. The API docs tell you that the indexOf() method returns -1 if the object parameter is not in an ArrayList.

Better Living in Objectville

And if you can write code that is flexible, for those pesky last-minute spec changes, that would be something you'd be interested in. 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 exploitation of inheritance.

Referensi

Dokumen terkait

Public Class frmRecogKombi Dim Cari As Boolean Dim Tambah As Boolean Dim StrDB As String. Dim ItemList1 As New ArrayList() Dim ItemList2 As New ArrayList()

public class DatabaseOpenHelper extends SQLiteAssetHelper { private static final int DATABASE_VERSION = 1;. private static final String DATABASE_NAME =

Kata Kunci assert* enum** static int double while short instanceof do volatile return import continue void public implements const try protected if class transient private goto

byte double implements private threadsafe byvalue else import protected throw case extends instanceof public throws catch false int return transient car final interface short true

Consider the following code in the Student class: public class Student { private static int lastId; private int id; private String firstName; private String lastName; private char

Gambar 7 public class Grafik3 extends javax.swing.JFrame implements Runnable { private Gambar g ; private String s ; private int rNumber; private Dimension area; private Thread

3.3 JAVA Socket 실습 : ChatHandler.java 1/3 예제: ChatHandler.java public class ChatHandler implements Runnable { private Socket socket; private DataInputStream dataIn; private

import javax.swing.*; import java.awt.event.*; public class SimpleGui1B implements ActionListener { JButton button; public static void mainString[] args { SimpleGui1B = new SimpleGui1B;