• Tidak ada hasil yang ditemukan

Buku Head First Java (A Learner’s Guide to Real-World Programming)

N/A
N/A
Motivation

Academic year: 2024

Membagikan "Buku Head First Java (A Learner’s Guide to Real-World Programming)"

Copied!
755
0
0

Teks penuh

Read Head First Java was more like being on the playground than being stuck in the classroom.”. Trisha has been talking (on and off) with Bert for the past eight years about updating Head First Java.

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 Data Structures

12 Lambdas and Streams: What, Not How

13 Risky Behavior

14 A Very Graphic Story

15 Work on Your Swing

16 Saving Objects (and Text)

17 Make a Connection

18 Dealing with Concurrency Issues

935 34 173 iterating

B Appendix B The top ten topics that didn't make it into the rest of the book. We can't send you out into the world yet. We have a few more things for you, but that's the end of the book.

Intro

If you've done anything with loops or if/then logic, you'll do well with this book, but HTML tagging 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 and unexpected.

We think of a Head First Java reader as a learner

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

This book assumes you’re using Java 11 (with the

We strongly recommend that you use nothing but a basic text editor until you finish this book. After downloading and extracting/installing/whatever (depends on which version and for which OS), add an entry to your PATH environment variable pointing to the bin folder inside the main Java directory.

However, if you’re using Java 8, you will find most

An IDE can shield you from some of the details that really matter, so it's much better to learn from the command line and then, once you really understand what's going on, switch to a tool that automates some of the the process. Notepad, Wordpad, TextEdit, etc. all work, as long as you're using plain text (not rich text) and make sure they don't append a “.txt” to the end of your source code (“.java ”) file.

Almost any text editor will do (VI, Emacs), including the GUI ones that come with most operating systems. Note: If you have problems with your installation, we recommend you go to Javaranch.com and join the Java-Beginning Forum.

If there’s discussion of a feature from a version of

You can also access the API docs online without downloading them, but trust us, it's worth the download.

This is your fifth time with us on a Head first book, and we are delighted that you are still talking to us. If you would like to be featured in our next book, and you have a large family, write to us.

Java takes you to new places. From its modest release to the public as the (lame) version 1.02, Java has enticed programmers with its friendly syntax, object-oriented features, memory management, and best of all: the promise of portability. While it's true that Java isn't the fastest language out there, it is considered a very fast language: almost as fast as languages ​​like C and Rust, and much faster than most other languages ​​out there.

Answers on page 6

What goes in a

Running a program means telling the Java Virtual Machine (JVM): “Load the MyFirstApp class and then start executing the main() method. No matter how big your program is (in other words, how many classes your program uses), there needs to be a main() method to get the ball rolling.

The Java Virtual Machine

The Compiler

Who’s more important?”

Look at all the security stuff I do and you're like, what, checking for semicolons. And it looks like we're out of time, so we'll have to discuss this again in a later conversation.

Syntax Fun

You'll get the full scoop later in the book, but not right now. To make that work, you would have to change it to something like: "While Bob snores....".

Answers on page 25

Java has several ways to use only a small part of the Java platform to run on smaller devices (depending on the version of Java you are using). For each of the three lists (strings), the goal is to choose a random word, so we need to know how many words are in each list.

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

Answers on page 26

Not all of the 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 listed output.

CCode Magnets (from page 20)

BE the Compiler (from page 21)

So 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

She could almost feel the coiled steel of Aeron beneath her.. what added to the specs. 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?

One will be the real class - the class whose objects we really want to use, and the other class will be the tester class, which we call . The dot (.) operator gives you access to the state and behavior of an object (instance variables and methods).

Yours to solve

The number to guess is 7 I guess 1 I guess 9 I guess 9 Player one guessed 1 Player two guessed 9 Player three guessed 9. The number to guess is 7 I'm guessing 3 I'm guessing 0 I'm guessing 9 Player one guesses 3 Player two guesses 0 Player three guesses 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,

Answers on page 46

Your job is to take pieces of code from the pool and place them in. Some of the exercises and puzzles in this book may have more than one correct answer.

Who A m I?

Answers on page 47

BCode Magnets (from page 43)

Who Am I? (from page 45)

Puzzle Solutions

Variables can store two types of things : primitives and references

Know Your Variables

It won't let you do something bizarre and dangerous like putting a Giraffe reference into a rabbit variable - what happens when someone tries to tell the so-called rabbit to jump(). And it won't let you put a floating-point number into an integer variable unless you tell the compiler that you know you might lose precision (like anything after the decimal point).

For all this type safety to work, you must specify the type of your variable. Primitives have fundamental values ​​(think: simple bit patterns) including integers, booleans, and floating point numbers.

After all, the value of x is 24, and 24 is certainly small enough to fit in a byte. Don't expect the compiler to know what the value of x is, even if you happen to see it literally in your code.

Answers on page 68

Even if you don't need to know what they mean, you should still know that you can't use them yourself. Don't worry, you'll have most of them out cold by the end of the book.

Dog d = new Dog();

We often think of it this way..we say things like, "I passed the string to the system.out. 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.

With reference variables, the value of the variable..bits that represent the way to get to a particular object. Sure, they might be a pointer to a pointer to... but even if you know, you still can't use the bits for anything other than accessing the object.

Dog myDog = new Dog();

I can refer to a Dog, and then five minutes later I can refer to another Dog. OK, so if you are indecisive then you can refer to one Dog and then refer to another Dog later.

Book b = new Book();

Book c = new Book();

Book d = c;

Be sure to notice one important thing in the image - the array is an object, albeit an array of primitives. In other words, the array object can have elements that are primitives, but the array itself is never a primitive.

Arrays are always objects, whether they’re declared to

Arrays give you fast random access by allowing you to use an index position to get to each element in the array. 2 Create a new Dog array of length 7 and assign it to the previously declared dog[].

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.

Answers on page 69

When "// do stuff" is reached, some objects and some reference variables will be created.

The case of the pilfered references

BCode Magnets (from page 64)

BE the Compiler (from page 63)

It's true that she didn't use as many reference variables as Bob, but she had no way to access any other than the last Contact object that her method created. We already know that each instance of a class (each object of a particular type) can have its own unique values ​​for its instance variables.

How Objects Behave

And if the Dog class has a makeNoise() method, don't you think that a 70-pound dog barks a little deeper than the little 9-pounder. Assuming that annoying yippy sound can be considered a bark.) Fortunately, that's the whole point of an object - it has behaviors that act on 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. When you call the play() method on an instance, it will play the song represented by the value of the title and artist instance variables for that instance.

Each instance of a particular 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'll hear the song "Havana" by Cabello, while another instance plays "Sing" by Travis.

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

Whatever you say you’ll give back, you

First argument l ands in the first parameter, second argument in the second parameter, and so on. You can pass variables into a method, as long as the variable's type matches the parameter's type.

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 to a method, you're passing a copy of the remote.

Reminder: Java cares about type!

You need to use an explicit cast when the declared type is less than the one you're trying to return (we'll see these in Chapter 5). Also, Getters and Setters fit a common Java naming convention, so that's what we'll call them.

