Chapter 1. Introduction

CHAPTER GOALS

  • To understand the activity of programming

  • To learn about the architecture of computers

  • To learn about machine code and high-level programming languages

  • To become familiar with the structure of simple Java programs

  • To compile and run your first Java program

  • To recognize compile-time and run-time errors

  • To write pseudocode for simple algorithms

The purpose of this chapter is to familiarize you with the concepts of programming and program development. It reviews the architecture of a computer and discusses the difference between machine code and high-level programming languages. You will see how to compile and run your first Java program, and how to diagnose errors that may occur when a program is compiled or executed. Finally, you will learn how to formulate simple algorithms using pseudocode notation.

What Is Programming?

You have probably used a computer for work or fun. Many people use computers for everyday tasks such as balancing a checkbook or writing a term paper. Computers are good for such tasks. They can handle repetitive chores, such as totaling up numbers or placing words on a page, without getting bored or exhausted. Computers also make good game machines because they can play sequences of sounds and pictures, involving the human user in the process.

The flexibility of a computer is quite an amazing phenomenon. The same machine can balance your checkbook, print your term paper, and play a game. In contrast, other machines carry out a much narrower range of tasks—a car drives and a toaster toasts.

To achieve this flexibility, the computer must be programmed to perform each task. A computer itself is a machine that stores data (numbers, words, pictures), interacts with devices (the monitor screen, the sound system, the printer), and executes programs. Programs are sequences of instructions and decisions that the computer carries out to achieve a task. One program balances checkbooks; a different program, perhaps designed and constructed by a different company, processes words; and a third program, probably from yet another company, plays a game.

Note

A computer must be programmed to perform tasks. Different tasks require different programs.

Today's computer programs are so sophisticated that it is hard to believe that they are all composed of extremely primitive instructions. A typical instruction may be one of the following:

  • Put a red dot onto this screen position.

  • Get a number from this location in memory.

  • Add up two numbers.

  • If this value is negative, continue the program at that instruction.

Note

A computer program executes a sequence of very basic instructions in rapid succession.

A computer program tells a computer, in minute detail, the sequence of steps that are needed to complete a task. A program contains a huge number of simple instructions, and the computer executes them at great speed. The computer has no intelligence—it simply executes instruction sequences that have been prepared in advance.

Note

A computer program contains the instruction sequences for all tasks that it can execute.

To use a computer, no knowledge of programming is required. When you write a term paper with a word processor, that computer program has been developed by the manufacturer and is ready for you to use. That is only to be expected—you can drive a car without being a mechanic and toast bread without being an electrician.

A primary purpose of this book is to teach you how to design and implement computer programs. You will learn how to formulate instructions for all tasks that your programs need to execute.

Keep in mind that programming a sophisticated computer game or word processor requires a team of many highly skilled programmers, graphic artists, and other professionals. Your first programming efforts will be more mundane. The concepts and skills you learn in this book form an important foundation, but you should not expect to immediately produce professional software. A typical college degree in computer science or software engineering takes four years to complete; this book is intended as a text for an introductory course in such a program.

Many students find that there is an immense thrill even in simple programming tasks. It is an amazing experience to see the computer carry out a task precisely and quickly that would take you hours of drudgery.

1.

What Is Programming?

2. Why is a CD player less flexible than a computer?

3. Can a computer program develop the initiative to execute tasks in a better way than its programmers envisioned?

The Anatomy of a Computer

To understand the programming process, you need to have a rudimentary understanding of the building blocks that make up a computer. This section will describe a personal computer. Larger computers have faster, larger, or more powerful components, but they have fundamentally the same design.

At the heart of the computer lies the central processing unit (CPU) (see Figure 1). It consists of a single chip (integrated circuit) or a small number of chips. A computer chip is a component with a plastic or metal housing, metal connectors, and inside wiring made principally from silicon. For a CPU chip, the inside wiring is enormously complicated. For example, the Intel Core processor (a popular CPU for inexpensive laptops at the time of this writing) contains several hundred million structural elements called transistors—the elements that enable electrical signals to control other electrical signals, making automatic computing possible. The CPU locates and executes the program instructions; it carries out arithmetic operations such as addition, subtraction, multiplication, and division; and it fetches data from storage and input/output devices and sends data back.

Note

At the heart of the computer lies the central processing unit (CPU).

Central Processing Unit

Figure 1.1. Central Processing Unit

A Memory Module with Memory Chips

Figure 1.2. A Memory Module with Memory Chips

The computer keeps data and programs in storage. There are two kinds of storage. Primary storage, also called random-access memory (RAM) or simply memory, is fast but expensive; it is made from memory chips (see Figure 2). Primary storage loses all its data when the power is turned off. Secondary storage, usually a hard disk (see Figure 3), provides less expensive storage that persists without electricity. A hard disk consists of rotating platters, which are coated with a magnetic material, and read/write heads, which can detect and change the patterns of varying magnetic flux on the platters.

