• Tidak ada hasil yang ditemukan

Buku Java For Dummies, 8th Edition

N/A
N/A
Motivation

Academic year: 2024

Membagikan "Buku Java For Dummies, 8th Edition"

Copied!
515
0
0

Teks penuh

NO WARRANTY MAY BE MADE OR EXTENDED FOR THIS WORK BY SALES REPRESENTATIVES, WRITTEN SALES MATERIALS OR PROMOTIONAL STATEMENTS. THIS WORK IS SOLD WITH THE CONSIDERATION THAT THE PUBLISHER IS NOT INVOLVED IN PROVIDING PROFESSIONAL SERVICES.

Introduction

About This Book

I provide exercises for each chapter, along with solutions to the exercises on the book's website. Finally, and most importantly – and undoubtedly the most important of all the features of this book – I'll throw in some jokes.

Foolish Assumptions

On the other hand, if you've done these things (perhaps in Visual Basic, Python, or C++), you'll discover some interesting plot twists in Java. As you learn about these features, many of them will seem quite natural to you.

Icons Used in This Book

When you start putting the concepts into practice for the first time, you'll discover all kinds of issues, problems, and obstacles that didn't occur to you when you first started reading about the material. You may also find it useful if you plan to read other (nicer) books about Java.

Beyond the Book

Or, if you get frustrated, visit this book's website (http://.javafordummies.allmycode.com) for tips and solutions. This fact can help you understand what the people behind the scenes (the people who developed Java) were thinking.

Where to Go from Here

1 Getting Started with Java

Chapter  1

All about Java

Without the overhead, you can do things much faster and do things that are much more complex than ever.

What You Can Do with Java

To tell a computer what to do, you have to use a special language to write short, unambiguous instructions.

Why You Should Use Java

Companies do it, freelancers do it, hobbyists do it - all kinds of people do it. Take almost anything that can be done with a computer - with the right amount of time you can write your own program to do it.

Gaining Perspective: Where Java Fits In

2004: Java is the top language on the world-famous TIOBE Index and will remain at the top for the next 15 years. Java is one of the most popular programming languages ​​in use today, so it's no surprise that it's ranked no.

Object-Oriented Programming (OOP)

Object-oriented languages

THE WINDING ROAD FROM FORTRAN TO JAVA

The C++ language became popular because it mixed the old C language terminology with the improved object-oriented structure. Using C++, you can bypass all the object-oriented features and write a program using the old FORTRAN/C programming style.

Objects and their classes

What’s so great about an object-oriented language?

The original house class is called the super class of the three and four bedroom house classes. The three and four bedroom house classes are child classes of the original house class.

Objects and classes are everywhere

Think of the table's column headers as a class and think of each row of the table as an object. According to the table's column headings, each account has an account number, a type, and a balance.

What’s Next?

Chapter  2

All about Software

Get Ready for Java

Install a Java Development Kit (JDK)

The problem with the official Oracle version is that it comes with a long, somewhat confusing list of legal requirements. It's probably OK to run the examples in this book with Oracle's JDK, but I'm no lawyer and I've never played one on TV.

Install an integrated development environment

The https://adoptium.net site has several JDKs, written by several different companies, and almost any of these kits will work with this book's examples. If you don't like the adoptium.net alternatives and you prefer to get the "official" JDK instead, you can download it from www.oracle.com/java/technologies/downloads.

Test your installed software

Visit this book's website (http://JavaForDummies. allmycode.com) to download all the code examples and copy them into the IDE of your choice. When you follow my instructions, you might end up with two copies of the JVM or two IDEs, but that's okay.

The Inside Scoop

A JDK contains at least thirty different programs — many more, if you count compressed archives and the like. A compiler is a program that takes your Java code and converts that code into a series of instructions called bytecode.

What is a compiler?

If so, the compiler probably puts the Java bytecode in another file named Hotel.class. No one (except a few crazy programmers in some isolated labs in far off places) writes Java bytecode.

What is a Java virtual machine?

A JVM running on a Pentium running Linux translates the Java bytecode instructions into the type of code you see in Listing 2-3. And a JVM running on a PowerPC running Linux translates the Java bytecode instructions into the type of code you see in Listing 2-4.

Developing Software

On that note, don't ever get discouraged when the 25th draft of your code doesn't work. They say "You build the code" and "You run the code." But the "you" is not always accurate and the "code" varies slightly from one part of the cycle to another.

Spoiler Alert!

Chapter  3

Using the Basic Building Blocks

Speaking the Java Language