Object: OK, you know the dream where you're talking to 500 people when you suddenly realize you're naked. It's right up there with the Pilates machine and..no, we're not going there.

Any place where a particular value can

While the methods don't really add 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 what happens when you call a getter method when you don't initialize an instance variable?

Local variables do NOT get a default

Sometimes you want to know if two primitives are equal; for example, you might want to check an int result with an expected integer value. Sometimes you want to know if two reference variables refer to a single object on the heap; for example, this Dog object is exactly the same Dog object that I started with.

For example, if two different String objects have the same characters (e.g. "my name"), 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 are the same size and weight?

Use == to compare two primitives or to see if

So whether two different objects should be treated as the same depends on what makes sense for a particular type of object. We will explore the notion of object equality again in later chapters, but for now.

Use the equals() method to see if two different

What’s legal?

Answers on page 93

Your task is to play compiler and determine whether each of these files determines or each of these files. If they won't compile, how will you compile, how will you fix it, and if they do compile, what will their output be.

Who Am I?

Your challenge is to match the possible code blocks (below) with the output you would see if the blocks were inserted.

Answers on page 94

Your job is to take pieces of code from the pool and place them in the empty lines of the code. You may not use the same excerpt more than once, and you do not have to use all of the excerpts.

Fast Times in Stim-City

Remember that Java is a 'pass by value' (meaning 'pass by copy') and the 'orig' variable is not changed by the go() method.

What did Jai suspect?

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. We'll build a simple version in this chapter and then build a more powerful deluxe version in Chapter 6, Using the Java Library.

Extra-Strength Methods

Instead, your job is to sink the computer's ships with as few guesses as possible. We kill ill-advised Silicon Valley startups (creating business relevance so you can afford the cost of this book).

Setup: When the game program is started, the computer places three Startups on a virtual 7 x 7 grid. When you've sent all three Startups to that big 404 in the sky, the game ends with you printing your rating.

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

In this chapter we build the simple version, followed by the luxury version that we build in the next chapter. This simplified version of the game gives us a big head start on building the full game.

Our sequence is designed to help you see (and learn) what we're thinking as we work through coding a class. In the real world, of course, you will follow the approach dictated by your personal preferences, project or employer.