Note

Data and programs are stored in primary storage (memory) and secondary storage (such as a hard disk).

Some computers are self-contained units, whereas others are interconnected through networks. Home computers are usually intermittently connected to the Internet via a dialup or broadband connection. The computers in your computer lab are probably permanently connected to a local area network. Through the network cabling, the computer can read programs from central storage locations or send data to other computers. For the user of a networked computer, it may not even be obvious which data reside on the computer itself and which are transmitted through the network.

Most computers have removable storage devices that can access data or programs on media such as memory sticks or optical disks.

To interact with a human user, a computer requires other peripheral devices. The computer transmits information to the user through a display screen, loudspeakers, and printers. The user can enter information and directions to the computer by using a keyboard or a pointing device such as a mouse.

A Hard Disk

Figure 1.3. A Hard Disk

The CPU, the RAM, and the electronics controlling the hard disk and other devices are interconnected through a set of electrical lines called a bus. Data travel along the bus from the system memory and peripheral devices to the CPU and back. Figure 4 shows a motherboard, which contains the CPU, the RAM, and connectors to peripheral devices.

A Motherboard

Figure 1.4. A Motherboard

Schematic Diagram of a Computer

Figure 1.5. Schematic Diagram of a Computer

Figure 5 gives a schematic overview of the architecture of a computer. Program instructions and data (such as text, numbers, audio, or video) are stored on the hard disk, on an optical disk (such as a DVD), or on a network. When a program is started, it is brought into memory where it can be read by the CPU. The CPU reads the program one instruction at a time. As directed by these instructions, the CPU reads data, modifies it, and writes it back to RAM or to secondary storage. Some program instructions will cause the CPU to interact with the devices that control the display screen or the speaker. Because these actions happen many times over and at great speed, the human user will perceive images and sound. Similarly, the CPU can send instructions to a printer to mark the paper with patterns of closely spaced dots, which a human recognizes as text characters and pictures. Some program instructions read user input from the keyboard or mouse. The program analyzes these inputs and then executes the next appropriate instructions.

Note

The CPU reads machine instructions from memory. The instructions direct it to communicate with memory, secondary storage, and peripheral devices.

4.

Schematic Diagram of a Computer

5. Which part of the computer carries out arithmetic operations, such as addition and multiplication?

Translating Human-Readable Programs to Machine Code

On the most basic level, computer instructions are extremely primitive. The processor executes machine instructions. CPUs from different vendors, such as the Intel Pentium or the Sun SPARC, have different sets of machine instructions. To enable Java applications to run on different CPUs without modification, Java programs contain machine instructions for a so-called "Java virtual machine" (JVM), an idealized CPU that is simulated by a program run on the actual CPU.

Note

Generally, machine code depends on the CPU type. However, the instruction set of the Java virtual machine (JVM) can be executed on different CPUs.

Instructions for actual and virtual machines are very simple and can be executed very quickly. A typical sequence of machine instructions is

  1. Load the contents of memory location 40.

  2. Load the value 100.

  3. If the first value is greater than the second value, continue with the instruction that is stored in memory location 240.

Actually, machine instructions are encoded as numbers so that they can be stored in memory. On the Java virtual machine, this sequence of instructions is encoded as the sequence of numbers

21 40
16 100
163 240

When the virtual machine fetches this sequence of numbers, it decodes them and executes the associated sequence of commands.

How can you communicate the command sequence to the computer? The most direct method is to place the actual numbers into the computer memory. This is, in fact, how the very earliest computers worked. However, a long program is composed of thousands of individual commands, and it is tedious and error-prone to look up the numeric codes for all commands and manually place the codes into memory. As we said before, computers are really good at automating tedious and error-prone activities, and it did not take long for computer programmers to realize that computers could be harnessed to help in the programming process.

Note

Because machine instructions are encoded as numbers, it is difficult to write programs in machine code.

In the mid-1950s, high-level programming languages began to appear. In these languages, the programmer expresses the idea behind the task that needs to be performed, and a special computer program, called a compiler, translates the high-level description into machine instructions for a particular processor.

Note

High-level languages allow you to describe tasks at a higher conceptual level than machine code.

For example, in Java, the high-level programming language that you will use in this book, you might give the following instruction:

if (intRate > 100)
   System.out.println("Interest rate error");

This means, "If the interest rate is over 100, display the message Interest rate error". It is then the job of the compiler program to look at the sequence of characters

21 40 16 100 163 240 . . .

Compilers are quite sophisticated programs. They translate logical statements, such as the if statement, into sequences of computations, tests, and jumps. They assign memory locations for variables—items of information identified by symbolic names—like intRate. In this course, we will generally take the existence of a compiler for granted. If you decide to become a professional computer scientist, you may well learn more about compiler-writing techniques later in your studies.

Note