The first category (grammar) includes rules like this: "The verb agrees with the noun in number and person." The second category (expressions, sayings, and other things) includes knowledge like this: "Julius Caesar was a famous Roman emperor, so don't call your son Julius Caesar unless you want him to be beaten every day after school."

The grammar and the common names

If you rarely write programs that open windows, you can look up the JFrame class in the API documentation the first few times you need to create a window. The folks at JCP don't keep the Java programs in the official Java API secret.

The words in a Java program

Unlike the names you create, the names in the API are distributed with each version of Java. Strictly speaking, the meanings of the identifiers in the Java API are not set in stone.

Checking Out Java Code for the First Time

But even worse, when your code assigns a new meaning to an identifier like a JButton, you lose any computational power that was created for the identifier in the API code. To see the list of Java keywords, go to www.dummies.com and type Beginning Programming with Java For Dummies Cheat Sheet in the search field.

Understanding a Simple Java Program

To download all the code in this book, visit the book's website (http://JavaFor Dummies.allmycode.com). This book's website (http://JavaForDummies.allmycode.com) contains instructions to help you run Java programs such as the code in Listing 3-1.

The Java class

You don't have to type the code into Listing 3-1 (or into any of the listings in this book). For example, the class name in Listing 3-1 is Displayer, starting with a capital D.

The Java method

The instruction to invoke the fixTheAlternator method might look like the line in Listing 3-3. The term method declaration distinguishes the list of instructions in Listing 3-2 from the instruction in Listing 3-3, which is known as a method call.

The main method in a program

A method call (a separate piece of code) tells the computer to actually call the method on the action. The keyword is the name of the method that is automatically invoked when the program starts running.

In other words, calling the System.out.println method is the only item on the main method's task list. The declaration for the System.out.println method is hidden in the official Java API.

Figure 3-5 illustrates the  System.out.println  situation. Actually, two methods  play active roles in the running of the  Displayer  program
Figure 3-5 illustrates the System.out.println situation. Actually, two methods play active roles in the running of the Displayer program

Brace yourself

Therefore, this System.out.println line goes inside all the other curly braces and is indented more than any other line. If you put curly braces in the wrong places or leave curly braces where the brace should be, your program will probably not work at all.

BEGIN THE BEGUINE

CAPITAL PAINS

STOLEN SEMICOLON

MISCELLANEOUS MISCHIEF

And Now, a Few Comments

Adding comments to your code

Because other people do not view the Java code, other people do not make changes to the Java code. Because other people don't see Java code, other people don't have to decipher the inner workings of Java code.

What’s Barry’s excuse?

Best of all, the Java Web API Specification, which describes all of Java's standard identifiers, comes entirely from javadoc program executions in comments in the Java code. You can generate your own web pages from the javadoc comments you put in your code.

Using comments to experiment with your code

The big problem is that you can't nest a traditional comment inside another. Because of this, I recommend recent comments as tools for experimenting with your code.

2 Writing Your Own Java

Programs

Chapter  4

Making the Most of Variables and

Varying a Variable

You can read more about types in the section "Types of values ​​that variables can have" later in this chapter. Each variable name is an identifier—a name that you can make up in your own code.

Assignment statements

The types of values that variables may have

In Listing 4-2, if I hadn't declared amount on account to be of type double, I might not have been able to save 50.22. Instead, I would have had to store plain old 50, with no digits beyond the decimal point.

TO THE DECIMAL POINT AND BEYOND!

How to hold the line

NUMBER FORMAT EXPERIMENTS

HOW TO DISPLAY VALUES

Numbers without decimal points

A certain branch of the Brickenchicker family is blessed with identical twins (ten siblings, all with the same physical characteristics). Shortly after lunch, all ten of Brickenchicker arrive at the elevator at exactly the same time.

TAKE A FLYING LEAP

Combining declarations and initializing variables

FOUR WAYS TO STORE WHOLE NUMBERS

When JShell shows you a command, you can press the left and right arrow keys to move to any character in the middle of the command. With JShell, you can test your statements before putting them into a full Java program.

SHELL GAME

If you press the up arrow key once, JShell shows you the command you recently typed. If you press the up arrow key twice, JShell shows you the next command to the last one you typed.

What Happened to All the Cool Visual Effects?

As visually unexciting as text-based programs are, they contain the basic concepts for all computer programming. The DummiesFrame class: In addition to the text-based examples, I present GUI versions using the DummiesFrame class, which I created specifically for this book.

The Atoms: Java’s Primitive Types

Text-based programs are also easier for beginners to read, write and understand than the corresponding GUI programs.

The char type

An exciting run of the Listing 4-4 ​​program as it appears in IntelliJ's Run tool window. The Character.toUpperCase method does exactly what its name suggests—the method produces the uppercase equivalent of the letter b.

TABLE 4-1  Java’s Primitive Types
TABLE 4-1 Java’s Primitive Types

The boolean type

But, as you know from the strawberry shortcake at the Brickenchicker family's catered lunch, the value of numberOfPeople is not greater than or equal to ten. Thus, in the statement in Listing 4-5, in which a value is assigned to allTenOkay, a false value is assigned to the allTenOkay variable.

The Molecules and Compounds

So with the variable myTitle declared to be of type String, setting "Blank Frame". for the variable myTitle has the meaning in Listing 4-6. The String class is declared in the Java API. By declaring the variable myFrame to be of type JFrame, you are reserving the use of the name myFrame.

RUN IT TWICE

SHUFFLE PLAY

An Import Declaration

PRIMITIVE-TYPE STEW

After declaring your intentions in the import statement, you can use the shortened name JFrame in your Java class code. If you do not use an import statement, you must repeat the full javax.swing.

Creating New Values by Applying Operators

Now you are ready for the next step, which is to take as many cents as you can. The MakeChange class gives you the smallest number of coins that are up to 248 cents.

SMOOTH OPERATORS

With these denominations, the MakeChange class gives you more than just a set of coins that add up to 248 cents. But for some types of coins, you won't always get the smallest number of coins that add up to a total.

Initialize once, assign often

The code in Listing 4-7 changes to US currency in the following denominations: 1 cent, 5 cents (a nickel), 10 cents (a dime), and 25 cents (a quarter).

IMPORT DECLARATIONS: THE UGLY TRUTH

The increment and decrement operators

The computer adds 1 to the variable's value after the variable is used in any other part of the statement. With postdecrement(numberOfBunnies--), the computer subtracts 1 from the variable's value after the variable is used in the rest of the statement.

Figure 4-16 shows a run of the code in Figure 4-15. Compare Figure 4-16 with the  run in Figure 4-14:
Figure 4-16 shows a run of the code in Figure 4-15. Compare Figure 4-16 with the run in Figure 4-14:

STATEMENTS AND EXPRESSIONS

With predecrement (--numberOfBunnies), the computer subtracts 1 from the value of the variable before the variable is used in the rest of the statement. Additionally, when you type the number of levers only once, you only have one chance (instead of two) of mistyping the variable name.

PROGNOSTICATION GAME

The best reason to use ++ is to avoid the inefficient and error-prone practice of typing the same variable name, such as number number, twice in the same statement. If you type numberOfBunnies only once (as you do when you use ++ or ––), the computer only needs to understand what numberOfBunnies means once.

SEE PLUS PLUS

Assignment operators

You can even use another expression's value (in Listing 4-8, numberExtra) as the number to apply. See, the last line in Listing 4-8 shows how you can do the same thing with Java's plain old equals sign.

THE OPERATION IS A SUCCESS

Chapter  5

Controlling Program Flow with Decision-

Making Decisions (Java if Statements)

Guess the number

The program receives a number (a guess) from the user and then generates a random number between 1 and 10. Otherwise, the user loses and the program tells the user what the random number was.

She controlled keystrokes from the keyboard

In Listing 5-1, your code connects to the keyboard by calling the new Scanner (System.in). The Java virtual machine code (which you should never see) contains a call to new PrintStream() in preparation for your System.out.println call.

Creating randomness

The out variable refers to a PrintStream, but you don't call new PrintStream() to prepare for calling System.out.println.) Instead, the Java virtual machine connects to the screen on your behalf. So, because it's a well-behaved piece of code, the Java Virtual Machine ends up calling out.close() without any effort on your part.

The if statement

If the condition is true, the computer does things differently between the condition and the word. If the condition turns out to be false, the computer does the stuff after the word differently.

Equal, equal

I call them the if part (top half) and the else part (bottom half). I do this by enclosing the three if statements in a pair of curly braces.

Your intent to indent

With this block, three calls to println are safely stored inside the if part. Worse, the indentation misleads you into thinking that the second part includes all three statements.

Elseless in Helsinki

In your favorite IDE, look for menus such as Source ➪ Format or Code ➪ Reformat Code. If you indent three statements after the word else and forget to enclose those statements in curly brackets, the computer will think that the else section contains only the first of the three statements.

STRAIGHT TALK

Use what you know about Java's if statements to make the program's output more natural.

Using Blocks in JShell

When you write a statement that is not inside a block, JShell lets you omit the semicolon at the end of the statement. When you write a statement that's inside a block, JShell (like plain old Java in Listing 5-2) doesn't let you omit the semicolon.

Comparing numbers; comparing characters

Oddly enough, when you compare uppercase and lowercase letters, the uppercase letter is always smaller. When you do some calculations and get two double values ​​or two float values, the values ​​you have are rarely exactly the same.

Comparing objects

Instead, you usually want to ask, "Does this string have the same characters as that other string?" To ask the second question (the more appropriate question): Java's String type has a method called equals. Like everything else in the known universe, this equals method is defined in the Java API, short for application programming interface.) The equals method compares two strings to see if they contain the same characters. When calling Java's equals method, it doesn't matter which string gets the period and which gets the parentheses.

Look!

The idea is that you have two objects: a password object and a "swordbox" object. When you call this method, you add "sword" to it as a method parameter (pun intended).

On the var side

When one line isn’t enough

Importing everything in one fell swoop

Java’s logical operators

In Listing 5-4, JOptionPane.showInputDialog works fine because the user input (username and password) are just character strings. For example, to get an int value from the user, type something like int numberOfCows = Integer.parseInt(JOptionPane.showInputDialog("How many cows?")).

Vive les nuls!

In Listing 5-4, the purpose of the comparison username != null is to prevent Java from checking username.equals("bburd") whenever Cancel is clicked. In the code JOptionPane.showMessageDialog(null, "You are in.") the word null means "no other dialog".

Conditions in parentheses)

