• Tidak ada hasil yang ditemukan

INTRODUCTION TO JAVA PROGRAMMING

N/A
N/A
Ali Basher

Academic year: 2023

Membagikan "INTRODUCTION TO JAVA PROGRAMMING"

Copied!
1345
0
0

Teks penuh

The Student Resource Website www.pearsonhighered.com/liang provides access to some of the following resources. The Instructor Resource Website, accessible at www.pearsonhighered.com/liang, provides access to the following resources:.

Algorithm Animations

Acknowledgments

BRIEF CONTENTS

Introduction to Computers, Programs,

CONTENTS

Mathematical Functions, Characters,

Single-Dimensional Arrays 245

Multidimensional Arrays 287

Object-Oriented Thinking 365

Chapter 11 Inheritance and Polymorphism 409

Exception Handling and Text I/O 449

Abstract Classes and Interfaces 495

Event-Driven Programming

JavaFX UI Controls and Multimedia 629

Lists, Stacks, Queues,

Developing Efficient Algorithms 821

Implementing Lists, Stacks, Queues,

Graphs and Applications 1015

Weighted Graphs and Applications 1061

Multithreading and Parallel

Java Database Programming 1173

Advanced Database Programming 35-1 Chapter 36 Internationalization 36-1

2-4 Trees and B-Trees 40-1

A PPENDIXES

VideoNotes

I NTRODUCTION TO C OMPUTERS ,

AND J AVA

CHAPTER

Introduction

The central theme of this book is learning how to solve problems by writing a program. Knowing that there are so many programming languages ​​available, it would be natural for you to wonder which one is the best.

What Is a Computer?

For this reason, experienced programmers try to master as many different programming languages ​​as possible, which gives them access to a wide arsenal of software development tools. If you are already familiar with terms such as CPU, memory, disks, operating systems, and programming languages, you can skip Sections 1.2-1.4.

What Is a Computer? 3

  • Central Processing Unit
  • Bits and Bytes
  • Memory
  • Storage Devices

A program and its data must be moved into the computer's memory before the CPU can execute them. Computer memory (RAM) is a volatile form of data storage: any information that has been stored in memory (i.e. stored) is lost when the system's power is turned off.

What Is a Computer? 5

  • Input and Output Devices
  • Communication Devices

It is used to move a graphical marker (usually in the form of an arrow) called a cursor around the screen or to click objects on the screen (such as a button) to make them perform an action. Dial-up modem uses a telephone line and can transfer data at a rate of up to 56,000 bps (bits per second).

Programming Languages 7 1.8 What unit is used to measure disk size?

Programming Languages

  • Machine Language
  • Assembly Language
  • High-Level Language

C combines the power of an assembly language with the ease of use and portability of a high-level language. They are platform independent, meaning you can write a program in a high-level language and run it in different types of machines.

Operating Systems 9 1.15 What is an interpreter?

Operating Systems

  • Controlling and Monitoring System Activities
  • Allocating and Assigning System Resources
  • Scheduling Operations

The operating system must also ensure that different programs and users working at the same time do not interfere with each other. For example, multiprogramming allows you to use a text editor to edit a file at the same time as your web browser is loading the file.

Java, the World Wide Web, and Beyond

The operating system is responsible for determining what computer resources a program needs (such as CPU time, memory space, disks, input and output devices) and allocating and allocating them to run the program. The operating system is responsible for scheduling the activities of programs to make efficient use of system resources.

The Java Language Specification, API, JDK, and IDE 11

The Java Language Specification, API, JDK, and IDE

Java Micro Edition (Java ME) to develop applications for mobile devices, such as cell phones. For Java SE 8, the Java Development Toolkit is called JDK 1.8 (also known as Java 8 or JDK 8).

A Simple Java Program