A compiler translates programs written in a high-level language into machine code.

6.

Translating Human-Readable Programs to Machine Code

7. Does a person who uses a computer for office work ever run a compiler?

The Java Programming Language

In 1991, a group led by James Gosling and Patrick Naughton at Sun Microsystems designed a programming language that they code-named "Green" for use in consumer devices, such as intelligent television "set-top" boxes. The language was designed to be simple and architecture neutral, so that it could be executed on a variety of hardware. No customer was ever found for this technology.

Note

Java was originally designed for programming consumer devices, but it was first used successfully to write Internet applets.

Gosling recounts that in 1994 the team realized, "We could write a really cool browser. It was one of the few things in the client/server mainstream that needed some of the weird things we'd done: architecture neutral, real-time, reliable, secure." Java was introduced to an enthusiastic crowd at the SunWorld exhibition in 1995.

Since then, Java has grown at a phenomenal rate. Programmers have embraced the language because it is simpler than its closest rival, C++. In addition, Java has a rich library that makes it possible to write portable programs that can bypass proprietary operating systems—a feature that was eagerly sought by those who wanted to be independent of those proprietary systems and was bitterly fought by their vendors. A "micro edition" and an "enterprise edition" of the Java library make Java programmers at home on hardware ranging from smart cards and cell phones to the largest Internet servers.

Note

Java was designed to be safe and portable, benefiting both Internet users and students.

