Learn Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

CHAPTER

Introduction

Chapter Goals
N N N N N N N To understand the activity of programming To learn about the architecture of computers To learn about machine languages and higher-level programming languages To become familiar with your compiler To compile and run your rst Java program To understand the concepts of classes and objects To recognize syntax and logic errors

Chapter 1.

Introduction

1.1

What Is a Computer?
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. More importantly, the computer presents you with the checkbook or the term paper on the screen and lets you x up mistakes easily. Computers make good game machines because they can play sequences of sounds and pictures, involving the human user in the process. Actually, what makes all this possible is not just the computer. The computer must be programmed to perform these tasks. One program balances checkbooks; a different program, probably designed and constructed by a different company, processes words; and a third program plays a game. 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. Todays computer programs are so sophisticated that it is hard to believe that they are all composed of extremely primitive operations. A typical operation may be one of the following.
N N N N N

Put a red dot onto this screen position. Send the letter A to the printer. Get a number from this location in memory. Add up these two numbers. If this value is negative, continue the program at that instruction.

Only because a program contains a huge number of such operations, and because the computer can execute them at great speed, does the computer user have the illusion of smooth interaction. The exibility 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. Computers can carry out a wide range of tasks because they execute different programs, each of which directs the computer to work on a specic task.

1.2

What Is Programming?
A computer program tells a computer, in minute detail, the sequence of steps that are needed to fulll a task. The act of designing and implementing these programs is called computer programming. In this course, you will learn how to program a computerthat is, how to direct the computer to execute tasks. To use a computer you do not need to do any programming. When you write a term paper with a word processor, that program has been programmed by the

1.3

The Anatomy of a Computer

manufacturer and is ready for you to use. That is only to be expectedyou can drive a car without being a mechanic and toast bread without being an electrician. Many people who use computers every day in their careers never need to do any programming. Of course, a professional computer scientist or software engineer does a great deal of programming. Since you are taking this rst course in computer science, it may well be your career goal to become such a professional. Programming is not the only skill required of a computer scientist or software engineer; indeed, programming is not the only skill required to create successful computer programs. Nevertheless, the activity of programming is an important part of computer science. It is also a fascinating and pleasurable activity that continues to attract and motivate students. The discipline of computer science is particularly fortunate that it can make such an interesting activity the foundation of the learning path. To write a computer game with motion and sound effects or a word processor that supports fancy fonts and pictures is a complex task that requires a team of many highly skilled programmers. Your rst programming efforts will be more mundane. The concepts and skills you learn in this course form an important foundation, and you should not be disappointed if your rst programs do not rival the sophisticated software that is familiar to you. Actually, you will nd that there is an immense thrill even in simple programming tasks. It is an amazing experience to see the computer precisely and quickly carry out a task that would take you hours of drudgery, to make small changes in a program that lead to immediate improvements, and to see the computer become an extension of your mental powers.

1.3

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. We will look at 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 or a small number of chips. A computer chip (integrated circuit) 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 Pentium chip (a popular CPU for personal computers at the time of this writing) is composed of over 3 million structural elements called transistors. Figure 2 shows a magnied detail view of a CPU chip. The CPU performs program control, arithmetic, and data movement. That is, the CPU locates and executes the program instructions; it carries out arithmetic operations such as addition, subtraction, multiplication, and division; it fetches data from external memory or devices or stores data back. All data must travel through the CPU whenever it is moved from one location to another. (There are a few technical exceptions to this rule; some devices can interact directly with memory.)

Chapter 1.

Introduction

Figure 1 Central Processing Unit


The computer stores data and programs in memory. There are two kinds of memory. Primary storage is fast but expensive; it is made from memory chips (see Figure 3): so-called random-access memory (RAM) and read-only memory (ROM). Read-only memory contains certain programs that must always be presentfor example, the code needed to start the computer. Random-access memory might have been better called read-write memory, because the CPU can read data from it and write data back to it. That makes RAM suitable to hold changing data and programs that do not have to be available permanently. RAM memory has two disadvantages. It is comparatively expensive, and it loses all its data when the power is turned off. Secondary storage, usually a hard disk (see Figure 4), 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 magnetic ux on the platters. This is essentially the same storage process that is used in audio or video tapes. Programs and data are typically stored on the hard disk and loaded into RAM when the program starts. The program then updates the data in RAM and writes the modied data back to the hard disk. You will often use another kind of magnetic storage device: a so-called oppy disk or diskette. Originally, oppy disks had a fairly low capacity, but recently highcapacity oppies such as the Zip disk and the Superdisk have become popular (see Figure 5). A oppy disk consists of a exible round base (hence the name oppy), covered with a magnetic material, inside a plastic cover (which is usually not exible). Like a hard disk, a oppy disk can also store data and programs, and the data

1.3

The Anatomy of a Computer

Figure 2 CPU Chip Detail

Figure 3 RAM Chips

Chapter 1.

Introduction

Figure 4 A Hard Disk

Figure 5 A High-Capacity Floppy Disk and Its Drive

1.3

The Anatomy of a Computer

Figure 6 A CD-ROM Drive


are kept without electricity. The most common use for a oppy disk is to move data from one computer to another; you can copy data from your home computer and bring the disk to school to continue working with it, or you can put the disk in the mail. Because a oppy disk is not an integral part of the computer system, it is called an external storage device. Floppy drives are inexpensive, comparatively rugged, and convenient, but they suffer from one disadvantage: One oppy disk cannot hold nearly as much data as a hard disk. That is not so much a problem for your personal data; it is quite likely that all the homework you will produce in this class will easily t on one oppy. However, audio and video information takes up much more space than a oppy disk provides. That kind of information is typically distributed on a CD-ROM (compact disc read-only memory; see Figure 6) or DVD (digital versatile disk). A CD-ROM looks just like an audio CD and is read by a laser device (in fact, a CD-ROM reader on a personal computer can also play an audio CD). A CD-ROM can hold a large amount of information, and it can be manufactured inexpensively, but it is a readonly device: It can be used only to deliver programs and data from the manufacturer to the user, not by the user to store more data. To store large amounts of user data, data tapes (see Figure 7) are commonly used. Like audio and video tape cassettes, data

Figure 7 Tape Backup Drives and Data Tape

Figure 8 A Personal Computer

1.3

The Anatomy of a Computer

tapes contain a long strip of magnetic tape for reading and writing data. Data tapes are inexpensive but slow. To locate data in the middle of the tape, the tape must be wound to the portion containing the dataa much slower task than moving a head across a rotating platter. Some computers are self-contained units, whereas others are interconnected through networks. Home computers are usually intermittently connected to the Internet via a modem. 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. 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. Figure 8 shows a typical personal computer equipped with these devices. The central processing unit, RAM memory, 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 9 shows a motherboard, which contains the CPU, the

Figure 9 A Motherboard

10

Chapter 1.

Introduction

Hard disk Printer Mouse Keyboard Modem Ports Disk controller Floppy disk drive CD-ROM drive Monitor