The JDK consists of a set of separate programs, each called from a command line, for developing and testing Java programs. Instead of using the JDK, you can use a Java development tool (such as NetBeans, Eclipse, and TextPad)—software that provides an integrated development environment (IDE) for rapidly developing Java programs.

A Simple Java Program 13

You are probably wondering why the main method is defined like this and why System.out.println(..) is used to display a message on the console. For example, you could rewrite the program to display three messages, as shown in Listing 1.2.

Creating, Compiling, and Executing a Java Program 15

Creating, Compiling, and Executing a Java Program

This is one of the main advantages of Java: Java bytecode can run on a variety of hardware platforms and operating systems. Java source code is compiled into Java bytecode, and Java bytecode is interpreted by the JVM.

Creating, Compiling, and Executing a Java Program 17

For instructions on using packages, see Appendix I.F, Using Packages to Organize Classes in Text.

Programming Style and Documentation

  • Appropriate Comments and Comment Styles

Programming Style and Documentation 19

  • Proper Indentation and Spacing
  • Block Styles

Programming Errors

  • Syntax Errors
  • Runtime Errors

Programming Errors 21

  • Logic Errors
  • Common Errors

To avoid this error, type a closing brace each time you open a brace, as shown in the following example. Often, a new programmer forgets to put a quotation mark at the end of a string, as shown in the following example.

Developing Java Programs Using NetBeans 23

Developing Java Programs Using NetBeans

  • Creating a Java Project
  • Creating a Java Class

Type "Welcome" in the "Class Name" field and select "Resource Packages" in the "Location" field. Modify the code in the Welcome class to match Listing 1.1 in the text, as shown in Figure 1.16.

Developing Java Programs Using Eclipse 25

  • Compiling and Running a Class

Developing Java Programs Using Eclipse

  • Creating a Java Project
  • Creating a Java Class

Click Finish to generate the Welcome.java source code template as shown in Figure 1.19.

Developing Java Programs Using Eclipse 27

  • Compiling and Running a Class

C HAPTER S UMMARY

K EY T ERMS

The main method is the entry point where the program is launched when it is executed. Reserved words or keywords have a special meaning for the translator and cannot be used in the program for other purposes.

Q UIZ

