Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Intro_Java_brief_Liang2011.pdf
Скачиваний:
195
Добавлен:
26.03.2016
Размер:
10.44 Mб
Скачать

16 Chapter 1

Introduction to Computers, Programs, and Java

 

Pedagogical Note

 

Instructors may require students to use packages for organizing programs. For example, you may

 

place all programs in this chapter in a package named chapter1. For instructions on how to use

using package

packages, please see Supplement I.F, “Using Packages to Organize the Classes in the Text.”

 

1.9 (GUI) Displaying Text in a Message Dialog Box

 

The program in Listing 1.1 displays the text on the console, as shown in Figure 1.12. You can

 

rewrite the program to display the text in a message dialog box. To do so, you need to use the

JOptionPane

showMessageDialog method in the JOptionPane class. JOptionPane is one of the many

 

predefined classes in the Java system that you can reuse rather than “reinventing the wheel.”

showMessageDialog

You can use the showMessageDialog method to display any text in a message dialog box,

 

as shown in Figure 1.13. The new program is given in Listing 1.4.

 

 

 

Title

 

Title bar

 

 

 

 

 

Message

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Click the OK button to

 

 

 

 

 

 

 

 

 

 

 

 

 

 

dismiss the dialog box

FIGURE 1.13 “Welcome to Java!” is displayed in a message box.

LISTING 1.4 WelcomeInMessageDialogBox.java

block comment

1

/*

 

This application program displays Welcome to Java!

 

2

*

 

in

a message dialog box.

 

3

*/

 

 

 

import

4

import

javax.swing.JOptionPane;

 

 

5

 

 

 

 

 

 

6

public

class WelcomeInMessageDialogBox {

main method

7

 

public static void main(String[] args) {

 

8

 

//

Display Welcome to Java! in a message dialog box

display message

9

 

 

JOptionPane.showMessageDialog(null, "Welcome to Java!");

 

10

 

}

 

 

 

 

11

}

 

 

 

 

This program uses a Java class JOptionPane (line 9). Java’s predefined classes are grouped package into packages. JOptionPane is in the javax.swing package. JOptionPane is imported to the program using the import statement in line 4 so that the compiler can locate the class

without the full name javax.swing.JOptionPane.

Note

If you replace JOptionPane on line 9 with javax.swing.JOptionPane, you don’t need to import it in line 4. javax.swing.JOptionPane is the full name for the JOptionPane class.

The showMessageDialog method is a static method. Such a method should be invoked by using the class name followed by a dot operator (.) and the method name with arguments. Methods will be introduced in Chapter 5, “Methods.” The showMessageDialog method can be invoked with two arguments, as shown below.

JOptionPane.showMessageDialog(null, "Welcome to Java!");

The first argument can always be null. null is a Java keyword that will be fully introduced in Chapter 8, “Objects and Classes.” The second argument is a string for text to be displayed.

There are several ways to use the showMessageDialog method. For the time being, you need to know only two ways. One is to use a statement, as shown in the example:

JOptionPane.showMessageDialog(null, x);

where x is a string for the text to be displayed. The other is to use a statement like this one:

JOptionPane.showMessageDialog(null, x, y, JOptionPane.INFORMATION_MESSAGE);

where x is a string for the text to be displayed, and y is a string for the title of the message box. The fourth argument can be JOptionPane.INFORMATION_MESSAGE, which causes the icon ( ) to be displayed in the message box, as shown in the following example.

Key Terms 17

two versions of showMessageDialog

JOptionPane.showMessageDialog(null, "Welcome to Java!",

"Display Message", JOptionPane.INFORMATION_MESSAGE);

Note

There are two types of import statements: specific import and wildcard import. The specific

specific import

import specifies a single class in the import statement. For example, the following statement

 

imports JOptionPane from package javax.swing.

 

import javax.swing.JOptionPane;

 

The wildcard import imports all the classes in a package. For example, the following statement

wildcard import

imports all classes from package javax.swing.

 

import javax.swing.*;

 

The information for the classes in an imported package is not read in at compile time or runtime

 

unless the class is used in the program. The import statement simply tells the compiler where to

 

locate the classes. There is no performance difference between a specific import and a wildcard

no performance difference

import declaration.

 

Note

Recall that you have used the System class in the statement System.out.println(”Welcome

 

to Java”); in Listing 1.1. The System class is not imported because it is in the java.lang

java.lang

package. All the classes in the java.lang package are implicitly imported in every Java program.

implicitly imported

KEY TERMS

.class file

14