CPU

Graphics card

RAM

Sound card

Speakers

Network card Bus Computer Computer

Figure 10 Schematic Diagram of a Personal Computer

RAM, and card slots, through which cards that control peripheral devices connect to the bus. Figure 10 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 a CD-ROM, or elsewhere on the network. When a program is started, it is brought into RAM memory, from which the CPU can read it. The CPU reads the program an instruction at a time. As directed by these instructions, the CPU reads data, modies them, and writes them back to RAM memory or the hard disk. Some program instructions will cause the CPU to place dots on the display screen or printer or to vibrate the speaker. As these actions happen many times over and at great speed, the human user will perceive images and sound. Some program instructions read user input from the keyboard or mouse. The program analyzes the nature of these inputs and then executes the next appropriate instructions.

1.3

The Anatomy of a Computer

11

Random Fact 1.1


N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N The ENIAC and the Dawn of Computing The ENIAC (electronic numerical integrator and computer) was the rst usable electronic computer. It was designed by J. Presper Eckert and John Mauchly at the University of Pennsylvania and was completed in 1946two years before transistors were invented. The computer was housed in a large room and consisted of many cabinets containing about 18,000 vacuum tubes (see Figure 11). Vacuum tubes burned out at the rate of several tubes per day. An attendant with a shopping cart full of tubes constantly made the rounds and replaced defective ones. The computer was programmed by connecting wires on panels. Each wiring conguration would set up the computer for a particular problem. To have the computer work on a different problem, the wires had to be replugged. Work on the ENIAC was supported by the U.S. Navy, which was interested in computations of ballistic tables that would give the trajectory of a projectile, depending on the wind

Figure 11 The ENIAC

12

Chapter 1.

Introduction

N N N N N

resistance, initial velocity, and atmospheric conditions. To compute the trajectories, one must nd the numerical solutions of certain differential equations; hence the name numerical integrator. Before machines like ENIAC were developed, humans did this kind of work, and until the 1950s the word computer referred to these people. The ENIAC was later used for peaceful purposes such as the tabulation of U.S. Census data.

1.4

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 programs to run on multiple CPUs without modication, most Java compilers generate a set of machine instructions for a so-called Java virtual machine, an idealized CPU that is then simulated by a program run on the actual CPU. The difference between actual and virtual machine instructions is not important to usall you need to know is that machine instructions are very simple and can be executed very quickly. A typical sequence of machine instructions is 1. 2. 3. Load the contents of memory location 40. Load the value 100. If the rst 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 instruction is encoded as the sequence of numbers 21 40 16 100 163 240 On a processor such as an Intel Pentium, the encoding would be quite different. 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 simplest 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 place the codes manually 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 the computers themselves could be harnessed to help in the programming process.

1.4

Translating Human-Readable Programs to Machine Code

13

The rst step was to assign short names to the commands. For example, iload denotes integer load, bipush means push integer constant, and if_icmpgt means if integers compare greater. Using these commands, the instruction sequence becomes
iload bipush if_icmpgt 40 100 240

That is a lot easier to read for humans. To get the instruction sequences accepted by the computer, though, the names must be translated into the machine codes. Early computers used a computer program called an assembler to carry out these translations. An assembler takes the sequence of characters such as iload, translates it into the command code 21, and carries out similar operations on the other commands. Assemblers have another feature: They can give names to memory locations as well as to instructions. Our program sequence might have checked that some interest rate was greater than 100 percent, and the interest rate was stored in memory location 40. It is usually not important where a value is stored; any available memory location will do. By using symbolic names instead of memory addresses, the program gets even easier to read:
iload intRate bipush 100 if_icmpgt intError

It is the job of the assembler program to nd suitable numeric values for the symbolic names and to put those values into the generated code sequence. Assembler instructions were a major advance over programming with raw machine codes, but they suffer from two problems. It still takes a great many instructions to achieve even the simplest goals, and the exact instruction sequence differs from one processor to another. For example, the above sequence of machine codes is valid only on the Java virtual machine, not on the Pentium or SPARC processor. That is a real problem for people who invest a lot of time and money producing a software package. If a computer becomes obsolete, the program must be completely rewritten to run on the replacement system. In the mid-1950s, higher-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 higher-level description into machine instructions for a particular processor. For example, in Java, the high-level programming language that you will use in this course, you might give the following instruction:
if (intRate > 100) System.out.print("Interest rate error");

This means, If the interest rate is over 100, display an error message. It is then the job of the compiler program to look at the sequence of characters if (intRate > 100) and translate that into 21 40 16 100 163 240

14

Chapter 1.

Introduction

Compilers are quite sophisticated programs. They have to translate logical statements, such as the if, into sequences of computations, tests, and jumps, and they must nd memory locations for variables like intRate. In this course, we will generally take the existence of a compiler for granted. If you become a professional computer scientist, you may well learn more about compiler-writing techniques later in your studies. Higher-level languages are independent of the underlying hardware. For example, the instruction if (intRate > 100) does not rely on particular machine instructions. In fact, it will compile to different code if it is to be run as native code on a Pentium or SPARC processor rather than the Java virtual machine.

1.5