For some reason Java doesn't insist that you specify the origin of the showInputDialog box. I'll check things after the || operator to find out if it is true. (Java often talks to himself. The psychiatrists are monitoring this situation.).

THE RULE OF THREE

OUT, DAMN’D NOT!

EQUAL BYTES

The Nesting Habits of if Statements

If you pass the first test (the username test), you immediately jump to another if statement that performs a second test (the password test). The code in Listing 5-5 does a good job with nested statements, but it does a terrible job with real-world user authentication.

Figure 5-6 shows several runs of the code in Listing 5-5. The main idea is that to  log on, you have to pass two tests
Figure 5-6 shows several runs of the code in Listing 5-5. The main idea is that to log on, you have to pass two tests

I CHANGED MY MIND

Choosing among Many Alternatives

Java’s glorious switch statement

AL’S ALL WET”

The value 2 does not match the top letter, so the computer continues to the middle of the three letters. When the computer is outside the switch sentence, the computer displays Oh, oh, oh, oh.

A switch in time saves 14

Looking at Listing 5-6 again, you wonder why someone enjoyed typing the words out.println so much. Why not have just one call to out.println for all the different responses the program might display.

Your grandparents’ switch statement

(Refer to Figure 5-8.) The big difference is that Listing 5-8 uses the old form of the switch statement. Execution continues until you eventually reach a break statement or the end of the entire switch statement.