byte 3

 

 

.java file

14

bytecode

14

 

assembly language 5

bytecode verifier 15

bit

3

 

cable modem

5

block 12

 

central processing unit (CPU) 2

block comment 11

class loader

15

bus

2

 

comment

11

18 Chapter 1 Introduction to Computers, Programs, and Java

compiler

7

 

 

 

console

11

 

 

 

dot pitch

5

 

 

 

DSL (digital subscriber line)

5

hardware

2

 

 

 

high-level language

6

 

Integrated Development Environment

(IDE)

10

 

 

 

java command

15

 

 

javac command 15

 

Java Development Toolkit (JDK) 10

Java Virtual Machine (JVM)

14

keyword (or reserved word)

11

line comment

11

 

 

machine language

5

 

main method

11

 

 

memory

3

modem

5

network interface card (NIC) 5 operating system (OS) 7

pixel 5

 

 

program

5

 

programming

5

resolution

5

 

software

5

 

source code 7

 

source file

14

 

specific import

17

storage devices

4

statement

11

 

wildcard import

17

 

Note

Supplement I.A

The above terms are defined in the present chapter. Supplement I.A, “Glossary,” lists all the

 

key terms and descriptions in the book, organized by chapters.

CHAPTER SUMMARY

1.A computer is an electronic device that stores and processes data.

2.A computer includes both hardware and software.

3.Hardware is the physical aspect of the computer that can be seen.

4.Computer programs, known as software, are the invisible instructions that control the hardware and make it perform tasks.

5.Computer programming is the writing of instructions (i.e., code) for computers to perform.

6.The central processing unit (CPU) is a computer’s brain. It retrieves instructions from memory and executes them.

7.Computers use zeros and ones because digital devices have two stable states, referred to by convention as zero and one.

8.A bit is a binary digit 0 or 1.

9.A byte is a sequence of 8 bits.

10.A kilobyte is about 1000 bytes, a megabyte about 1 million bytes, a gigabyte about 1 billion bytes, and a terabyte about 1000 gigabytes.

11.Memory stores data and program instructions for the CPU to execute.

12.A memory unit is an ordered sequence of bytes.

13.Memory is volatile, because information is lost when the power is turned off.

Chapter Summary 19

14.Programs and data are permanently stored on storage devices and are moved to memory when the computer actually uses them.

15.The machine language is a set of primitive instructions built into every computer.

16.Assembly language is a low-level programming language in which a mnemonic is used to represent each machine-language instruction.

17.High-level languages are English-like and easy to learn and program.

18.A program written in a high-level language is called a source program.

19.A compiler is a software program that translates the source program into a machinelanguage program.

20.The operating system (OS) is a program that manages and controls a computer’s activities.

21.Java is platform independent, meaning that you can write a program once and run it anywhere.

22. Java programs can be embedded in HTML pages and downloaded by Web browsers to bring live animation and interaction to Web clients.

23.Java source files end with the .java extension.

24.Every class is compiled into a separate bytecode file that has the same name as the class and ends with the .class extension.

25.To compile a Java source-code file from the command line, use the javac command.

26.To run a Java class from the command line, use the java command.

27.Every Java program is a set of class definitions. The keyword class introduces a class definition. The contents of the class are included in a block.

28.A block begins with an opening brace ({) and ends with a closing brace (}). Methods are contained in a class.

29.A Java program must have a main method. The main method is the entry point where the program starts when it is executed.

30.Every statement in Java ends with a semicolon (;), known as the statement terminator.

31.Reserved words, or keywords, have a specific meaning to the compiler and cannot be used for other purposes in the program.