Programming Languages
Programming languages are independent of specic computer architecture, but they are human creations. As such, they follow certain conventions. To ease the translation process, those conventions are much stricter than they are for human languages. When you talk to another person, and you scramble or omit a word or two, your conversation partner will usually still understand what you have to say. Compilers are less forgiving. For example, if you omit the quotation mark close to the end of the instruction,
if (intRate > 100) System.out.print("Interest rate error);

the Java compiler will get quite confused and complain that it cannot translate an instruction containing this error. That is actually a good thing. If the compiler were to try to guess what you did wrong and tried to x it, it might not guess your intentions correctly. In that case, the resulting program would do the wrong thingquite possibly with disastrous effects, if that program controlled a device on whose functions someones well-being depends. When a compiler reads programming instructions in a programming language, it will translate them into machine code only if the input follows the language conventions exactly. Just as there are many human languages, there are many programming languages. Consider the instruction
if (intRate > 100) System.out.print("Interest rate error");

This is how you must format the instruction in Java. Java is a very popular programming language, and it is the one we use in this book. But in Pascal (another programming language that was in common use in the 1970s and 1980s) the same instruction would be written as
if intRate > 100 then write('Interest rate error');

In this case, the differences between the Java and Pascal versions are slight. For other constructions, there will be far more substantial differences. Compilers are languagespecic. The Java compiler will translate only Java code, whereas a Pascal compiler

1.6

The Java Programming Language

15

will reject anything but legal Pascal code. For example, if a Java compiler reads the instruction if intRate > 100 then ..., it will complain, because the condition of the if statement isnt surrounded by parentheses () and the compiler doesnt expect the word then. The choice of the layout for a language construct like the if statement is somewhat arbitrary, and the designers of different languages choose different tradeoffs among readability, easy translation, and consistency with other languages.

1.6

The Java Programming Language


In 1991, a group led by James Gosling and Patrick Naughton at Sun Microsystems designed a 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. 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 wed done: architecture neutral, real-time, reliable, secure. The HotJava browser, which was shown to an enthusiastic crowd at the SunWorld exhibition in 1995, had one unique property: It could download programs, called applets, from the web and run them. Applets, written in the language now called Java, let web developers provide a variety of animation and interaction that can greatly extend the capabilities of a page. (See Figure 12.) In 1996, both Netscape and Microsoft supported Java in their browsers. 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 to the programming language itself, Java has a rich library that makes it possible to write portable programs that can bypass proprietary operating systemsa feature that was eagerly sought by those who wanted to be independent of those proprietary systems and was bitterly fought by their vendors. Some of the early expectations that were placed on the Java language were overly optimistic, and the slogan write once, run anywhere turned into write once, debug everywhere for the early adopters of Java, who had to deal with less-than-perfect implementations. Since then, Java has come a long way, and the Java 2 language and library, released in 1998, promises to bring stability to Java development and to fulll the promise of write once, run everywhere. 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 applets, those applets automatically start 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

16

Chapter 1.

Introduction

Figure 12 An Applet on a Web Page


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 guarantee that no evil applets can be written. As an added benet, 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 benet 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 you the portable code that was generated by the Java compiler. The virtual machine on your computer executes that portable code. Again, there is a benet for the student. You do not have to learn how to write programs for different computers operating systems.

1.7

Becoming Familiar with Your Computer

17

At this time, Java has already established itself 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 two reasons. Because Java was not specically designed for students, no thought was given to make it really simple to write basic programs. A certain amount of technical machinery is necessary in Java to write even the simplest programs. To understand what this technical machinery does, you need to know something about programming. This is not a problem for a professional programmer with prior experience in another programming language, but not having a linear learning path is a drawback for the student. As you learn how to program in Java, there will be times when you will be asked to be satised with a preliminary explanation and wait for a complete details in a later chapter. Furthermore, you cannot hope to learn all of Java in one semester. The Java language itself is relatively simple, but Java contains a vast set of library packages that are necessary to write useful programs. There are packages for graphics, user interface design, cryptography, networking, sound, database storage, and many other purposes. Even expert Java programmers do not know the contents of all of the packagesthey just use those that are needed for particular projects. Using this book, you should expect to learn a good deal about the Java language and about the most important packages. 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.

1.7

Becoming Familiar with Your Computer


For many readers this will be your rst programming course, and you may well be doing your work on an unfamiliar computer system. You should spend some time making yourself familiar with the computer. Because computer systems vary widely, this book can only give an outline of the steps you need to follow. Using a new and unfamiliar computer system can be frustrating, especially if you are on your own. Look for training courses that your campus offers, or just ask a friend to give you a brief tour. Step 1. Login If you use your own home computer, you probably dont need to worry about this step. Computers in a lab, however, are usually not open to everyone. Access is usually restricted to those who have paid the necessary fees and who can be trusted not to mess up the conguration. You will likely need an account number and a password to gain access to the system.

18

Chapter 1.

Introduction

Figure 13 A Startup Screen with Icons

Step 2. Locate the Java Compiler Computer systems differ greatly in this regard. Some systems let you start the compiler by selecting an icon (see Figure 13) or menu. On other systems you must use the keyboard to type a command to launch the compiler. On most personal computers there is a so-called integrated environment in which you can write and test your programs. On other computers you must rst launch one program that functions like a word processor, in which you can enter your Java instructions; then launch another program to translate them to virtual machine instructions; and then run the virtual machine interpreter to carry out those instructions. Step 3. Understand Files and Folders As a programmer, you will write Java programs, try them out, and improve them. You will be provided a place on the computer to store them, and you need to nd out where that place is. You will store your programs in les. A Java le is a container of Java instructions. Files have names, and the rules for legal names differ from one

1.7

Becoming Familiar with Your Computer

19

Figure 14 A Directory Hierarchy

system to another. Some systems allow spaces in le names; others dont. Some distinguish between upper- and lowercase letters; others dont. Most Java compilers require that Java les end in an extension .java; for example, test.java. Java le names cannot contain spaces, and the distinction between upper- and lowercase letters is important. Files are stored in folders or directories. These le containers can be nested. A folder can contain les as well as other folders, which themselves can contain more les and folders (see Figure 14). This hierarchy can be quite large, especially on networked computers, where some of the les may be on your local disk, others elsewhere on the network. While you need not be concerned with every branch of the hierarchy, you should familiarize yourself with your local environment. Different systems have different ways of showing les and directories. Some use a graphical display and let you move around by clicking the mouse on folder icons. In other systems, you must enter commands to visit or inspect different locations. Step 4. Write a Simple Program In the next section, we will introduce a very simple program. You will need to learn how to type it in, how to run it, and how to x mistakes. Step 5. Save Your Work You will spend many hours typing Java programs in and improving them. The resulting program les have some value, and you should treat them as you would

20

Chapter 1.

Introduction

other important property. A conscientious safety strategy is particularly important for computer les. They are more fragile than paper documents or other more tangible objects. It is easy to delete a le by accident, and occasionally les are lost because of a computer malfunction. Unless you kept another copy, you must then retype the contents. Because you probably wont remember the entire le, you will likely nd yourself spending almost as much time again as you did to enter and improve it in the rst place. This costs time, and it may cause you to miss deadlines. It is therefore crucially important that you learn how to safeguard les and get in the habit of doing so before disaster strikes. You can make safety or backup copies of les by saving copies on a oppy or by saving them into another folder.

Productivity Hint 1.1


N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N Backup Copies Backing up on oppy disks is the easiest and most convenient method for most people. If you cant back up onto oppies, you can back up into separate folders on your hard diskbut then you need to back up those folders, typically onto data tape, in case the hard disk dies. Here are a few pointers to keep in mind. N Back up often. Backing up a le takes only a few seconds, and you will hate yourself if you have to spend many hours recreating work that you could have saved easily. I recommend that you back up your work once every thirty minutes, and every time before you run a program that you wrote. Rotate backups. Use more than one oppy disk for backups, and rotate them. That is, rst back up onto the rst oppy disk and put it aside. Then back up onto the second oppy disk. Then use the third, and then go back to the rst. That way you always have three recent backups. Even if one of the oppy disks has a defect, you can use one of the others. The next day, switch to a new set of three. How many simultaneous backups should you keep? It is a tradeoff between convenience and paranoia. I suggest you keep seven sets of three, one set for each weekday. Back up source les only. The compiler translates the les that you write into les consisting of machine code. There is no need to back up the machine code les, since you can recreate them easily by running the compiler again. Focus your backup activity on those les that represent your effort. That way your backup disks wont ll up with les that you dont need. Pay attention to the backup direction. Backing up involves copying les from one place to another. It is important that you do this rightthat is, copy from your work location to the backup location. If you do it the wrong way, you will overwrite a newer le with an older version. Check your backups once in a while. Double-check that your backups are where you think they are. There is nothing more frustrating than to nd out that the backups are not there when you need them. This is particularly true if you use a backup program that stores les on an unfamiliar device (such as data tape) or in a compressed format.

1.8

Compiling a Simple Program

21

N N N N

Relax, then restore. When you lose a le and need to restore it from backup, you are likely to be in an unhappy, nervous state. Take a deep breath and think through the recovery process before you start. It is not uncommon for an agitated computer user to wipe out the last backup when trying to restore a damaged le.

1.8

Compiling a Simple Program


You are now ready to write and run our rst Java program. The traditional choice for the very rst program in a new programming language is a program that displays a simple greeting: Hello, World!. We follow that tradition. Here is the Hello, World! program in Java. Program Hello.java
public class Hello { public static void main(String[] args) { System.out.println("Hello, World!"); } }

We will explain this program in a minute. For now, you should make a new program le and call it Hello.java. Enter the program instructions and compile and run the program, following the procedure that is appropriate for your compiler. By the way, Java is case-sensitive. You must enter upper- and lowercase letters exactly as they appear in the program listing. You cannot type MAIN or PrintLn. On the other hand, Java has free-form layout. Spaces and line breaks are not important, except to separate words. You can cram as many words as possible into each line,
public class Hello{public static void main(String[] args){System .out.println("Hello, World!");}}

or write every word and symbol on a separate line,


public class Hello { public static void main ( String [ ] args )

22

Chapter 1.

Introduction

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

However, good taste dictates that you lay out your programs in a readable fashion, so you should follow the layout in the program listing. When you run the program, the message
Hello, World!

will appear on the screen. On some systems, you may need to switch to a different window to nd the message. Now that you have seen the program working, it is time to understand its makeup. The rst line,
public class Hello

starts a new class. Classes are a fundamental concept in Java. Their primary role is as factories for objects. Objects are another central Java concept, and you will begin to study objects in greater detail in Chapter 3. Right now, think of an object as an item that a program can manipulate. In our rst program, you need not be concerned about classes as object factories. You just want to print a message. Java, like most programming languages, requires that all program statements must be placed inside methods. (In many other programming languages, methods are called functions or procedures, but we will use the Java terminology in this book.) Java, unlike many other languages, further requires that every method must be placed inside a class. In Java, classes are the central organizing mechanism for code. That is why we introduce the Hello class, as the holder of the main method. The keyword public denotes that the class is usable by the public. You will later encounter private features, which are not. At this point, you should simply regard the
public class ClassName { . . . }

as a necessary part of the plumbing that is required to write any Java program. In Java, every source le can contain at most one public class, and the name of the public class must match the name of the le containing the class. For example, the

1.8

Compiling a Simple Program

23

class Hello must be contained in a le Hello.java. It is very important that the names and the capitalization match exactly. You can get strange error messages if you call the class HELLO or the le hello.java. The construction
public static void main(String[] args) { }

denes a method called main. A method is 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, but it will take us until Chapter 3 to learn how to write other methods. The parameter String[] args is a required part of the main methodit contains the so-called command line arguments (which we will not discuss until Chapter 13). The keyword static denotes the fact that the main method does not inspect or change objects of the Hello class. As you will see in Chapter 3, most methods in Java do operate on objects, and the so-called static methods are not common in large Java programs. Nevertheless, main must always be static. At this time, simply consider
public class ClassName { public static void main(String[] args) { . . . } }

as yet another part of the plumbing. For the time being, simply put all instructions that you want to have executed inside the main method of a class.

Java Syntax 1.1 Simple Program


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

Example:
public class Greetings { public static void main(String[] args) { System.out.println("Greetings, Earthling!"); } }

Purpose: To execute a simple program

24

Chapter 1.

Introduction

The instructions or statements in the body of the main methodthat is, the statements inside the curly braces {}are executed one by one. Note that 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 string: to a window, to a le, or to a networked computer on the other side of the world. You need to specify that the destination for the string is the standard outputthat is, a terminal window. The terminal window is represented in Java by an object called out. Just as you needed to place the main method in a Hello class, the designers of the Java library needed to place out in a class. They placed it in the System class, which contains useful objects and methods to access system resources. To use the out object in the System class, you must refer to it as System.out. To use an object such as System.out, you specify what you want to do to it. In this case, you want to print a line of text. The println method (of the PrintStream class) carries out this task. You do not have to implement this methodthe programmers who wrote the Java library already did that for usbut you do need to call the method. Whenever you call a method in Java, you need to specify three items: 1. 2. 3. The object that you want to use (in this case, System.out) The name of the method you want to use (in this case, println) A pair of parentheses, containing any other information the method needs (in this case, ("Hello, World!"))

Note that the two periods in System.out.println have two different meanings. The rst period means locate the out object in the System class. The second period means apply the println method to that object. A sequence of characters enclosed in quotation marks
"Hello, World!"

Java Syntax 1.2 Method Call


object.methodName (parameters) Example:
System.out.println("Good morning!");

Purpose: To invoke a method of an object and supply any additional parameters

1.8

Compiling a Simple Program

25

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 needed 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. 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 afterwards. For example, the output of the two statements
System.out.print("00"); System.out.println(3 + 4);

is the single line


007

Common Error 1.1


N N N N N N N N N N N N N N N N Omitting Semicolons In Java every statement must end in a semicolon. Forgetting to type a semicolon is a common error. It confuses the compiler, because the compiler uses the semicolon to nd where one statement ends and the next one starts. The compiler does not use line ends or closing braces to recognize the end of statements. For example, the compiler considers System.out.println("Hello") System.out.println("World!"); a single statement, as if you had written System.out.println("Hello") System.out.println("World!"); Then it doesnt understand that statement, because it does not expect the word System following the closing parenthesis after "Hello". The remedy is simple. Scan every statement for a terminating semicolon, just as you would check that every English sentence ends in a period.

26

Chapter 1.

Introduction

Advanced Topic 1.1


N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N N Escape Sequences Suppose you want to display a string containing quotation marks, such as Hello, "World"! You cant use System.out.println("Hello, "World""); As soon as the compiler reads "Hello, ", it thinks the string is nished, and then it gets all confused about World followed by two quotation marks. A human would probably realize that the second and third quotation marks were supposed to be part of the string, but compilers have a one-track mind, and if a simple analysis of the input doesnt make sense to them, they just refuse to go on, and they report an error. Well, how do you then display quotation marks on the screen? You precede the quotation marks inside the string with a backslash character. Inside a string, the sequence \" denotes a literal quote, not the end of a string. The correct display statement is therefore System.out.println("Hello, \"World\"!"); The backslash character is used as a so-called escape character, and the character sequence \" is called an escape sequence. The backslash does not denote itself; instead, it is used to encode other characters that would otherwise be difcult to include in a string. Now, what do you do if you actually want to print a backslash (for example, to specify a Windows lename)? You must enter two in a row, like this: System.out.println("The secret message is in C:\\Temp\\Secret.txt"); This statement prints The secret message is in C:\Temp\Secret.txt Another escape sequence occasionally used is \n, which denotes a newline or line feed character. Printing a newline character causes the start of a new line on the display. For example, the statement System.out.print("*\n**\n***\n"); prints the characters * ** *** on three separate lines. Of course, you could have achieved the same effect with three separate calls to println. Finally, escape sequences are useful for including international characters in a string. For e!", with an accented letter example, suppose you want to print "All the way to San Jos e. If you use a U.S. keyboard, you may not have a key to generate that letter. Java uses an encoding scheme called Unicode to denote international characters. For example, the e character

1.9

Errors

27

N N N N N N

has Unicode encoding 00E9. You can include that character inside a string by writing \u, followed by its Unicode encoding: System.out.println("All the way to San Jos\u00E9!"); You can look up the codes for the U.S. English and Western European characters in Appendix 3, and codes for thousands of characters in reference [1].

1.9

Errors
Experiment a little with the Hello program. What happens if you make a typing error such as
System.ouch.println("Hello, World!"); System.out.println("Hello, World!); System.out.println("Hell, World!");

In the rst case, the compiler will complain. It will say that it has no clue what you mean by ouch. The exact wording of the error message is dependent on the compiler, but it might be something like Undened symbol ouch. This is a compile-time error or syntax error. Something is wrong according to the language rules, and the compiler nds it. When the compiler nds one or more errors, it refuses to translate the program to bytecode, and as a consequence you have no program that you can run. You must x the error and compile again. In fact, the compiler is quite picky, and it is common to go through several rounds of xing compile-time errors before compilation succeeds for the rst time. If the compiler nds an error, it will not simply stop and give up. It will try to report as many errors as it can nd, so you can x them all at once. Sometimes, however, one error throws it off track. This is likely to happen with the error in the second line. Because the closing quotation mark is missing, the compiler will think that the ); are still part of the string. In such cases, it is common for the compiler to emit bogus error reports for neighboring lines. You should x only those error messages that make sense to you and then recompile. The error in the third line is of a different kind. The program will compile and run, but its output will be wrong. It will print
Hell, World!

This is a run-time error or logic error. The program is syntactically correct and does something, but it doesnt do what it is supposed to do. The compiler cannot nd the error. You, the programmer, must ush out this type of error. Run the program, and carefully look at its output. 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 nd yourself omitting semicolons or quotes more often than you would like, but the compiler will track down these problems for you. Logic errors are more troublesome. The compiler will not nd themin fact, the compiler will cheerfully translate any program as long as its syntax is correctbut the

28

Chapter 1.

Introduction

resulting program will do something wrong. It is the responsibility of the program author to test the program and nd any logic errors. Testing programs is an important topic that you will encounter many times in this course. Another important aspect of good craftsmanship is defensive programming: structuring programs and development processes in such a way that an error in one place of a program does not trigger a disastrous response. The error examples that you saw so far were not difcult to diagnose or x, 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 difcult. 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 x it. Special software tools (so-called debuggers) let you trace through a program to nd bugsthat is, logic errors. In this course you will learn how to use a debugger effectively. Note that all these errors are different from the kind 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. When a computer adds up numbers, it will get the correct answer. Admittedly, computers can make overow or roundoff errors, just as pocket calculators do when you ask them to perform computations whose result falls outside their numeric range. An overow error occurs if the result of a computation is very large or very small. For example, most computers and pocket calculators overow when you try to compute 101000 . A roundoff error occurs when a value cannot be represented precisely. For example, 1 3 may be stored in the computer as 0.3333333, 1 a value that is close to, but not exactly equal to 1 3 . If you compute 1 3 3 , you may obtain 0.0000001, not 0, as a result of the roundoff error. We will consider such errors logic errors, because the programmer should have chosen a more appropriate calculation scheme that handles overow or roundoff correctly. You will learn a three-part error management strategy in this course. 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 debugging strategies to ush out those errors that remain.

Common Error 1.2


N N N N N N N N N N N Misspelling Words If you accidentally misspell a word, then strange things may happen, and it may not always be completely obvious from the error messages what went wrong. Here is a good example of how simple spelling errors can cause trouble: public class Hello { public static void Main(String[] args) { System.out.println("Hello, World!"); } }

1.10

The Compilation Process

29

N N N N N N N N N N N N N

This code denes a method called Main. The compiler will not consider this to be the same as the main method, because Main starts with an uppercase letter and the Java language is casesensitive. Upper- and lowercase letters are considered to be completely different from each other, and to the compiler Main is no better match for main than rain. The compiler will cheerfully compile your Main method, but when the Java interpreter is ready to read the compiled le, it will complain about the missing main method and refuse to run the program. Of course, the message missing main method should give you a clue where to look for the error. If you get an error message that seems to indicate that the compiler is on the wrong track, it is a good idea to check for spelling and capitalization. All Java keywords use only lowercase letters. Names of classes usually start with an uppercase letter, names of methods and variables with a lowercase letter. If you misspell the name of a symbol (for example, ouch instead of out), the compiler will complain about an undened symbol. That error message is usually a good clue that you made a spelling error.

1.10 The Compilation Process


Some Java development environments are very convenient to use. You just enter the code in one window, click on a button or menu to compile, and click on another button or menu to run your code. Error messages show up in a second window, and the program runs in a third window. Figure 15 shows the screen layout of a popular Java compiler with these features. 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. Even if you use a convenient Java environment, it is useful to know what goes on behind the scenes, mainly because knowing the process helps you solve problems when something goes wrong. In many Java environments, you must set up a project for every program that you want to write. Instructions for this process vary widely between compiler vendors, and you need to read the documentation of your development environment or ask your instructor. You enter the program statements into a text editor. The editor stores the text and gives it a name such as Hello.java. If the editor window shows a name like Noname.java, you should change the name. You should save the le to disk frequently, because otherwise the editor stores the text only in the computers memory. If something goes wrong with the computer and you need to restart it, the contents of the RAM (including your program text) are lost, but anything stored on a hard disk or oppy disk is permanent even if you need to restart the computer. When you compile your program, the compiler translates the Java source code (that is, the statements that you wrote) into so-called bytecode, which consists of virtual machine instructions and some other pieces of information on how to load the program into memory prior to execution. The bytecode for a program is stored in a separate le, with extension .class. For example, the bytecode for the Hello program will be stored in Hello.class.

30

Chapter 1.

Introduction

Figure 15 Screen Layout of an Integrated Java Environment

The bytecode le contains the translation of only the instructions that you wrote. That is not enough actually to run the program. To display a string on a window, quite a bit of low-level activity is necessary. The authors of the System and PrintStream classes (which dene the out object and the println method) have implemented all necessary actions and placed the required bytecodes 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. (More complicated programs are built from more than one bytecode le and more than one library.) A Java interpreter loads the bytecode of the program that you wrote, starts your program, and loads the necessary library bytecode les as they are required. These steps are outlined in Figure 16. The most basic Java tools require you to invoke the editor, compiler, and loader manually, by starting these programs from a command line interface. You would type
edit Hello.java javac Hello.java java Hello

1.11

A First Look at Objects and Classes

31

Source code

Compiler

Bytecode files

Interpreter

Running Program

Libraries

Figure 16 From Source Code to Running Program


to edit and compile the Hello.java le and to execute the resulting program. In a more sophisticated environment, you can achieve the same effect by clicking on menus or toolbar buttons. Your programming activity centers around these steps. You start in the editor, writing the source le. You compile the program and look at the error messages. You go back to the editor and x the syntax errors. When the compiler succeeds, you run the executable le. If you nd an error, you can run the debugger to execute it a line at a time. Once you nd the cause of the error, you go back to the editor and x it. You compile and run again to see whether the error has gone away. If not, you go back to the editor. This is called the editcompiledebug loop (see Figure 17), and you will spend a substantial amount of time in this loop in the months and years to come.

1.11 A First Look at Objects and Classes


Objects and classes are central concepts for Java programming. It will take you some time to master these concepts fully, but since every Java program uses at least a couple of objects and classes, it is a good idea to have a basic understanding of these concepts right away. An object is an entity that you can manipulate in your program, generally by calling methods. For example, System.out refers to an object, and you saw how to manipulate it by calling the println method. (Actually, several different methods are available: all called println, one for printing strings, one for printing integers, one for printing oating-point numbers, and so on.) When you call the println method, some activities occur inside the object, and the ultimate effect is that the object causes text to appear in the console window. For now, you should think of the object as a black box with a public interfacethe methods you can calland a hidden implementationthe code and data that are necessary to make these methods work.

32

Chapter 1.

Introduction

Figure 17 EditCompileDebug Loop

Begin

Edit program

Compile program

Compiler errors? No Test program

Yes

Run-time errors? No End

Yes

Different objects support different sets of methods. For example, the println method can be applied to the System.out object, but it cannot be applied to the string object "Hello, World!". That is, it would be an error to call
"Hello, World!".println(); // This method call is an error

The reason is simple. The System.out and "Hello, World!" objects belong to different classes. The System.out object is an object of the class PrintStream, and the "Hello, World!" object is an object of class String. You can apply the println method to any object of the PrintStream class, but the String class does not support the println method. The String class supports a good number of other methods; you will see many of them in Chapter 2. For example, the length method counts the number of characters in string. You can apply that method to any object of type String. Thus,
"Hello, World!".length(); // This method call is ok

is a correct method callit computes the number 13, the number of characters in the string object "Hello, World!". (The quotation marks are not counted.)

1.11

A First Look at Objects and Classes

33

A class has four purposes: 1. 2. 3. 4. A class species the methods that you can use for objects that belong to the class. A class is a factory for objects. A class is a holding place for static methods and objects. A class denes implementation details: the data layout of the objects and the code for the methods.

In our rst program, you saw the third (and least important) purpose. The Hello class holds the static main method. The System class holds the static out object. To see how a class can be an object factory, let us turn to another class: the Rectangle class in the Java class library. Objects of type Rectangle describe rectangular shapessee Figure 18. Note that a Rectangle object isnt a rectangular shapeit is a set of numbers that describe the rectangle (see Figure 19). Each rectangle is described by the x- and y-coordinates of its top left corner, its width, and its height. To make a new rectangle, you need to specify these four values. For example, you can make a new rectangle with top left corner at (5, 10), width 20 and height 30 as follows:
new Rectangle(5, 10, 20, 30)

The new operator causes the creation of an object of type Rectangle. The process of creating a new object is called construction. The four values 5, 10, 20, 30 are called the construction parameters. Different classes will require different construction parameters. For example, to construct a Rectangle object, you supply four numbers that describe the position and size of the rectangle. To construct a Car object, you might supply the model name and year. Actually, some classes let you construct objects in multiple ways. For example, you can also obtain a rectangle object by supplying no construction parameters at all (but you must still supply the parentheses):
new Rectangle()

This constructs a (rather useless) rectangle with top left corner at the origin (0, 0), width 0 and height 0. Construction without parameters is called default construction.

Figure 18 Rectangular Shapes

34

Chapter 1.

Introduction

Figure 19
Rectangle Objects

Rectangle
x y width height 5 10 20 30

Rectangle
x y width height 45 0 30 20

Rectangle
x y width height 35 30 20 20

Java Syntax 1.3 Object Construction


new

ClassName (parameters)

Example:
new Rectangle(5, 10, 20, 30); new Car();

Purpose: To construct a new object, initialize it with the construction parameters, and return a reference to the constructed object

1.11

A First Look at Objects and Classes

35

To construct any object, you do the following: 1. 2. 3. Use the new operator Give the name of the class Supply construction parameters (if any) inside parentheses

What can you do with a Rectangle object? Not much, for now. In Chapter 4, you will learn how to display rectangles and other shapes in a window. You already know how to print a description of the rectangle object onto the console windowsimply call the System.out.println method:
System.out.println(new Rectangle(5, 10, 20, 30));

This code prints the line


java.awt.Rectangle[x=5,y=10,width=20,height=30]

Or, more specically, this code creates an object of type Rectangle, then passes that object to the println method, and nally forgets that object. Of course, usually you want to do something more to an object than just create it, print it and forget it. To remember an object, you need to hold it in an object variable. An object variable is a storage location that stores not the actual object, but information about the objects locationsee Figure 20. You can create an object variable by giving the name of a class, followed by a name for the variable. For example,
Rectangle cerealBox;

This statement denes an object variable, cerealBox. The type of this variable is Rectangle. In Java, every object variable has a particular type. For example, after the cerealBox variable has been dened by the preceding statement, thereafter in the program it must always refer to an object of type Rectangle, never to an object of type Car or string. However, so far, the cerealBox variable doesnt yet refer to any object at all. It is an uninitialized variable (see Figure 21). To make cerealBox refer to an object, simply set it to another object reference. How do you get another object reference? The new operator returns a reference to a newly created object.

Figure 20
Rectangle

An Object Variable That Refers to an Object

x y width height

5 10 20 30

36

Chapter 1.

Introduction

Figure 21 An Uninitialized Object Variable

cerealBox

cerealBox crispyCrunchyStuff

Rectangle
x y width height 5 10 20 30

Figure 22 Two Object Variables That Refer to the Same Object


Rectangle cerealBox = new Rectangle(5, 10, 20, 30);

It is very important that you remember that the cerealBox variable does not contain the object. It refers to the object. You can have two object variables refer to the same object:
Rectangle crispyCrunchyStuff = cerealBox;

Now you can access the same Rectangle object both as cerealBox and as crispyCrunchyStuff as shown in Figure 22. The Rectangle class has over 50 methods, some useful, some less so. To give you a avor of manipulating Rectangle objects, let us look at a method of the Rectangle class. The translate method moves a rectangle by a certain distance in the x- and y-direction. For example,
cerealBox.translate(15, 25);

moves the rectangle by 15 units in the x-direction and 25 units in the y-direction. Moving a rectangle doesnt change its width or height, but it changes the top left corner. For example, the code fragment
Rectangle cerealBox = new Rectangle(5, 10, 20, 30); cerealBox.translate(15, 25); System.out.println(cerealBox);

1.11

A First Look at Objects and Classes

37

prints
java.awt.Rectangle[x=20,y=35,width=20,height=30]

Lets turn this code fragment into a complete program. As with the Hello program, you need to carry out three steps: 1. 2. 3. Invent a new class, say MoveRectangle Supply a main method Place instructions inside the main method

However, for this program, there is an additional step that you need to carry out: You need to import the Rectangle class from a package, which is a collection of classes with a related purpose. All classes in the standard library are contained in packages. For example, the System class and the String class are in a package called java.lang, and the Rectangle class belongs to the package java.awt. (The abbreviation awt stands for Abstract Windowing Toolkit). The java.awt package contains many classes for drawing windows and graphical shapes. To use the Rectangle class from the java.awt package, simply place the following line at the top of your program:
import java.awt.Rectangle;

You never need to import classes from the java.lang package. All classes from this package are automatically imported. For example, you can use the System and String classes without importing them.

Java Syntax 1.4 Importing a Class from a Package


import

packageName.ClassName ;

Example:
import java.awt.Rectangle;

Purpose: To import a class from a package for use in a program

38

Chapter 1.

Introduction

Thus, the complete program is: Program MoveRectangle.java


import java.awt.Rectangle; public class MoveRectangle { public static void main(String[] args) { Rectangle cerealBox = new Rectangle(5, 10, 20, 30); cerealBox.translate(15, 25); System.out.println(cerealBox); } }

In this section you have had a rst introduction to objects and classes. You saw that each object belongs to a class and that each class denes the set of methods that you can use with all objects of that class. You also learned how to create new objects with the new operator, how to store an object reference in an object variable, and how to import a package. In Chapter 2 you will learn how to use objects of the String class, and you will also learn about a number of other classes that are necessary to read input from the keyboard. In Chapter 3 you will start implementing your own classes.

Advanced Topic 1.2


N N N N N N N N N N N N N N N N N N N N N N N Importing Classes You have seen the simplest and clearest method for importing classes from packages. Simply use an import statement that names the package and class for each class that you want to import. For example, import java.awt.Rectangle; import java.awt.Point; There is a shortcut that many programmers nd convenient. You can import all classes from a package name with the construct import packagename .*; For example, the statement import java.awt.*; imports all classes from the java.awt package. This is less trouble to type, but we wont use this style in this book, for a simple reason. If a program imports multiple packages, and you encounter an unfamiliar class name, then you have to look up all packages to nd the class. For example, suppose you see a program that imports import java.awt.*; import java.io.*;

1.12

Algorithms

39

N N N N N N N N N N N N N N N N N N N N

Furthermore, suppose you see a class name Image. You would not know whether the Image class is in the java.awt package or the java.io package. Why do you care in which package it is? You need to know, if you want to use the class in your own programs. You dont have this problem when using an explicit import statement: import java.awt.Image; Note that you cannot import multiple packages with a single import statement. For example, import java.*.*; // Error is a syntax error. You can avoid all import statements by using the full name (both package name and class name) whenever you use a class. For example, java.awt.Rectangle cerealBox = new java.awt.Rectangle(5, 10, 20, 30); That is pretty tedious, and you wont nd many programmers doing it.

1.12 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 us consider the planning process that precedes the implementation. You may have run across advertisements that encourage you to pay for a computerized service that matches you up with a love partner. Let us think how this might work. You ll 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 nding 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 cant say, Find the best-looking person of the opposite sex who likes inline skating and browsing the Internet. There is no objective standard for good looks, and your brothers opinion (or that of a computer program analyzing the digitized photo) will likely be different from yours. If you cant give instructions for someone to solve the problem by hand, there is no way the computer can magically solve the problem. The computer can do only what you can do by hand. It just does it faster, and it doesnt get bored or exhausted. Now consider the following investment problem:
You put $10,000 into a bank account that earns 5% interest per year. Interest is compounded annually. How many years does it take for the account balance to be double the original?

40

Chapter 1.

Introduction

Could you solve this problem by hand? Sure, you could. For example, after the rst year, you earned $500 (5% of $10,000). The interest gets added to your bank account. Next year, the interest is $525 (5% of $10,500), and your balance is $11,025. You can keep going this way. The following table shows the process:

Year
0 1 2 3 4 ...

Balance
$10,000.00 $10,500.00 $11,025.00 $11,576.25 $12,155.06 ...

You keep going until the balance goes over $20,000. Then you look into the Year column, and you have the answer. Of course, carrying out this computation is intensely boring. You could try to get your younger brother to do it. Seriously, the fact that a computation is boring or tedious is irrelevant to the computer. Computers are very good at carrying out repetitive calculations quickly and awlessly. What is important to the computer (and your younger brother) is the existence of a systematic approach for nding the solution. The answer can be found just by following a series of steps that involves no guesswork. Here is such a series of steps: Step 1. Start with the table

Year
0

Balance
$10,000.00

Step 2.

Repeat steps 2a . . . 2c while the balance is less than $20,000. Add a new row to the table. In column 1 of the new row, put one more than the preceding year value. In column 2 of the new row, place the value of the preceding balance value, multiplied by 1.05 (1 5 percent).

Step 2a. Step 2b. Step 2c. Step 3.

Read the last number in the year column and report it as the number of years required to double the investment.

Chapter Summary

41

Of course, these steps are not yet in a language that a computer can understand, but you will learn soon how to formulate them in Java. What is important is that the method that we described be
N N N

Unambiguous Executable Terminating

The method is unambiguous because there are precise instructions what to do in every step and where to go next. There is no room for guesswork or creativity. The method is executable because each step can be carried out in practice. Had we asked to use a variable rate that depends on economic factors in years to come, not a xed rate of 5 percent per year, our method would not have been executable, because there is no way for anyone to know what that interest rate will be. Finally, the computation will eventually come to an end. With every step, the balance goes up by at least $500, so eventually it must reach $20,000. A solution technique that is unambiguous, executable, and terminating is called an algorithm. We have found an algorithm to solve our investment problem, and thus we can nd the solution with the computer. The existence of an algorithm is an essential prerequisite for programming a task. Sometimes nding an algorithm is very simple. At other times it requires ingenuity or planning. If you cannot nd an algorithm, you cannot use the computer to solve your problem. You need to satisfy yourself that an algorithm exists, and that you understand its steps, before you start programming.

Chapter Summary
1. Computers execute very basic operations in rapid succession. The sequence of operations is called a computer program. Different tasks (such as balancing a checkbook, printing a letter, or playing a game) require different programs. Programmers produce computer programs to make the computer solve new tasks. 2. The central processing unit (CPU) of the computer executes one operation at a time. Each operation species how data should be processed, how data should be brought into the CPU or out of the CPU, or what operation should be selected next. 3. Data values can be brought into the CPU for processing from storage or from input devices such as the keyboard, the mouse, or a communications link. Processed information is sent back from the CPU to storage or to output devices such as the display or a printer. 4. Storage devices include random-access memory (RAM) and secondary storage. RAM is fast, but it is expensive and loses its information when the power is turned

42

Chapter 1.

Introduction

off. Secondary storage devices use magnetic or optical technology to store information. Access time is slower, but the information is retained without the need for electrical power. 5. Computer programs are stored as machine instructions in a code that depends on the processor type. Writing instruction codes directly is difcult for human programmers. Computer scientists have found ways to make this task easier by using assembly language and higher-level programming languages. The programmer writes the programs in such a language, and a special computer program translates it into the equivalent sequence of machine instructions. Assembly language instructions are tied to a particular processor or virtual machine type. Higher-level languages are independent of the processor. The same program can be translated to run on many different processor types from different manufacturers. 6. Programming languages are designed by computer scientists for a variety of purposes. Some languages are designed for specic purposes, such as database processing. In this book, we use Java, a general-purpose language that is suited for a wide range of programming tasks. 7. Set aside some time to become familiar with the computer system and the Java compiler that you will use for your class work. Develop a strategy for keeping backup copies of your work before disaster strikes. 8. Java programs contain one or more classes. Classes contain denitions of methods. A method is a sequence of instructions that describes how to carry out a computation. Every Java application contains at least one class with a method called main. 9. Classes are factories for objects. You construct a new object of a class with the new operator. You store references to objects in object variables. You can have multiple references to the same object. 10. Java classes are grouped into packages. If you use a class from another package (other than the java.lang package), you must import the class. 11. Errors are a fact of life for the programmer. Syntax errors are faulty constructs that do not conform to the rules of the programming language. They are detected by the compiler, and no program is generated. Logic errors are constructs that can be translated into a running program, but the resulting program does not perform the action that the programmer intended. The programmer is responsible for inspecting and testing the program to guard against logic errors. 12. Java programs are translated by a program called a compiler into bytecode. In a separate step, a program called an interpreter reads the bytecode of your program as well as previously translated bytecode for input/output and other services used in your program.

Review Exercises

43

13. An algorithm is a description of steps to solve a problem that is unambiguous, executable, and terminating. That is, the description leaves no room for interpretation, the steps can be carried out in practice, and the result is guaranteed to be obtained after a nite amount of time. In order to solve a problem by computer, you must know an algorithm for nding the solution.

Further Reading
[1] The Unicode Consortium, The Unicode Standard Worldwide Character Encoding, Version 2.0, Addison-Wesley, 1996.

Classes, Objects, and Methods Introduced in This Chapter


Here is a list of all classes, methods, static variables, and constants introduced in this chapter. Please turn to the documentation in Appendix 2 for more information.
java.awt.Rectangle translate java.io.PrintStream print println java.lang.String length java.lang.System out

Review Exercises
Exercise R1.1. Explain the difference between using a computer program and programming a computer. Exercise R1.2. What distinguishes a computer from a typical household appliance? Exercise R1.3. Which parts of a computer can store program code? Which can store user data? Exercise R1.4. Which parts of a computer serve to give information to the user? Which parts take user input? Exercise R1.5. Rate the storage devices that can be part of a computer system by (a) speed, (b) cost, and (c) storage capacity.

44

Chapter 1.

Introduction

Exercise R1.6. Describe the utility of the computer network in your departments computer lab. To what other computers is a lab computer connected? Exercise R1.7. What is the Java virtual machine? Exercise R1.8. What is an applet? Exercise R1.9. Explain two benets of higher-level programming languages over assembler code. Exercise R1.10. List the programming languages mentioned in this chapter. Exercise R1.11. What is an integrated programming environment? Exercise R1.12. On your own computer or on your lab computer, nd the exact location (folder or directory name) of
N N N

The sample le Hello.java, which you wrote with the editor The Java interpreter java.exe The library le rt.jar that contains the runtime library

Exercise R1.13. Explain the special role of the \ escape character in Java character strings. Exercise R1.14. Write three versions of the Hello.java program that have different syntax errors. Write a version that has a logic error. Exercise R1.15. How do you discover syntax errors? How do you discover logic errors? Exercise R1.16. Write an algorithm to settle the following question: A bank account starts out with $10,000. Interest is compounded at the end of every month at 6 percent per year (0.5 percent per month). At the beginning of every month, $500 is withdrawn to meet college expenses after the interest has been credited. After how many years is the account depleted? Exercise R1.17. Consider the question of the preceding exercise. 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. Exercise R1.18. The value of can be computed according to the following formula:

1 1 1 1 1 4 3 5 7 9

Programming Exercises

45

Write an algorithm to compute . Since the formula is an innite series and an algorithm must stop after a nite number of steps, you should stop when you have the result determined up to six signicant digits. Exercise R1.19. Suppose you put your younger brother in charge of backing up your work. Write a set of detailed instructions how he should carry out his task. Explain how often he should do it, and what les he needs to copy from which folder to which oppy disk. Explain how he should verify that the backup was carried out correctly. Exercise R1.20. Explain the difference between an object and an object reference. Exercise R1.21. Explain the difference between an object and a class. Exercise R1.22. Explain the difference between an object and a method.

Programming Exercises
Exercise P1.1. Write a program that displays your name inside a box on the terminal screen, like this:
+----+ |Dave| +----+

Do your best to approximate lines with characters like | - +. Exercise P1.2. Write a program that prints a Christmas tree:
/\ / / \ \

/ \ -------" " " " " "

Remember to use escape sequences to print the \ and " characters. Exercise P1.3. Write a program that computes the sum of the rst 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( ); } }

46

Chapter 1.

Introduction

1 Exercise P1.4. Write a program that computes the sum of the reciprocals 1 1 2 1 10 . This is harder than it sounds. Try writing the program, and check the results against a pocket calculator. The programs results arent likely to be correct. Then write the numbers as oating-point numbers, 1.0, 2.0, . . . , 10.0, and run the program again. Can you explain the difference in the results? We will explain this phenomenon in Chapter 2.

Exercise P1.5. Write a program that constructs a Rectangle object, prints it, and then translates and prints it three more times, so that, if the rectangles were drawn, they would form one large rectangle:

Exercise P1.6. The intersection method computes the intersection of two rectangles that is, the rectangle that is formed by two overlapping rectangles:

Intersection

You call this method as follows:


Rectangle r3 = r1.intersection(r2);

Write a program that constructs two rectangle objects, prints them, and then prints their intersection. What happens when the rectangles do not overlap?

You might also like