An Applet for Visualizing Molecules Running in a Browser (http://jmol.sourceforge.net/applet/)

Figure 1.6. An Applet for Visualizing Molecules Running in a Browser (http://jmol.sourceforge.net/applet/)

Because Java was designed for the Internet, it has two attributes that make it very suitable for beginners: safety and portability. If you visit a web page that contains Java code (so-called applets—see Figure 6 for an example), the code automatically starts running. It is important that you can trust that applets are inherently safe. If an applet could do something evil, such as damaging data or reading personal information on your computer, then you would be in real danger every time you browsed the Web—an unscrupulous designer might put up a web page containing dangerous code that would execute on your machine as soon as you visited the page. The Java language has an assortment of security features that guarantees that no malicious applets can run on your computer. As an added benefit, these features also help you to learn the language faster. The Java virtual machine can catch many kinds of beginners' mistakes and report them accurately. (In contrast, many beginners' mistakes in the C++ language merely produce programs that act in random and confusing ways.) The other benefit of Java is portability. The same Java program will run, without change, on Windows, UNIX, Linux, or the Macintosh. This too is a requirement for applets. When you visit a web page, the web server that serves up the page contents has no idea what computer you are using to browse the Web. It simply returns the portable code that was generated by the Java compiler. The virtual machine on your computer executes that portable code. Again, there is a benefit for the student. You do not have to learn how to write programs for different platforms.

At this time, Java is firmly established as one of the most important languages for general-purpose programming as well as for computer science instruction. However, although Java is a good language for beginners, it is not perfect, for three reasons.

Because Java was not specifically designed for students, no thought was given to making it really simple to write basic programs. You must master a certain amount of technical detail to write even the simplest Java program. This is not a problem for professional programmers, but it is a drawback for beginning students. As you learn how to program in Java, there will be times when you will be asked to be satisfied with a preliminary explanation and wait for complete information in a later chapter.

Table 1.1. Java Versions

Version

Year

Important New Features

1.0

1996

 

1.1

1997

Inner classes

1.2

1998

Swing, Collections framework

1.3

2000

Performance enhancements

1.4

2002

Assertions, XML support

5

2004

Generic classes, enhanced for loop, auto-boxing, enumerations, annotations

6

2006

Library improvements

7

2010

Small language changes and library improvements

Java was revised and extended many times during its life—see Table 1. In this book, we assume that you have Java version 5 or later.

Finally, you cannot hope to learn all of Java in one term. The Java language itself is relatively simple, but Java has a vast library with support for graphics, user interface design, cryptography, networking, sound, database storage, and many other purposes. Even expert Java programmers cannot hope to know the contents of the entire library—they just use those parts that they need for particular projects.

Note

Java has a very large library. Focus on learning those parts of the library that you need for your programming projects.

Using this book, you should expect to learn a good deal about the Java language and about the most important parts of the Java library. Keep in mind that the central goal of this book is not to make you memorize Java minutiae, but to teach you how to think about programming.

8.

Java Versions

9. How long does it take to learn the entire Java library?

The Structure of a Simple Program

When learning a new programming language, it is traditional to start with a "Hello, World!" program—a program that displays a greeting. Here is this program in Java:

ch01/hello/HelloPrinter.java

1    public class HelloPrinter
2    {
3       public static void main(String[] args)
4       {
5          // Display a greeting in the console window
6
7          System.out.println("Hello, World!");
8       }
9    }

Program Run

Hello, World!

In the next section, you will see how to compile and run this program. But let us first understand how it is structured.

The line,

public class HelloPrinter

starts a new class. Classes are a fundamental concept in Java, and you will begin to study them in Chapter 2. In Java, every program consists of one or more classes.

The word public denotes that the class is usable by the "public", that is, everywhere in your program. You will later encounter private features.

In Java, every source file can contain at most one public class, and the name of the public class must match the name of the file containing the class. For example, the class HelloPrinter must be contained in a file named HelloPrinter.java.

Note

Classes are the fundamental building blocks of Java programs.

The construction

public static void main(String[] args)
{
   ...
}

declares a method called main. A method contains a collection of programming instructions that describe how to carry out a particular task. Every Java application must have a main method. Most Java programs contain other methods besides main, and you will see in Chapter 3 how to write other methods.

Note

Every Java application contains a class with a main method. When the application starts, the instructions in the main method are executed.

We will fully explain the word static and the declaration String[] args in Chapters 8 and 11. At this time, you should simply consider

public class ClassName
{
   public static void main(String[] args)
   {
      ...
   }
}

as a part of the "plumbing" that is required to write any Java program.

The first line inside the main method is a comment:

// Display a greeting in the console window

This comment is purely for the benefit of the human reader, to explain in more detail what the next statement does. Any text enclosed between // and the end of the line is completely ignored by the compiler. Comments are used to explain the program to other programmers or to yourself.

Note

Use comments to help human readers understand your program.

The instructions or statements in the body of the main method—that is, the statements inside the curly brackets ({})—are executed one by one. Each statement ends in a semicolon (;). Our method has a single statement:

System.out.println("Hello, World!");

This statement prints a line of text, namely "Hello, World!". However, there are many places where a program can send that text: to a window, to a file, or to a networked computer on the other side of the world. You need to specify that the destination is the system output—that is, a console window. The console window is represented in Java by an object called System.out. An object is an entity that you manipulate in your programs.

In Java, each object belongs to a class, and the class declares methods that specify what you can do with the objects. The System.out object belongs to the PrintStream class. The PrintStream class has a method called println for printing a line of text.

You do not have to implement this method—the programmers who wrote the Java library already did that for us—but you do need to call the method.

Whenever you call a method in Java, you need to specify three items (see Figure 7):

  1. The object that you want to use (in this case, System.out).

  2. The name of the method you want to use (in this case, println).

  3. A pair of parentheses, containing any other information the method needs (in this case, "Hello, World!"). The technical term for this information is a parameter.

Note

A method is called by specifying an object, the method name, and the method parameters.

Calling a Method

Figure 1.7. Calling a Method

A sequence of characters enclosed in double quotation marks

"Hello, World!"

is called a string. You must enclose the contents of the string inside quotation marks so that the compiler knows you literally mean "Hello, World!". There is a reason for this requirement. Suppose you need to print the word main. By enclosing it in quotation marks, "main", the compiler knows you mean the sequence of characters m a i n, not the method named main. The rule is simply that you must enclose all text strings in quotation marks, so that the compiler considers them plain text and does not try to interpret them as program instructions.

Note

A string is a sequence of characters enclosed in quotation marks.

You can also print numerical values. For example, the statement

System.out.println(3 + 4);

displays the number 7.

The println method prints a string or a number and then starts a new line. For example, the sequence of statements

System.out.println("Hello");
System.out.println("World!");

prints two lines of text:

Hello
World!

There is a second method, called print, that you can use to print an item without starting a new line. For example, the output of the two statements

System.out.print("00");
System.out.println(3 + 4);

is the single line

007

10.

Method Call

11. Would the program continue to work if you omitted the line starting with //?

12. What does the following set of statements print?

System.out.print("My lucky number is");
System.out.println(3 + 4 + 5);

Compiling and Running a Java Program

Many students find that the tools that they need as programmers are very different from the software with which they familiar. You should spend some time making yourself familiar with your programming environment. Instructions for several popular environments are available in WileyPLUS.

Note

Set aside some time to become familiar with the computer system and the Java compiler that you will use for your class work.

Some Java development environments are very convenient to use. Enter the code in one window, click on a button to compile, and click on another button to execute your program. Error messages show up in a second window, and the program runs in a third window. With such an environment you are completely shielded from the details of the compilation process. On other systems you must carry out every step manually, by typing commands into a console window.

No matter which development environment you use, you begin your activity by typing in the program statements. The program that you use for entering and modifying the program text is called an editor. The first step for creating a Java program, such as the HelloPrinter program of the preceding section, is to start your editor. Make a new program file and call it HelloPrinter.java. (If your environment requires that you supply a project name in addition to the file name, use the name hello for the project.) Enter the program instructions exactly as they are given above. Alternatively, locate an electronic copy and paste it into your editor.

Note

An editor is a program for entering and modifying text, such as a Java program.

Java is case sensitive. You must enter upper- and lowercase letters in the same way as they appear in the program listing. You cannot type MAIN or PrintLn. If you are not careful, you will run into problems—see Common Error 1.2 on page 20. On the other hand, Java has free-form layout. You can use any number of spaces and line breaks to separate words. You can cram as many words as possible into each line,

public class HelloPrinter{public static void main(String[]
args){// Display a greeting in the console window
System.out.println("Hello, World!");}}

Note

Java is case sensitive. You must be careful about distinguishing between upper- and lowercase letters.

Of course, this is not a good idea. It is important to format your programs neatly so that you and other programmers can read them easily. We will give you recommendations for good layout throughout this book. Appendix L contains a summary of our recommendations.

Note

Lay out your programs so that they are easy to read.

Now find out how to run the test program. The message

Hello, World!

will appear somewhere on the screen (see Figures 8 and 9). The exact location depends on your programming environment.

Running the HelloPrinter Program in a Console Window

Figure 1.8. Running the HelloPrinter Program in a Console Window

Running the HelloPrinter Program in an Integrated Development Environment

Figure 1.9. Running the HelloPrinter Program in an Integrated Development Environment

Running your program takes two steps. (Some development environments automatically carry out both steps when you ask to run a program.)

Note

The Java compiler translates source code into class files that contain instructions for the Java virtual machine.

The first step is to compile your program. The compiler translates the Java source code (that is, the statements that you wrote) into class files, which consist of virtual machine instructions and other information that is required for execution. The class files have the extension .class. For example, the virtual machine instructions for the HelloPrinter program are stored in a file HelloPrinter.class. Note that the compiler does not produce a class file if it has found errors in your program.

From Source Code to Running Program

Figure 1.10. From Source Code to Running Program

The class file contains merely the translation of the instructions that you wrote. That is not enough to actually run the program. To display a string in a window, quite a bit of low-level activity is necessary. The authors of the System and PrintStream classes (which declare the out object and the println method) have implemented all necessary actions and placed the required class files into a library. A library is a collection of code that has been programmed and translated by someone else, ready for you to use in your program.

The Java virtual machine loads the instructions for the program that you wrote, starts your program, and loads the necessary library files as they are required.

The steps of compiling and running your program are outlined in Figure 10.

Note

The Java virtual machine loads program instructions from class files and library files.

13.

From Source Code to Running Program

14. What do you expect to see when you load a class file into your text editor?

Errors

Experiment a little with the HelloPrinter program. What happens if you make a typing error such as

System.ou.println("Hello, World!);
System.out.println("Hello, Word!");

In the first case, the compiler will complain. It will say that it has no clue what you mean by ou. The exact wording of the error message is dependent on the compiler, but it might be something like "Cannot find symbol ou". This is a compile-time error, also called a syntax error. Something is wrong according to the language rules and the compiler finds it. When the compiler finds one or more errors, it refuses to translate the program to Java virtual machine instructions, and as a consequence you have no program that you can run. You must fix the error and compile again. In fact, the compiler is quite picky, and it is common to go through several rounds of fixing compile-time errors before compilation succeeds for the first time.

Note

A compile-time error is a violation of the programming language rules that is detected by the compiler.

If the compiler finds an error, it will not simply stop and give up. It will try to report as many errors as it can find, so you can fix them all at once.

Sometimes, an error throws the compiler off track. Suppose, for example, you forget the quotation marks around a string: System.out.println(Hello, World!). The compiler will not complain about the missing quotation marks. Instead, it will report "Cannot find symbol Hello". It is up to you to realize that you need to enclose strings in quotation marks.

The error in the second line is of a different kind. The program will compile and run, but its output will be wrong. It will print

Hello, Word!

This is a run-time error, also called a logic error. The program is syntactically correct and does something, but it doesn't do what it is supposed to do.

Note

A run-time error causes a program to take an action that the programmer did not intend.

This particular run-time error did not include an error message. It simply produced the wrong output. Some kinds of run-time errors are so severe that they generate an exception: an error message from the Java virtual machine. For example, if your program includes the statement

System.out.println(1/0);

you will get a run-time error message "Division by zero".

During program development, errors are unavoidable. Once a program is longer than a few lines, it requires superhuman concentration to enter it correctly without slipping up once. You will find yourself omitting semicolons or quotes more often than you would like, but the compiler will track down these problems for you.

Run-time errors are more troublesome. The compiler will not find them—in fact, the compiler will cheerfully translate any program as long as its syntax is correct—but the resulting program will do something wrong. It is the responsibility of the program author to test the program and find any run-time errors. Testing programs is an important topic that you will encounter many times in this book. Another important aspect of good craftsmanship is defensive programming: structuring programs and development processes in such a way that an error in one part of a program does not trigger a disastrous response.

The error examples that you saw so far were not difficult to diagnose or fix, but as you learn more sophisticated programming techniques, there will also be much more room for error. It is an uncomfortable fact that locating all errors in a program is very difficult. Even if you can observe that a program exhibits faulty behavior, it may not at all be obvious what part of the program caused it and how you can fix it. Special software tools (so-called debuggers) let you trace through a program to find bugs—that is, run-time errors. In Chapter 6 you will learn how to use a debugger effectively.

Note that these errors are different from the types of errors that you are likely to make in calculations. If you total up a column of numbers, you may miss a minus sign or accidentally drop a carry, perhaps because you are bored or tired. Computers do not make these kinds of errors.

This book uses a three-part error management strategy. First, you will learn about common errors and how to avoid them. Then you will learn defensive programming strategies to minimize the likelihood and impact of errors. Finally, you will learn testing and debugging strategies to flush out those errors that remain.

Errors

16. When you used your computer, you may have experienced a program that "crashed" (quit spontaneously) or "hung" (failed to respond to your input). Is that behavior a compile-time error or a run-time error?

17. Why can't you test a program for run-time errors when it has compiler errors?

Algorithms

You will soon learn how to program calculations and decision making in Java. But before we look at the mechanics of implementing computations in the next chapter, let's consider the planning process that precedes implementation.

You may have run across advertisements that encourage you to pay for a computerized service that matches you up with a love partner. Think how this might work. You fill out a form and send it in. Others do the same. The data are processed by a computer program. Is it reasonable to assume that the computer can perform the task of finding the best match for you? Suppose your younger brother, not the computer, had all the forms on his desk. What instructions could you give him? You can't say, "Find the best-looking person who likes inline skating and browsing the Internet". There is no objective standard for good looks, and your brother's opinion (or that of a computer program analyzing the digitized photo) will likely be different from yours. If you can't give written instructions for someone to solve the problem, there is no way the computer can magically find the right solution. The computer can only do what you tell it to do. It just does it faster, without getting bored or exhausted.

For that reason, a computerized match-making service cannot guarantee to find the optimal match for you. Instead, it may present a set of potential partners who share common interests with you. That is a task that a computer program can solve.

Now consider the following investment problem:

You put $10,000 into a bank account that earns 5 percent interest per year. How many years does it take for the account balance to be double the original?

Could you solve this problem by hand? Sure, you could. You figure out the balance as follows:

Algorithms

You keep going until the balance is at least $20,000. Then the last number in the year column is the answer.

Of course, carrying out this computation is intensely boring to you or your younger brother. But computers are very good at carrying out repetitive calculations quickly and flawlessly. What is important to the computer is a description of the steps for finding the solution. Each step must be clear and unambiguous, requiring no guesswork. Here is such a description:

Start with a year value of 0 and a balance of $10,000.

Algorithms

Repeat the following steps while the balance is less than $20,000.

Add 1 to the year value.

Multiply the balance value by 1.05 (a 5 percent increase).

Algorithms

Report the final year value as the answer.

Of course, these steps are not yet in a language that a computer can understand, but you will soon learn how to formulate them in Java. This informal description is called pseudocode.

Note

Pseudocode is an informal description of a sequence of steps for solving a problem.

There are no strict requirements for pseudocode because it is read by human readers, not a computer program. Here are the kinds of pseudocode statements that we will use in this book:

  • Use statements such as the following to describe how a value is set or changed:

    total cost = purchase price + operating cost

    or

    Multiply the balance value by 1.05.

    or

    Remove the first and last character from the word.

  • Describe decisions and repetitions as follows:

    If total cost 1 < total cost 2

    or

    While the balance is less than $20,000

    or

    For each picture in the sequence

    Use indentation to indicate which statements should be selected or repeated.

    For each car

    operating cost = 10 x annual fuel cost

    total cost = purchase price + operating cost

    Here, the indentation indicates that both statements should be executed for each car.

  • Indicate results with statements such as

    Choose car1.

    Report the final year value as the answer.

The exact wording is not important. What is important is that the pseudocode describes a sequence of steps that is

  • Unambiguous

  • Executable

  • Terminating

The step sequence is unambiguous when there are precise instructions for what to do at each step and where to go next. There is no room for guesswork or personal opinion. A step is executable when it can be carried out in practice. Had we asked to use the actual interest rate that will be charged in years to come, and not a fixed rate of 5 percent per year, that step would not have been executable, because there is no way for anyone to know what that interest rate will be. A sequence of steps is terminating if it will eventually come to an end. In our example, it requires a bit of thought to see that the sequence will not go on forever: With every step, the balance goes up by at least $500, so eventually it must reach $20,000.

A sequence of steps that is unambiguous, executable, and terminating is called an algorithm. We have found an algorithm to solve our investment problem, and thus we can find the solution by programming a computer. The existence of an algorithm is an essential prerequisite for programming a task. You need to first discover and describe an algorithm for the task that you want to solve before you start programming (see Figure 12).

Note

An algorithm for solving a problem is a sequence of steps that is unambiguous, executable, and terminating.

The Program Development Process

Figure 1.12. The Program Development Process

The Program Development Process

19. Suppose your cell phone carrier charges you $29.95 for up to 300 minutes of calls, and $0.45 for each additional minute, plus 12.5 percent taxes and fees. Give an algorithm to compute the monthly charge for a given number of minutes.

Summary of Learning Objectives

Define "computer program" and "programming".

  • A computer must be programmed to perform tasks. Different tasks require different programs.

  • A computer program executes a sequence of very basic instructions in rapid succession.

  • A computer program contains the instruction sequences for all tasks that it can execute.

Describe the components of a computer.

  • At the heart of the computer lies the central processing unit (CPU).

  • Data and programs are stored in primary storage (memory) and secondary storage (such as a hard disk).

  • The CPU reads machine instructions from memory. The instructions direct it to communicate with memory, secondary storage, and peripheral devices.

Describe the process of translating high-level languages to machine code.

  • Generally, machine code depends on the CPU type. However, the instruction set of the Java virtual machine (JVM) can be executed on different CPUs.

  • Because machine instructions are encoded as numbers, it is difficult to write programs in machine code.

  • High-level languages allow you to describe tasks at a higher conceptual level than machine code.

  • A compiler translates programs written in a high-level language into machine code.

Describe the history and design principles of the Java programming language.

  • Java was originally designed for programming consumer devices, but it was first used successfully to write Internet applets.

  • Java was designed to be safe and portable, benefiting both Internet users and students.

  • Java has a very large library. Focus on learning those parts of the library that you need for your programming projects.

Describe the building blocks of a simple program and the structure of a method call.

  • Classes are the fundamental building blocks of Java programs.

  • Every Java application contains a class with a main method. When the application starts, the instructions in the main method are executed.

  • Use comments to help human readers understand your program.

  • A method is called by specifying an object, the method name, and the method parameters.

  • A string is a sequence of characters enclosed in quotation marks.

Use your programming environment to write and run Java programs.

  • Set aside some time to become familiar with the computer system and the Java compiler that you will use for your class work.

  • An editor is a program for entering and modifying text, such as a Java program.

  • Java is case sensitive. You must be careful about distinguishing between upper- and lowercase letters.

  • Lay out your programs so that they are easy to read.

  • The Java compiler translates source code into class files that contain instructions for the Java virtual machine.

  • The Java virtual machine loads program instructions from class files and library files.

  • Develop a strategy for keeping backup copies of your work before disaster strikes.

Classify program errors as compile-time and run-time errors.

  • A compile-time error is a violation of the programming language rules that is detected by the compiler.

  • A run-time error causes a program to take an action that the programmer did not intend.

Write pseudocode for simple algorithms.

  • Pseudocode is an informal description of a sequence of steps for solving a problem.

  • An algorithm for solving a problem is a sequence of steps that is unambiguous, executable, and terminating.

Classes, Objects, and Methods Introduced in this Chapter

Here is a list of all classes, objects, and methods introduced in this chapter. Turn to the documentation in Appendix D for more information.

java.io.PrintStream                      java.lang.System
   print                                    out
   println

Media Resources

  • Worked Example Writing an Algorithm for Tiling a Floor

  • Media Resources
  • Media Resources

Review Exercises

  • R1.1 Explain the difference between using a computer program and programming a computer.

  • R1.2 What distinguishes a computer from a typical household appliance?

  • R1.3 Describe exactly what steps you would take to back up your work after you have typed in the HelloPrinter.java program.

  • R1.4 On your own computer or on a lab computer, find the exact location (folder or directory name) of

    1. The sample file HelloPrinter.java, which you wrote with the editor.

    2. The Java program launcher java.exe or java.

    3. The library file rt.jar that contains the run-time library.

  • R1.5 How do you discover syntax errors? How do you discover logic errors?

  • R1.6 Write three versions of the HelloPrinter.java program that have different compile-time errors. Write a version that has a run-time error.

  • R1.7 What do the following statements print? Don't guess; write programs to find out.

    1. System.out.println("3 + 4");

    2. System.out.println(3 + 4);

    3. System.out.println(3 + "4");

  • R1.8 Write an algorithm to settle the following question: A bank account starts out with $10,000. Interest is compounded monthly at 6 percent per year (0.5 percent per month). Every month, $500 is withdrawn to meet college expenses. After how many years is the account depleted?

  • R1.9 Consider the question in Exercise R1.8. Suppose the numbers ($10,000, 6 percent, $500) were user selectable. Are there values for which the algorithm you developed would not terminate? If so, change the algorithm to make sure it always terminates.

  • R1.10 In order to estimate the cost of painting a house, a painter needs to know the surface area of the exterior. Develop an algorithm for computing that value. Your inputs are the width, length, and height of the house, the number of windows and doors, and their dimensions. (Assume the windows and doors have a uniform size.)

  • R1.11 You want to decide whether you should drive your car to work or take the train. You know the one-way distance from your home to your place of work, and the fuel efficiency of your car (in miles per gallon). You also know the one-way price of a train ticket. You assume the cost of gas at $4 per gallon, and car maintenance at 5 cents per mile. Write an algorithm to decide which commute is cheaper.

  • R1.12 You want to find out which fraction of your car use is for commuting to work, and which is for personal use. You know the one-way distance from your home to your place of work. For a particular period, you recorded the beginning and ending mileage on the odometer and the number of work days. Write an algorithm to settle this question.

  • R1.13 In the problem described in How To 1.1 on page 23, you made assumptions about the price of gas and the annual usage. Ideally, you would like to know which car is the better deal without making these assumptions. Why can't a computer program solve that problem?

Programming Exercises

P1.1 Write a program NamePrinter that displays your name inside a box on the console screen, like this:

Programming Exercises

Do your best to approximate lines with characters, such as |, -, and +.

P1.2 Write a program that prints your name in large letters, such as

Programming Exercises

P1.3 Write a program FacePrinter that prints a face, using text characters, hopefully better looking than this one:

Programming Exercises

Use comments to indicate the statements that print the hair, ears, mouth, and so on.

P1.4 Write a program that prints an animal speaking a greeting, similar to (but different from) the following

Programming Exercises

P1.5 Write a program TicTacToeBoardPrinter that prints a tic-tac-toe board:

Programming Exercises

P1.6 Write a program StaircasePrinter that prints a staircase:

Programming Exercises

P1.7 Write a program that prints three items, such as the names of your three best friends or favorite movies, on three separate lines.

P1.8 Write a program that computes the sum of the first ten positive integers, 1 + 2 + ... + 10. Hint: Write a program of the form

public class Sum10
{
   public static void main(String[] args)
   {
      System.out.println(           );
   }
}

P1.9 Type in and run the following program:

import javax.swing.JOptionPane;

public class DialogViewer
{
   public static void main(String[] args)
   {
      JOptionPane.showMessageDialog(null, "Hello, World!");
      System.exit(0);
   }
}

Then modify the program to show the message "Hello, your name!".

P1.10 Type in and run the following program:

import javax.swing.JOptionPane;

public class DialogViewer
{
   public static void main(String[] args)
   {
      String name = JOptionPane.showInputDialog("What is your name?");
      System.out.println(name);
      System.exit(0);
   }
}

Then modify the program to print "Hello, name!", displaying the name that the user typed in.

P1.11 Run the following program:

import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class Test
{
   public static void main(String[] args) throws Exception
   {
      URL imageLocation = new URL(
         "http://horstmann.com/bigjava/duke.gif");
      JOptionPane.showMessageDialog(null, "Hello", "Title",
         JOptionPane.PLAIN_MESSAGE, new ImageIcon(imageLocation));
      System.exit(0);
   }
}

Then modify it to show a different greeting and image.

Programming Projects

Project 1.1 This project builds on Exercises P1.9 and P1.10. Your program should read the user's name, then show a sequence of two dialog boxes:

  • First, an input dialog box that asks: "What would you like me to do?"

  • Then a message dialog box that says: "I'm sorry, your name. I'm afraid I can't do that."

Answers to Self-Check Questions

  1. A program that reads the data on the CD and sends output to the speakers and the screen.

  2. A CD player can do one thing—play music CDs. It cannot execute programs.

  3. No—the program simply executes the instruction sequences that the programmers have prepared in advance.

  4. In secondary storage, typically a hard disk.

  5. The central processing unit.

  6. 21 100

  7. No—a compiler is intended for programmers, to translate high-level programming instructions into machine code.

  8. Safety and portability.

  9. No one person can learn the entire library—it is too large.

  10. System.out.println("Hello,"); System.out.println("World!");

  11. Yes—the line starting with // is a comment, intended for human readers. The compiler ignores comments.

  12. The printout is My lucky number is12. It would be a good idea to add a space after the is.

  13. Yes, but you must remember to save your file as "plain text."

  14. A sequence of random characters, some funny-looking. Class files contain virtual machine instructions that are encoded as binary numbers.

  15. A compile-time error. The compiler will not know what to do with the word Display.

  16. It is a run-time error. After all, the program had been compiled in order for you to run it.

  17. When a program has compiler errors, no class file is produced, and there is nothing to run.

  18. 4 years:

    0 10,000

    1 12,000

    2 14,400

    3 17,280

    4 20,736

  19. Is the number of minutes at most 300?

    1. If so, the answer is $29.95 × 1.125 = $33.70.

    2. If not,

      1. Compute the difference: (number of minutes) – 300.

      2. Multiply that difference by 0.45.

      3. Add $29.95.

      4. Multiply the total by 1.125. That is the answer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.249.210