32.In Java, comments are preceded by two slashes (//) on a line, called a line comment, or enclosed between /* and */ on one or several lines, called a block comment.

33.Java source programs are case sensitive.

34.There are two types of import statements: specific import and wildcard import. The specific import specifies a single class in the import statement. The wildcard import imports all the classes in a package.

20 Chapter 1 Introduction to Computers, Programs, and Java

REVIEW QUESTIONS

Note

Answers to review questions are on the Companion Website.

Sections 1.2–1.4

1.1Define hardware and software.

1.2List the main components of the computer.

1.3Define machine language, assembly language, and high-level programming language.

1.4What is a source program? What is a compiler?

1.5What is the JVM?

1.6What is an operating system?

Sections 1.5–1.6

1.7Describe the history of Java. Can Java run on any machine? What is needed to run Java on a computer?

1.8What are the input and output of a Java compiler?

1.9List some Java development tools. Are tools like NetBeans and Eclipse different languages from Java, or are they dialects or extensions of Java?

1.10What is the relationship between Java and HTML?

Sections 1.7–1.9

1.11Explain the Java keywords. List some Java keywords you learned in this chapter.

1.12Is Java case sensitive? What is the case for Java keywords?

1.13What is the Java source filename extension, and what is the Java bytecode filename extension?

1.14What is a comment? Is the comment ignored by the compiler? How do you denote a comment line and a comment paragraph?

1.15What is the statement to display a string on the console? What is the statement to display the message “Hello world” in a message dialog box?

1.16The following program is wrong. Reorder the lines so that the program displays morning followed by afternoon.

public static void main(String[] args) {

}

public class Welcome { System.out.println("afternoon"); System.out.println("morning");

}

1.17Identify and fix the errors in the following code:

1 public class Welcome {

2public void Main(String[] args) {

3System.out.println('Welcome to Java!);

4

}

5

)

Programming Exercises 21

1.18What is the command to compile a Java program? What is the command to run a Java program?

1.19If a NoClassDefFoundError occurs when you run a program, what is the cause of the error?

1.20If a NoSuchMethodError occurs when you run a program, what is the cause of the error?

1.21Why does the System class not need to be imported?

1.22Are there any performance differences between the following two import statements?

import javax.swing.JOptionPane;

import javax.swing.*;

1.23Show the output of the following code:

public class Test {

public static void main(String[] args) { System.out.println("3.5 * 4 / 2 – 2.5 is "); System.out.println(3.5 * 4 / 2 2.5);

}

}

PROGRAMMING EXERCISES

Note

Solutions to even-numbered exercises are on the Companion Website. Solutions to all exer-

cises are on the Instructor Resource Website. The level of difficulty is rated easy (no star), level of difficulty moderate (*), hard (**), or challenging (***).

1.1(Displaying three messages) Write a program that displays Welcome to Java,

Welcome to Computer Science, and Programming is fun.

1.2(Displaying five messages) Write a program that displays Welcome to Java five times.

1.3* (Displaying a pattern) Write a program that displays the following pattern:

 

J

A

V

 

V

A

 

J

A A

 

V

V

A A

J

J

AAAAA

 

V V

 

AAAAA

J J

A

 

A

V

A

A

1.4(Printing a table) Write a program that displays the following table:

a

a^2

a^3

1

1

1

2

4

8

3

9

27

4

16

64

1.5

(Computing

expressions) Write a program that displays the result of

 

 

9.5 * 4.5

- 2.5 * 3

.

 

45.5

-

3.5

 

 

22 Chapter 1 Introduction to Computers, Programs, and Java

1.6 (Summation of a series) Write a program that displays the result of

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9.

1.7(Approximating p) p can be computed using the following formula:

 

 

 

 

1

1

1

 

 

1

 

1

 

1

 

 

 

 

 

 

 

 

 

 

 

 

 

 

p = 4 * a1 -

 

+

 

-

 

 

+

 

 

-

 

+

 

+

Á b

 

 

 

 

 

 

 

 

 

 

 

 

3

5

7

9

11

13

 

 

 

 

 

 

Write

a

program that displays

the

 

result

of

4 * a1 -

1

+

1

-

1

+

 

3

5

7

1

-

1

+

1

b. Use 1.0 instead of

1 in your program.

 

 

 

 

 

 

 

 

9

11

 

13

 

 

 

 

 

 

 

 

CHAPTER 2

ELEMENTARY PROGRAMMING

Objectives

To write Java programs to perform simple calculations (§2.2).

To obtain input from the console using the Scanner class (§2.3).

To use identifiers to name variables, constants, methods, and classes (§2.4).

To use variables to store data (§§2.5–2.6).

To program with assignment statements and assignment expressions (§2.6).

To use constants to store permanent data (§2.7).

To declare Java primitive data types: byte, short, int, long, float, double, and char (§2.8.1).

To use Java operators to write numeric expressions (§§2.8.2–2.8.3).

To display the current time (§2.9).

To use shorthand operators (§2.10).

To cast the value of one type to another type (§2.11).

To compute loan payments (§2.12).

To represent characters using the char type (§2.13).

To compute monetary changes (§2.14).

To represent a string using the String type (§2.15).

To become familiar with Java documentation, programming style, and naming conventions (§2.16).

To distinguish syntax errors, runtime errors, and logic errors and debug errors (§2.17).

(GUI) To obtain input using the JOptionPane input dialog boxes (§2.18).

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]