The concept of writing the test code first is one of the practices of Test-Driven Development (TDD), and it can make it easier (and faster) for you to write your code. One of the central ideas in XP was to write test code before the actual code was written.

Test-Driven Development (TDD)

We need to write test code that can create a SimpleStartup object and run its methods. Why not wait until the code is written and then dig into the test code.

Each time you go through the loop, that variable (in this case an int variable named ..cell”) will contain another element from the array until there are no more elements (or the code does a “break”. see #4 below).

Based on the code on the opposite page and the specification for the actual game, enter your ideas for the preparatory code for the game class. For example, we have one line of prep code that says "GET user input from command line." Let me tell you, this is a bit more than we want to roll out from scratch right now.

Oh, if you're wondering why we skipped the test code phase for this class, we don't need a test class for the game. WHILE Startup is still alive GET user input // CHECK it INVOKE checkYourself() on Startup INCREASE numOfGuesses IF result is "kill".

This is just a quick look to get you going; more details on the GameHelper class are at the end of this chapter. We know how much you love to write, but for those rare moments when you'd rather be doing something else, we've made Standby Code available at https://oreil.ly/hfJava_3e_examples.

It’s a cliff-hanger!

Again, don't worry about the other non-array types of collections - you'll see them in the next chapter. That's really all the enhanced gives you - a simpler way to step through all the elements in the collection.

The Java file on this page represents a complete source

Answers on page 122

Some of the curly braces fell to the floor and were too small to grab, so feel free to add as many as you need.

Answers on page 123

Your challenge is to match the candidate code block (on the left) with the output you would see if the block was entered.

Be the JVM (from page 118) Code Magnets (from page 119)

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. The Java Ready-Bake we use in this book is code that doesn't need to be created from scratch, but you still need to type it.

Using the Java Library

"True" at a given index in an array means that the cell location at the same index in ANOTHER array (locationCells) was hit. We could make another array and every time the user hits we store that hit in another array and then check that array every time we get a hit to see if that cell has been hit before.

We have a virtual row of seven cells, and a Startup will occupy three consecutive cells somewhere in that row. The Startup has an instance variable—an int array—that holds that Startup object's cell locations.

The long answer is at the end of this chapter where you learn how to do it. And if you're using Java 5 or later, this wrapping (and unpacking when you take the primitive out again) happens automatically.

Solution

We've been working on the "simple" version, but now let's build it real. You will build the Sink a Startup game, with the Sink a Startup game, with a 7 x 7 grid and three Startups.

3 Classes

Place the startups on a grid and not just in one row, and do this for all three startups. Since we're not here to do the math, we've put the startup location allocation algorithm in the GameHelper (Ready-Bake Code) class.

5 Objects

The StartupBust object gives each of the Startup objects a location (which StartupBust got from the helper object) as. DECLARE a startPlaying() method that prompts the player for guesses and calls the checkUserGuess() method until all the Startup objects are removed from the game.

Variable Declarations

DECLARE a checkUserGuess() method that loops through all remaining Startup objects and calls each Startup object's checkYourself() method. DECLARE a finishGame() method that prints a message about the user's performance based on how many guesses it took to sink all the startup objects.

Implementations

Ask the startup to check the user's guess, looking for a hit (or kill). Get out of the loop early, no point. If the user's guess is one of the entries in the ArrayList, indexOf( ) will return its ArrayList location.

Not equals ( != and ! )

You may be able to choose cameras in the $50 to $1000 range, but in some cases you want to narrow down the price range more precisely. If you want to get really technical, you can ask about the advantage of these carriers.

Non-Short-Circuit Operators ( & , | )

We'll be using more powerful boolean expressions in some of the Ready-Bake code you'll see, and while we know you won't be peeping, we thought this would be a good time to discuss how to make your expressions stronger. You will be able to "cheat" these print statements by giving you the location of the startups, but they will help you in testing.

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* of the class you want to use in your code

IMPORT

TYPE

Third, packages provide a level of security because you can restrict the code you write so that only other classes in the same package can access it. But if you look at the code in the repo (https://oreil.ly/hfJava_3e_examples) you will see it.

Browsing through a reference book is a good way to find out what's in the Java library. The API docs are the best reference for getting more details about what's in a package, and what the classes and interfaces in the package provide (eg in terms of methods and functionality).

The docs look different depending upon the version of Java you’re using Make sure you're looking at the docs for your version of Java!

The documents look different depending on the version of Java you are using. Make sure you look at the docs for your version of Java. All the classes we've covered in this book so far are in the java.base module; this contains core Java packages such as java.lang and java.util.

To understand the docs, you need to know that the JDK is now split into modules. This will make it easier for you to find the classes you are interested in because they are sorted by function.

Referensi

Dokumen terkait