Free fall

In effect, Java jumps out of the entire switch statement and goes directly to the statement just after the end of the switch statement. The switch statement in Listing 5-9 has no capital "six" and no default, so none of the actions in the switch statement are performed.

LEAPING TO CONCLUSIONS

HOW ABOUT A DATE?

THE YIELD APP

Chapter  6

Controlling Program Flow with Loops

Repeating Instructions Over and Over Again (Java while Statements)

With code like the one shown in Listing 6-1, the computer never jumps out in the middle loop. The computer does the test again (to see if the inputNumber is still not equal to the randomNumber) only after it has fully executed all five statements in the loop.

BIGGER AND BETTER

NO NEGATIVITY

Count On Me

Finally, the for statement does the last thing inside its parentheses - it adds 1 to the value of count. Finally, the for statement does the last thing inside its parentheses - it adds 1 to the value of count, increasing the value of count to 3.

Figure 6-3 shows you what you get when you run the program from Listing 6-2.
Figure 6-3 shows you what you get when you run the program from Listing 6-2.

The anatomy of a for statement

Now that the number is equal to 2, the for statement checks again to make sure the number is less than or equal to 10. Yes, 2 is less than 10.) Since the test turns out fine, the for marches -instruction back in the curly- statements and prints with braces. The value of count is 2 on the screen. The initialization is performed once, when your program's execution first reaches the for statement.

The world premiere of “Al’s All Wet”

For example, in Listing 6-2, you see an error message if you try to put out.println(count) after the end of the loop. But really, you can do just about any kind of iteration with a for statement.

COLLECTING VALUES

The for ( ; ; ) loop runs forever, which is fine if the loop controls a serious chunk of machinery.

FACTORIAL

SEEING STARS

After you make your prediction, run the code to see if your prediction is correct.

SEEING MORE AND MORE STARS

THREE TRIANGLES

You Can Always Get What You Want