In Java, comments are preceded by two slashes (//) on a line, called a line comment, or enclosed between /* and */ on one or more lines, called a block comment or paragraph comment. Programming errors can be categorized into three types: syntax errors, runtime errors, and logic errors.

P ROGRAMMING E XERCISES

To get an exact result with a fraction, one of the values ​​involved in the division must be a number with a decimal point.

E LEMENTARY

P ROGRAMMING

Introduction

Through these problems, you will learn elementary programming using primitive data types, variables, constants, operators, expressions, and input and output.

Writing a Simple Program

Writing a Simple Program 35

The following table shows the value in memory for area and radius while the program is executing. Therefore, the plus sign (+) in lines 13-14 concatenates strings into a longer string, which is then displayed in the output.

Reading Input from the Console 37

Reading Input from the Console

Your program should always tell the user what to enter when it expects input from the keyboard. For now, just accept that this is how you can get input from the keyboard.

Identifiers 39

Identifiers

For example, $2,ComputeArea,area,radius and print are legal identifiers, whereas 2A and d+4 are not because they do not follow the rules. However, we will occasionally use variable names like i,j,k,x and y in the code snippets for brevity.

Variables

Assignment Statements and Assignment Expressions 41

Assignment Statements and Assignment Expressions

Once a variable is declared, you can assign it a value by using an assignment statement. In Java, an assignment statement is essentially an expression that evaluates to the value to be assigned to the variable on the left-hand side of the assignment operator.

Named Constants 43

Named Constants

Naming Conventions

Numeric Data Types and Operations

  • Numeric Types

Numeric Data Types and Operations 45

  • Reading Numbers from the Keyboard
  • Numeric Operators

When both operands of a division are integers, the result of the division is the quotient and the fractional part is truncated. The operand on the left is the dividend and the operand on the right is the divisor.

Numeric Data Types and Operations 47

  • Exponent Operations

Here, a and b are parameters of the pow method, and the numbers 2 and 3 are actual values ​​used to call the method. For now, all you need to know is how to invoke the pow method to perform the exponent operation.

Numeric Literals

How would you rewrite the expression if you wanted the result to be a floating-point number?

Numeric Literals 49

  • Integer Literals
  • Floating-Point Literals
  • Scientific Notation

To improve readability, Java allows you to use underscores between two digits in a literal number.

Evaluating Expressions and Operator Precedence

Evaluating Expressions and Operator Precedence 51

Case Study: Displaying the Current Time

Case Study: Displaying the Current Time 53

Augmented Assignment Operators

Increment and Decrement Operators 55

Increment and Decrement Operators

In this case, i is incremented by 1, then the old value of i is used in the multiplication.

Numeric Type Conversions

Numeric Type Conversions 57

Software Development Process 59

Software Development Process

An independent team of software engineers who are not involved in the design and implementation of the product usually performs such testing. This requires periodic product upgrades to fix newly discovered bugs and incorporate changes.

Requirements Specification

Depending on the type of software, it can be installed on each user's computer or installed on a server accessible on the Internet. To see the software development process in action, we will now create a program that calculates the loan payments.

System Analysis

  • Software Development Process 61

System Design

Implementation

The program also uses the Math class, and you may be wondering why that class is not imported into the program. The Math class is in the java.lang package, and all classes in the java.lang package are implicitly imported.

Testing

  • Case Study: Counting Monetary Units 63 2.32 How would you write the following arithmetic expression?
  • Case Study: Counting Monetary Units
  • Common Errors and Pitfalls 65
  • Common Errors and Pitfalls

The program subtracts the maximum number of singles from the remaining amount and gets a new remaining amount in the remainingAmount variable (lines 16–17). Continuing the same process, the program finds the maximum number of dimes, nickels, and pennies in the balance.

C HAPTER S UMMARY

You can explicitly convert a value from one type to another using the (type)value notation

Write a program that asks the user to enter v in meters/second (m/s) and the accelerations in meters/second squared (m/s2), and displays the minimum runway length. 2.16 (Geometry: area of ​​a hexagon) Write a program that asks the user to enter the side of a hexagon and displays its area.

S ELECTIONS

Introduction

If you enter a negative value for radius in Listing 2.2, ComputeAreaWithConsoleInput.java, the program returns an invalid result. Like all high-level programming languages, Java provides choice statements: statements that let you choose actions with alternative courses.

Two-Way if-else Statements

If the Boolean expression evaluates to true, the statement(s) is executed for the true case; otherwise, the statement(s) for the false case are executed. As usual, the braces can be omitted if there is only one statement inside them.

Nested if and Multi-Way if-else Statements 81

The parentheses surrounding the System.out.println("Negative input") statement can therefore be omitted in the previous example.

Nested if and Multi-Way if-else Statements

If this condition is false, the third condition and the remaining conditions (if necessary) are tested until the condition is met or all conditions are false. Note that a condition is only tested if all the conditions before it are false.

Common Errors and Pitfalls 83

Common Errors and Pitfalls

This error is hard to find because it is neither a compilation error nor a runtime error; this is a logical fallacy. Using the = operator instead of the == operator to compare the equality of two items in a test condition is a common mistake.

Common Errors and Pitfalls 85

Often, new programmers write duplicate code in different cases that should be combined in one place. The new code removes the duplication and makes the code easy to maintain because you only need to change one place if the print statement changes.

Generating Random Numbers 87

Generating Random Numbers

To swap two variables number1 and number2, a temporary variable temp (line 11) is used to first hold the value in number1. The value in number2 is mapped to number1 (line 12) and the value in temp is mapped to number2 (line 13).

Case Study: Computing Body Mass Index 89

Case Study: Computing Body Mass Index

Case Study: Computing Taxes

Case Study: Computing Taxes 91

A compilation error would occur if it had no initial value because all the other statements that assign values ​​to tax are inside the if statement. The compiler believes that these statements may not be able to execute and therefore reports a compilation error.

Logical Operators 93

Logical Operators

Logical Operators 95

If one of the operands of the && operator is false, the expression is false; if one of the operands is || operator true, the expression is true. 3.19 (a) Write a logical expression that evaluates to true if the number stored in the variable num is between 1 and 100. b) Write a logical expression that evaluates to true if the number stored in the variable num is between 1 and 100 or the number is negative.

Case Study: Determining Leap Year 97 3.26 Write a Boolean expression that evaluates to true if weight is greater than

Case Study: Determining Leap Year

Case Study: Lottery

Case Study: Lottery 99

When the value in a case statement matches the value of the switch expression, the statements starting from this case are executed until either a break statement or the end of the switch statement is reached. Once a case is matched, the statements starting from the matching case are executed until a break statement or the end of the switch statement is reached.

-expression must return a value of char,byte,short,int or String type and must always be surrounded by parentheses. The default case, which is optional, can be used to perform actions when none of the specified cases match the switch expression.

Conditional Expressions

As you can see from these examples, conditional expressions enable you to write short and precise code.

Operator Precedence and Associativity

Operator Precedence and Associativity 105

Debugging

When evaluating p1 && p2, Java first evaluates p1 and then evaluates p2 if p1 is true; if p1 is false, does not evaluate p2. When evaluating p1 || p2, Java first evaluates sp1 and then evaluates p2 if p1 is false; if p1 is true, it does not evaluate p2.

T EST Q UESTIONS

Write a program that prompts the user to enter the first 9 digits and displays the 10-digit ISBN (including leading zeros). 3.31 (Financial: foreign exchange) Write a program that prompts the user to enter the exchange rate from currency to U.S.

M ATHEMATICAL

F UNCTIONS , C HARACTERS ,

AND  S TRINGS

Introduction

The focus of this chapter is to introduce mathematical functions, characters, and string objects and their use to develop programs. This chapter provides a brief introduction to string objects; you will learn more about objects and arrays in Chapters 9 and 10.

Common Mathematical Functions

  • Trigonometric Methods

The preceding chapters introduced fundamental programming techniques and taught you how to write simple programs to solve basic problems using selection statements. Because strings are used frequently in programming, it is beneficial to introduce strings early so that you can start using them to develop useful programs.

Common Mathematical Functions 121

  • Exponent Methods
  • The Rounding Methods
  • The min , max , and abs Methods
  • The random Method

Common Mathematical Functions 123

  • Case Study: Computing Angles of a Triangle

The program calculates the distances between two points (lines 17–22) and applies the formula to calculate the angles (lines 25–30). The Math class is used in the program but not imported because it resides in Java.

Character Data Type and Operations 125

Character Data Type and Operations

  • Unicode and ASCII code
  • Escape Sequences for Special Characters

This special notation, called an escape sequence, consists of a backslash (\) followed by a character or combination of numbers. For example, \t is an escape sequence for the Tab character, and an escape sequence like \u03b1 is used to represent a Unicode.

Character Data Type and Operations 127

  • Casting between char and Numeric Types
  • Comparing and Testing Characters

You often have to test in the program whether a character is a number, a letter, an uppercase letter or a lowercase letter. For convenience, Java provides the following methods in the Character class for testing characters, as shown in Table 4.6.

Character Data Type and Operations 129

The String Type

  • Getting String Length

The String Type 131

  • Getting Characters from a String
  • Concatenating Strings
  • Converting Strings
  • Reading a String from the Console

The toLowerCase() method returns a new string with all lowercase letters, and the toUpperCase() method returns a new string with all uppercase letters. Thetrim() method returns a new string by eliminating the whitespace characters from both ends of the string.