Before deleting the file, the program asks the user if the deletion is okay. But if the user enters another character (a number, capital letter, punctuation mark or whatever), the program will ask the user for a different answer.

Figure 6-5 shows some runs of a program to delete a file. Before deleting the file,  the program asks the user whether making the deletion is okay
Figure 6-5 shows some runs of a program to delete a file. Before deleting the file, the program asks the user whether making the deletion is okay

The root of the matter

With a do loop, the situation in program twoPlusTwo (shown at the beginning of this section) can never happen. When you run the code, Java tells you where on your hard drive the cooked-Books.txt file should be.

Reading a single character

File handling in Java

Block on the while side

MISSED OPPORTUNITY

LET’S BUST OUT OF HERE

Fortunately, when you execute a break statement, Java jumps to the code immediately after the loop.

CARRY ON AND KEEP CODING

3 Working with

Object-Oriented Programming

Chapter  7

The Inside scOOP

Execution of any Java program must begin with the main method, so the code in Listing 7-1 has no starting point. In this chapter, Listing 7-2 has a convenient main method so that the Account class in Listing 7-1 is not lost.

PACKAGE DEAL

To use the listing account class, your project must contain at least two Java files: one file with the code in Listing 7-1 and another file with a main method. Before you copy the code from Listing 7-1 into your IDE, you probably need to ask the IDE to create a package named com.example.accounts.

Declaring variables and creating objects

Instead, the line Account yourAccount means, "If and when I make the variable yourAccount refer to something, that something will be an instance of the Account class." So what is the difference. All the statement does is reserve the variable name yourAccount so that the name will eventually refer to an instance of the Account class.

Initializing a variable

Before you do new Account(), you cannot print the object name variable because the object does not exist. Concatenating lines this way automatically avoids the variable may not have been initialized error I described in the previous section.

Using an object’s fields

One program; several classes

Declaring a public class

You might say to yourself, "The Account class must be public because another class (the code in Listing 7-2) uses the Account class." When you declare a class public, you must declare it in a file whose name is exactly the same as the class name (but with the .java suffix added).

GETTING ORGANIZED

In fact, when the planets align themselves correctly, one class can make use of another class's code, even though the other class is not public. For example, if you declare public class MyImportantCode, you must place the class's code in a file named MyImportantCode.java, with uppercase letters M, I, and C and all other letters lowercase.

YUMMY FOODS

Companies that manufacture and sell products are generally for-profit organizations; Disaster relief groups are generally not for-profit organizations.

Defining a Method within a Class (Displaying an Account)

With object-oriented programming, all the functionality associated with an account is collected within the code for the account class. Therefore, if someone has problems with your account class or your year class, they know just where to look for all the codes.

An account that displays itself

In Listing 7-3, the Account class has four things: name, address, status, and display method. Thus, each instance of the Account class has a name, address, state, and display method.

The display method’s header

SHOW OFF

Sending Values to and from Methods (Calculating Interest)

The first call, myAccount.getInterest(5.00), references the myAccount object and the values ​​stored in the myAccount object's fields. In the main method, just before this second call is made, the variable yourInterestRate is assigned the value 7.00.

Passing a value to a method

Fortunately for me, I declared yourInterestRate to be of type double just a few lines before. The action goes from main to getInterest, then back to main, then back to getInterest, and finally back to main again.

Returning a value from the getInterest method

The UseAccount class in Listing 7-6 is a test case—a short-lived class whose sole purpose is to test another class's code. Like the code in Listing 7-6, every test case in this book is a regular class—a free-form class that contains its own main method.

TAX DAY

COST OF CONSUMPTION

Giving Your Numbers a Makeover

You can round the numbers and display only two digits beyond the decimal point, and some handy tools from Java's API (application programming interface) can help. Java's API has a class called BigDecimal - a class that bypasses the computer's weird 0s and 1s and uses regular decimal digits to perform arithmetic calculations.

FILL IN THE BLANKS

For some better ways to handle currency amounts (such as the interest amounts in this section's example), see Chapter 11. To do this, look for clues in the java.util.Formatter page of Java's API documentation at https : //docs.oracle.com/en/java/javase/17/docs/api/java.

Hide-and-Seek

Good programming

Gambar

TABLE 1-1  A Table of Accounts
Figure 2-2 illustrates the cycle.
Figure 3-5 illustrates the  System.out.println  situation. Actually, two methods  play active roles in the running of the  Displayer  program
Figure 4-1 gives a before-and-after picture of the code in Listing 4-1. After the  first statement in Listing 4-1 is executed, the variable  amountInAccount  has the  number 50.22 in it
+7

Referensi

Dokumen terkait