The String Type 133

  • Reading a Character from the Console
  • Comparing Strings

Theequals method returns true if two strings are equal and false if they are not. The equalsIgnoreCase and compareToIgnoreCase methods ignore the case of the letters when comparing two strings.

The String Type 135

  • Obtaining Substrings
  • Finding a Character or a Substring in a String

The String class provides several versions of the indexOf and lastIndexOf methods to find a character or a substring in a string, as shown in Table 4.10. You can use the following code to extract the first and last name from the string:.

The String Type 137

  • Conversion between Strings and Numbers

Case Studies 139

Case Studies

  • Case Study: Guessing Birthdays

Case Studies 141

  • Case Study: Converting a Hexadecimal Digit to a Decimal Value
  • Case Study: Revising the Lottery Program Using Strings

If the user entry matches the lottery number in exact order, the prize is $10,000. If one user entry number matches a lottery number, the prize is $1,000.

Formatting Console Output 145

Formatting Console Output

Since the interest amount is currency, it is desirable to display only two decimal places.

Formatting Console Output 147

Write a program that asks the user to enter the side of a hexagon and display its area. Write a program that prompts the user to enter a letter and displays the corresponding number.

L OOPS

  • Introduction
  • The while Loop
  • The while Loop 159
    • Case Study: Guessing Numbers
  • The while Loop 161
    • Loop Design Strategies
  • The while Loop 163
    • Case Study: Multiple Subtraction Quiz
    • Controlling a Loop with a Sentinel Value
  • The while Loop 165
    • Input and Output Redirections
  • The while Loop 167
  • The do-while Loop
  • The do-while Loop 169
  • The for Loop
  • The for Loop 171
  • The for Loop 173
  • Which Loop to Use?
  • Which Loop to Use? 175
  • Can you always convert a while loop into a for loop? Convert the following while loop into a for loop
  • Nested Loops
  • Nested Loops 177

If data is 0, the loop text is no longer executed and the while loop exits. The loop text is executed first and then the loop continuation condition is evaluated.

table title
table title

Gambar

Figure 1.9 shows the  javac  command for compiling Welcome.java. The compiler gener- gener-ates the Welcome.class file, and this file is executed using the  java  command.
Table 3.2 shows the rates for 2009. If you are, say, single with a taxable income of $10,000,  the first $8,350 is taxed at 10% and the other $1,650 is taxed at 15%, so, your total tax is
Table 4.7 lists the  String  methods for obtaining string length, for accessing characters  in the string, for concatenating strings, for converting a string to upper or lowercases, and for  trimming a string.
table title

Referensi

Dokumen terkait

ƒ Method main() akan dipanggil dari luar oleh run‐time Java saat program akan dieksekusi sehingga access specifier yang dimiliki haruslah public.... Sekilas public

ƒ Method main() akan dipanggil dari luar oleh run‐time Java saat program akan dieksekusi sehingga access specifier yang dimiliki haruslah

To help overcome this problem, this chapter provides a brief overview of several Java features, including the general form of a Java program, some basic control structures, and

There was no need to call method join() in the Java programs in Listings 1.1 and 1.2 since threads created in a Java main() method continue to run after the main thread

Before you can try out anything in this book, you need to be able to compile and run your Java code, so I start there, showing several ways: the JDK way, the Integrated

27 Java Tools and Environment 28 Installing the JDK 28 Installing OpenJDK on Linux 29 Installing OpenJDK on macOS 30 Installing OpenJDK on Windows 31 Configuring IntelliJ IDEA and

• Was the “turtle program”, a program in written in C?No • To be able to write programs in C, we need to learn the language.. • That is the goal of this

Perancangan Sistem Informasi Praktek Kerja Industri dengan menggunakan Java Netbeans untuk Program Studi PTIK Universitas Bung Hatta Permasalahan dalam penelitian ini adalah