+ All Categories
Home > Documents > Introduction to Computer Systems

Introduction to Computer Systems

Date post: 07-Jul-2015
Category:
Upload: achieng-okoth-joseph
View: 153 times
Download: 0 times
Share this document with a friend
293
 Introduction to Computer Systems A computer is a complex system consisting of both hardware and software components. This chapter discusses these components. Chapter Topics: Hardware and Software Components of a Computer System  Networks World-Wide Web Hardware and Software In thinking about The Wizard of Oz , you are thinking about information, no t about something  physical. You would not usually think about the actual material used to store the information (movie film or a DVD) nor about the device which uses the information (a movie projector or a DVD player). A DVD is physical, but the movie itself is intangible information. When you speak of a movie, you usually mean the intangible movie, not a particular device that has a record of it. (Although hu man language is wonderfully flexible; if you were in a video store and someone asked you to hand them "The Wizard of Oz" you would probably hand them the correct DVD.) The word hardware is used for physical devices such as TV sets, DVD players and computers. The word software is used for the information used with such devices: movies, music, novels, web pages, computer programs, and data. When talking about computer systems, hardware means the physical parts of the computer. Software means the programs and data used with the physical co Components of a Computer System Information is funny stuff. The information for the web page you are looking at is recorded on a hard disk inside a computer located in New Britain, Connecticut. The information was copied from that physical device to other physical devices perhaps hundreds of times before it got to your computer where your web browser is using it to display these words on your monitor. Clearly information is something different from the devices used to store and transmit it. A computer system consists of both hardware and information stored on hardware. Information stored on computer hardware is often called software. The hardware components of a computer system are the electronic and mechanical parts.
Transcript
Page 1: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 1/293

 

Introduction to Computer Systems

A computer is a complex system consisting of both hardware and software components. Thischapter discusses these components.

Chapter Topics:

• Hardware and Software• Components of a Computer System•  Networks• World-Wide Web

Hardware and Software

In thinking about The Wizard of Oz , you are thinking about information, not about something physical. You would not usually think about the actual material used to store the information(movie film or a DVD) nor about the device which uses the information (a movie projector or aDVD player). A DVD is physical, but the movie itself is intangible information.

When you speak of a movie, you usually mean the intangible movie, not a particular device thathas a record of it. (Although human language is wonderfully flexible; if you were in a video storeand someone asked you to hand them "The Wizard of Oz" you would probably hand them thecorrect DVD.)

The word hardware is used for physical devices such as TV sets, DVD players and computers.

The word software is used for the information used with such devices: movies, music, novels,web pages, computer programs, and data.

When talking about computer systems, hardware means the physical parts of the computer.Software means the programs and data used with the physical co

Components of a Computer System

Information is funny stuff. The information for the web page you are looking at is recorded on ahard disk inside a computer located in New Britain, Connecticut. The information was copied

from that physical device to other physical devices perhaps hundreds of times before it got toyour computer where your web browser is using it to display these words on your monitor.Clearly information is something different from the devices used to store and transmit it.

A computer system consists of both hardware and information stored on hardware. Informationstored on computer hardware is often called software.

The hardware components of a computer system are the electronic and mechanical parts.

Page 2: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 2/293

 

The software components of a computer system are the data and the computer programs.

Click Here to see the desktop system these notes were originally prepared on. (This was back when anything to do with computers had to be beige. Everything in this picture has since beenreplaced, except for the gargoyle.)

The major hardware components of a computer system are:

• Processor • Main memory• Secondary memory• Input devices• Output devices

For typical desktop computers, the processor, main memory, secondary memory, power supply,and supporting hardware are housed in a metal case. Many of the components are connected to

the main circuit board of the computer, called the motherboard . The power supply supplies power for most of the components. Various input devices (such as the keyboard) and outputdevices (such as the monitor) are attached through connectors at the rear of the case.

Hardware Components

The terms input and output say if data flow into or out of the computer. The picture shows themajor hardware components of a computer system. The arrows show the direction of data flow.

A bus is a group of wires on the main circuit board of the computer. It is a pathway for dataflowing between components. Most devices are connected to the bus through a controller whichcoordinates the activities of the device with the bus.

The processor is an electronic device about a one inch square, covered in plastic. Inside thesquare is an even smaller square of silicon containing millions of tiny electrical parts. A

Page 3: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 3/293

 

 processor may contain 100 million transistors. It does the fundamental computing within thesystem, and directly or indirectly controls all the other components.

The processor is sometimes called the Central Processing Unit or CPU. A particular computer will have a particular type of processor, such as a Pentium chip or a SPARC chip.

Memory

The processor performs all the fundamental computation of the computer system. Other components contribute to the computation by doing such things as storing data or moving datainto and out of the processor. But the processor is where the fundamental action takes place.

A processor chip has relatively little memory. It has only enough memory to hold a fewinstructions of a program and the data they process. Complete programs and data sets are held inmemory external to the processor. This memory is of two fundamental types: main memory, and

secondary memory.

Main memory is sometimes called volatile because it looses its information when power isremoved. Secondary memory is usually nonvolatile because it retains its information when power is removed. (However, it needs power when information is stored into memory or retrieved from it.)

• Main memory: 

o closely connected to the processor.o stored data are quickly and easily changed.

o holds the programs and data that the processor is actively working with.

o interacts with the processor millions of times per second.

o needs constant electric power to keep its information.

• Secondary memory: o connected to main memory through the bus and a controller.

o stored data are easily changed, but changes are slow compared to main memory.

o used for long-term storage of programs and data.

o  before data and programs can be used, they must be copied from secondary

memory into main memory.o does not need electric power to keep its information.

Main Memory

Page 4: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 4/293

 

Main memory is where programs and data are kept when the processor is actively using them.When programs and data become active, they are copied from secondary memory into mainmemory where the processor can interact with them. A copy remains in secondary memory.

Main memory is intimately connected to the processor, so moving instructions and data into and

out of the processor is very fast. Main memory is sometimes called RAM. RAM stands for Random Access Memory. "Random" means that the memory cells can be accessed in any order.

When people say that a computer has "512 megabytes of RAM" they are talking about how bigits main memory is. One megabyte of memory is enough to hold approximately one million (10 6)characters of a word processing document. (There will be more about bytes and megabytes later on in these notes.)

 Nothing permanent is kept in main memory. Sometimes data are placed in main memory for justa few seconds, only as long as they are needed.

QUESTION 6:

Imagine that you are using a computer to write a book report on Tom Sawyer .

• Where is the word processor program that you are running located?• Where are the characters you have typed?

Secondary Memory

Secondary memory is where programs and data are kept on a long-term basis. Commonsecondary storage devices are the hard disk and optical disks.

•  The hard disk has enormous storage capacity compared to main memory.•  The hard disk is usually contained inside the case of a computer.•  The hard disk is used for long-term storage of programs and data.• Data and programs on the hard disk are organized into files.• A file is a section of the disk that has a name.

A hard disk might have a storage capacity of 500 gigabytes (room for about 500 x 109

characters). This is about 100 times the capacity of main memory. A hard disk is slow compared

to main memory. If the disk were the only type of memory the computer system would slowdown to a crawl. The reason for having two types of storage is this difference in speed andcapacity.

Large blocks of data are copied from disk into main memory. The operation is slow, but lots of data is copied. Then the processor can quickly read and write small sections of that data in mainmemory. When it is done, a large block of data is written to disk.

Page 5: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 5/293

 

Often, while the processor is computing with one block of data in main memory, the next block of data from disk is read into another section of main memory and made ready for the processor.One of the jobs of an operating system is to manage main storage and disks this way.

Primary memory Secondary memory

• Fast• Expensive• Low capacity

• Works directly with theprocessor

• Slow• Cheap• Large capacity

• Not connected directly to theprocessor

QUESTION 7:

Say that you have purchased the game Doom IV and have installed it on your computer. Thegame consists of 

• A program (that controls the action of the game)• Data (the images and other information)

After installation, where is each of these parts located in your computer system?

After you have installed the game, where are its parts located?

Answer:

• A programo On the hard disk

• Datao On the hard disk

When you play the game, its various parts are copied from the hard disk into main memory asneeded.

Input and Output Devices

Input and output devices allow the computer system to interact with the outside world by movingdata into and out of the system. An input device is used to bring data into the system. Some inputdevices are:

Page 6: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 6/293

 

• Keyboard• Mouse• Microphone• Bar code reader• Graphics tablet

An output device is used to send data out of the system. Some output devices are:

• Monitor• Printer• Speaker

A network interface acts as both input and output. Data flows from the network into thecomputer, and out of the computer into the network.

QUESTION 8:

Do you think that data transfer from the network is slower or faster than from main memory?

Answer:

Data transfers from the network are much slower than from main memory and even slower thanfrom hard disk.

I/O

Input/output devices are usually called I/O devices. They are directly connected to an electronicmodule attached to the motherboard called a device controller. For example, the speakers of amultimedia computer system are directly connected to a device controller called an audio card,which in turn is plugged into a bus on the motherboard.

Sometimes secondary memory devices like the hard disk are called I/O devices (because theymove data in and out of main memory). What counts as an I/O device depends on context. To auser, an I/O device is something outside of the computer case. To a programmer, anything

outside of the processor and main memory is an I/O device. To an engineer working on thedesign of a processor everything outside of the processor is an I/O device.

QUESTION 9:

Is a game controller an input device or an output device?

Page 7: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 7/293

 

Answer:

Input. (Although some game controllers have tactile feedback and so are output devices as wellas input devices.)

Embedded Systems

A computer system that is part of a larger machine and which controls how that machineoperates is an embedded system. Usually the processor constantly runs a single control programwhich is permanently kept in ROM (Read Only Memory).

The overwhelming majority of processor chips are used in embedded systems. Only 0.2% of  processor chips are used in the familiar desktop computer!

A typical embedded system is a cell phone. This is obvious, but there are many less obviousembedded systems. Your car contains dozens of processors, and even more in the audio system.For instance, each airbag is controlled by its own computer chip.

QUESTION 10:

Your automobile engine is controlled by a computer. Do you think that this computer has:

Input devices?• Output devices?• Main storage?• Secondary storage?

Answer:

Does the computer controlling an automobile engine have:

• Input devices? Yes — various sensors throughout the car deliver data to thecomputer.

• Output devices? Yes — various actuators (that perform actions) arecontrolled by the computer.

• Main storage? Yes — ROM holds the program and there must be enough RAMto hold the current data and results.

• Secondary storage? No — Hard disks do not hold up well next to a carengine.

Page 8: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 8/293

 

Software

Computer software consists of both programs and data. Programs consist of instructions for the processor. Data can be any information that a program needs: character data, numerical data,

image data, audio data, and countless other types. The distinction between programs and data isnot as clear-cut as you might think, however.

Fundamental Idea: Both programs and data are saved in computer memory in the same way.The electronics of computer memory (both main memory and secondary memory) make nodistinction between programs and data.

The insight that both programs and data can be saved using the same electronic methods is animportant concept in computer science. Computer systems use memory for either programs or data, as needed.

QUESTION 11:

Which of the following can be saved on a disk?

• A game program• Accounting data (numbers)• Audio data• Graphics data• Digital photographs• Video data

Answer:

Everything on the list can be stored on a disk (or on any other kind of computer memory, for thatmatter).

Types of Programs

There are two categories of programs. Application programs (usually called just "applications")

are programs that people use to get their work done. Computers exist because people want to runthese programs. Systems programs keep the hardware and software running together smoothly.The difference between "application program" and "system program" is fuzzy. Often it is more amatter of marketing than of logic.

The most important systems program is the operating system. The operating system is always present when a computer is running. It coordinates the operation of the other hardware andsoftware components of the computer system. The operating system is responsible for starting up

Page 9: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 9/293

 

application programs, running them, and managing the resources that they need. When anapplication program is running, the operating system manages the details of the hardware for it.For example, when you type characters on the keyboard, the operating system determines whichapplication program they are intended for and does the work of getting them there.

Some embedded systems do not use an operating system, but run their programs directly on the processor.

Modern operating systems for desktop computers come with a user interface that enables usersto easily interact with application programs (and with the operating system itself) by usingwindows, buttons, menus, icons, the mouse, and the keyboard. Examples of operating systemsare Unix, Linux, Windows XP, and System 10.

Application Programs Systems Programs

• Word processors• Game programs• Spreadsheets• Data base

systems• Graphics

programs

• Web browsers

• Operating system• Networking system• Programming language

software• Web site server

• Data backup

QUESTION 12:

(Thought question:) Imagine that you have just turned on your computer and have not yet startedany application. Are any programs running?

Answer:

Yes—the operating system is running. Mostly it is managing the user interface, waiting for someinput to tell it what to do.

Operating Systems

An operating system is a complex program that keeps the hardware and software components of a computer system coordinated and functioning. It is like the owner of a small shop, who keepseverything in order by attending to customers, accepting deliveries, stocking the shelves, doing

Page 10: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 10/293

 

the bookkeeping, and so on. The shopkeeper must promptly attend to tasks as they arise. Withoutthe shopkeeper the shop could not function.

Most computer systems can potentially run any of several operating systems. For example, mostPentium-based computers can run either Linux or a Windows operating systems. Usually only

one operating system is installed on a computer system, although some computers have several.In any case, only one operating system at a time can be in control of the computer system. Thecomputer user makes a choice when the computer is turned on, and that operating systemremains in control until the computer is turned off.

QUESTION 13:

(Review:) What component of a computer system holds the operating system when the computer is not running?

Answer:

The hard disk. The hard disk is used for long-term storage of all software, including theoperating system.

Starting a Program

When a computer is first started, the hardware automatically loads the operating system andstarts it running. This process is called booting. The reason for this odd term is that the operatingsystem is itself involved in getting itself running—a process that is like someone "pullingthemselves up by their bootstraps". Once the operating system is running, it is used to start upapplication programs.

Here is a (simplified) list of what happens when the user (you) starts up an application. Assumethat the operating system (OS) is already running.

1. The user asks to run an application.o  This is done by clicking on an icon, making a menu choice, or by other

means.2. The OS determines the name of the application.3. The OS finds the files on the hard disk where the application and its data are

stored.4. The OS finds an unused section of main memory that is large enough for the

application.5. The OS makes a copy of the application and its data in that section of main

memory.

Page 11: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 11/293

 

o  The software on the hard disk is unchanged; main memory holds acopy of what is on disk.

6. The OS sets up resources for the application.7. Finally, the OS starts the application running.

As the application runs, the OS is there in the background managing resources, doing input andoutput for the application, and keeping everything else running.

QUESTION 14:

(Thought Question: ) When an application stops running, do you think that it is copied frommain memory back to the hard disk?

Answer:

 No. The hard disk already has a copy, and that copy will be used the next time the application isrun.

Networks

A computer network consists of two or more computers connected so that they can exchangedata and programs. When a computer is a member of a network, the programs it runs and thedata it uses can be on the hard disk of some other computer on the network. In business andindustrial settings, most computers are on a network. The operating system that runs on anetworked computer must manage its share of the network (along with managing all its other responsibilities). The operating system is able to find programs and data that are stored on other network computers, and copy them into its own main memory.

In a local-area network only a few dozen computers are connected together, usually all locatedwithin the same building. Each computer has a network address that the other computers use toaccess it. Usually the computers share a printer. There may be an especially powerful computer called a server whose hard disk holds application programs and data that the other computers areexpected to need.

Each computer in a network has a network interface card. This is an input/output device thatsends and receives data over cables. The network interface cards of computers on a network areconnected together with cables.

Page 12: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 12/293

 

QUESTION 15:

Can a local area network be implemented using radio waves instead of cables?

Answer:

Yes.

Wide-Area Networks

Large organizations need to connect many more computers than can be handled with a local areanetwork. A wide-area network can connect thousands of computers together over greatdistances. The long distance connections are made by using optical fiber, telephone lines,

microwave radio, and satellite communications. Each computer in the network has a network address (as with local-area networks) to uniquely identify it.

Wide-area networks use a variety of special hardware to manage the flow of data. When twocomputers share data, this hardware makes it appear that the two computers are connectedtogether directly. In reality, there may be dozens of network devices between the two computers.

All these devices use the same method for dealing with data. Without a common method of dealing with data, a large network would become a hopeless muddle. An agreement about how torepresent and transmit data over a network is called a protocol. Usually large networks use a protocol called TCP/IP (for transmission control protocol / internet protocol).

QUESTION 16:

(Thought Question: ) When two computers communicate must they both use the same protocol?

Answer:

Yes. There are several protocols available, but when two computers communicate they mustagree on which one to use.

Internet

The Internet consists of many networks that have been connected together to form one hugeworldwide network. Even on this huge network, each computer must have a unique network 

Page 13: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 13/293

 

address, called an IP address, much like each telephone in the world has a unique telephonenumber (including the country code and area code).

Here a typical IP address:

149.152.18.25

IP addresses actually are 32-bit binary numbers. Networking equipment uses these addresses toroute information over the network. The above example shows the standard way of writing these bits using decimal digits.

But even when written in decimal the address is not clear to humans. One of the features of theWorld Wide Web is that it allows humans to use computer names rather than numbers. Here isa typical computer name:

chortle.ccsu.edu

This computer name corresponds to the above IP address. When you use it in a Web browser it isconverted into the 32 binary digits of the computer's IP address.

As an experiment, enter the above IP address into the address field of your browser and hitreturn. Now do the same with the computer name. You will get to the same web page with each.

QUESTION 17:

(Thought Question: ) With so many computers connected to the Web, do you suppose that there

is trouble giving each computer its own address?

Answer:

Yes. The Web is running out of addresses. The next generation of Internet hardware andsoftware will fix this (and other) problems.

World Wide Web

Remember that important idea (discussed several pages back):

Fundamental Idea: Both programs and data are saved in computer memory in the

same way. The electronics of computer memory (both main memory and secondary

memory) make no distinction between programs and data.

Page 14: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 14/293

 

Communications equipment makes no distinction between programs and data, either. It is allinformation as far as it is concerned, and all information is transmitted the same way. TheInternet is like a worldwide package delivery service. It is concerned with moving packages fromone address to another, without concern about what is in the packages.

The Internet provides the hardware and the information transmission protocols for the World-

Wide Web. Data intended for the Web is transmitted over the Internet just like any data. Whatmakes Web data special is that it is intended for Web browsers (such as the one you are probablylooking at). A browser is a program that can read Web pages and display them in a nicelyformatted way.

A Web page is a package of data that contains information on how it is to be displayed on amonitor. This information is given using a language called Hypertext Markup Language

(HTML). If you want to see an example of this, left-click on View in the menu at the top of your Web browser, then left-click on Source. This will bring up a new window with the HTML of this

 page in it. After you are done viewing, close the window by clicking on the close button in itsupper right corner (the button marked with X).

QUESTION 18:

Can programs, as well as data, be exchanged over the Internet?

Answer:

Yes.

Recall the fundamental idea, that programs and data are saved in the same fashion. They bothcan be transmitted over the Internet in the same fashion, too.

Hyperlinks

Page 15: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 15/293

 

One Web page is connected to another with a hyperlink . If you have been reading these notesover the Web, you have been linking between Web pages by using hyperlinks.

A Web browser usually displays a hyperlink in a distinguishing color (usually blue). When youclick on it, the browser asks the operating system to get a particular Web page from another 

computer connected to the Internet.

The Web page to get is specified with a uniform resource locator URL. A URL specifies theexact computer (among all the Internet computers in the world) and the exact Web page on thatcomputer.

To see some examples of URLs, keep watching the box at the top of your browser labeled"Address".

QUESTION 19:

When you click on the following hyperlink, will the URL in the address box change?

End of the Chapter

This ends the general overview of computer systems. At this point, you should have an idea of what computer systems are all about. But you will likely be uncertain about quite a few things.

The following chapters will clarify some topics, and others will remain mystifying until later 

courses. For now, you may wish to review the following. Click on a subject that interests you togo to where it was discussed.

• Hardware and software. • Major hardware components of a computer system• Types of memory• Characteristics of a hard disk. • I/O devices• Two categories of programs•

The operating system. • How programs start running. • Computer networks

revised: 01/18/99, 01/16/00, 09/01/01, 01/08/06

Page 16: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 16/293

 

CHAPTER 2 — Analog and Binary Signals

Everyone knows that computers are "digital" and that they use "binary" numbers. You probablyhave some idea of what these terms mean. But we need to be clear about their precise meaningand to be clear about why computers are digital.

Chapter Topics:

• Binary signals• Analog signals• Advantages of Binary•

Bits• Noisy signals

Study these topics carefully if you want to know what is really going on with computers.

QUESTION 1:

Why is a digital wristwatch called "digital"?

Answer:

Because it shows time using definite digits, rather than positions of hands that have to bemeasured. (It would be less correct to say "because it has a computer inside".)

Binary

Binary means "two states." The two states are sometimes called "1" and "0", or called "true" and"false", or called "on" and "off", (or other names.) The essential characteristic is that a single binary device can be in just one of two possible states.

A bit is a single "on/off" value.

A good example is a toggle switch, such as a light switch. You can turn it "on" or "off" but not(in normal operation) anything else. A light switch holds one bit of information.

Page 17: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 17/293

 

A light dimmer is not a binary device: it has many positions between "off" and "fully on". If youwant a light dimmer to be set to 25%, you must carefully adjust it.

QUESTION 2:

Which of the following is a binary device:

•  The ignition switch of an automobile.•  The hour hand of a clock.• A button on a hand calculator.•  The volume control on a stereo.

Answer:

•  The ignition switch of an automobile. No•  The hour hand of a clock. No• A button on a hand calculator.  Yes•  The volume control on a stereo. No

Why Computers use Binary

The ignition switch of an automobile is discrete — it has definite states—but there are usuallymore than two states (off, running, start, acc...) A button on a electronic calculator is a binarydevice. It is either on or off. Ordinarily it is "off." When you push it, it is "on." It springs back to"off" when you release it, which is different from a toggle switch, but it still is a binary device.

There are many advantages to binary. Here are four (somewhat overlapping) important reasonsfor using binary:

1. Simple; easy to build.2. Unambiguous signals (hence noise immunity).3. Flawless copies can be made.

4. Anything that can be represented with some sort of pattern can berepresented with patterns of bits.

These characteristics of binary were realized by Claude Shannon, a mathematician at BellTelephone Laboratories. His 1948 paper  A Mathematical Theory of Communication is thefoundation of information theory and much of computer science.

Page 18: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 18/293

 

QUESTION 3:

Which is easier to build:

• An on/off switch.•

A light dimmer.

Advantage of Binary 1: Simple; easy to build

An on/off switch is simple and easy to build. An on/off switch moves two pieces of metal

together or moves them apart. A light dimmer must gradually and smoothly change the currentthat reaches the light. It has more components that an on/off switch and must be carefullyassembled. An accurate dimmer (where 25% means exactly 25%) is even harder to build.

The same is true for the tiny devices inside of a silicon chip. On/off switches are relatively easyto fabricate. Easy to build means that the devices are cheap, small, and reliable, and millions of them can be put in a small area.

QUESTION 4:

Which of the following methods for producing books is simple and easy?

• Each book is individually made by scratching marks onto tablets of wet clay.• Each book is individually made by copying the characters onto paper with

pen and ink.• Many copies of the book are made by carving flat wooden blocks with the

text then printing the text on paper.

Page 19: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 19/293

 

• Many copies of the book are made by setting movable type and printing thetext on paper.

Answer:

Setting type.

Simplicity

Carving a block of wood into a book page requires great technical and artistic skill. The task iscomplex and labor intensive. A small mistake might ruin the whole block. The Renaissancewoodcarvers were as skilled as woodcarvers ever have been.

Setting type is comparatively easy. Little artistic or technical skill is needed. Individual pieces of type are just dropped into place. The method is robust and reliable; mistakes can be corrected.The type can be reused many times.

It is a paradox that advances in technology often lead to simple methods. Woodcarving iscomplex; setting type is easy. The computer revolution (ca. 1950—) is often compared to theGutenberg revolution (ca. 1450—).

QUESTION 5:

Which is easier to do: (a) determine exactly how bright a light is, or (b) decide if it is on or off 

Advantage of Binary 2: Unambiguous Signals

Page 20: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 20/293

 

Here again are the advantages of binary:

1. Simple; easy to build.2. Unambiguous signals (hence noise immunity).3. Flawless copies can be made.4. Anything that can be represented with patterns can be represented with

patterns of bits.

Unambigous Signals: Consider Paul Revere, waiting for news of the attack of the British troops.

He is expecting to see a signal lantern in the tower of Old North Church telling him how theBritish are attacking:

1.32456 if by land, 1.71922 if by sea.

The signal shines out! ...and Paul Revere's famous ride is delayed for several hours as he tries tofigure out just how bright that signal is.

Lack of ambiguity is a tremendous advantage. The signal that Paul Revere was actually waitingfor that night in 1775 was:

One (lantern) if by land, and two (lanterns) if by sea.

...an easily interpreted signal. All Paul Revere had to do was count. Such signals are calleddiscrete because they have a fixed number of definite states. Sometimes the word digital is usedto mean the same thing.

Page 21: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 21/293

 

QUESTION 6:

Why can a Chinese abacus be regarded as a "digital computer."

Answer:

The computation is done by moving beads into definite positions. A bead is either placed whereit counts as part of a number, or it is placed where it does not count. This "all or nothing"operation means that an abacus is a discrete device.

An Analog Signal

An analog signal may continuously change in value. Its values can be anything within a range of values, and its exact value at any time is important. The graph represents an audio signal. Theexact value at each time is part of the information it contains. For example, the value at time

"T2" must be measured exactly.

 Now say that you are observing the voltage of a wire. It has been agreed that any voltage below athreshold will be counted as an "off" signal, and that any value above the threshold will becounted as an "on" signal.

Page 22: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 22/293

 

QUESTION 7:

At time "T2", is the signal "on" or "off"?

Answer:

ON. The analog signal (continuously changing voltage signal) moves up and down, but at time"T2" it is clear that it is above the threshold. Exact measurement is not needed.

Binary Signal

Analog signals usually continuously change their value. The information they convey iscontained in the exact value at any instant.

However, by using a threshold, a signal can represent binary data ("on/off" data). Such a signal is

called binary signal.

It is easy and fast (for electronics, as well as for humans) to determine if a voltage is above or  below a threshold. The figure shows a signal that transmits "off" then "on". (The signal isexamined at times T1 and T2.)

Page 23: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 23/293

 

QUESTION 8:

Is is clear that the signal is "off" at time T1 and "on" at time T2?

Answer:

Yes.

Imperfect Transmission

Page 24: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 24/293

 

The "ons" and "offs" of previous signal are clear. But what if the signal is sent down a long wireand someone nearby turns on a vacuum cleaner? The graph shows the signal at the other end of the wire.

Even though the signal is noisy (at the analog level), the binary values are transmitted perfectly.

You (and the electronics) can still tell that at time T1 the signal represents "off" and that at timeT2 the signal represents "on" The receiving end just needs to get the binary values.

Since only the "on" "off" information matters, the analog noise is irrelevant, and the originalsignal is received perfectly (so far as the binary information goes.)

QUESTION 9:

If the signal were regarded as an analog signal, and exact values were important, would some

information present in the first signal (before the noise) have been lost?

Answer:

Yes—if the signals represented a singer's voice, the noisy signal would sound, er.. well... noisy.After just one copy, information has been lost.

Advantage of Binary 3: Flawless copies can

be made.

Page 25: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 25/293

 

Review the advantages of binary: 

1. Simple; easy to build.2. Unambiguous signals (hence noise immunity).

3. Flawless copies can be made.4. Anything that can be represented with some sort of pattern can be

represented with patterns of bits.

Flawless copies can be made: The receiving end of the signal is only interested in the binaryvalues. All it has to do it check if the signal is above or below the threshold. This can be done perfectly (as long as the noise is not too great.) For example, here is the noisy signal with the"on"/"off" values recovered from it:

The original signal has been recovered flawlessly. This process can occur as many times asneeded with a perfect copy made each time. This is essential in a computer system, where bit

 patterns (patterns of one and zero, or on and off) are copied back and forth between the processor and memory millions of times a second. The copies have to be perfect.

Page 26: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 26/293

 

QUESTION 10:

Something might be wrong here. Is the signal is "on" or "off" at the time "x"? This is not easy totell. What is worse, a different amount of noise changes the answer. What can be done about this problem? (Hint: must the value of the signal be known at all times?)

Answer:

The system is built so that the signal is tested only at particular times, and that changes in thesignal occur between these times.

Clocks

Digital systems are built so that the "on" "off" (binary) value is only tested at certain times,giving the wire (or transistor, or...) a chance to change its state between these times. This is whycomputer systems have a "clock" — to keep all these times synchronized. So faster clocks meanwires can be tested more times per second, and the whole system runs faster.

Processor chips (and the computers that contain them) are often described in terms of their clock speed. Clock speed is measured in Hertz, where one Hertz is one clock tick per second. Thesymbol MHz means megahertz, a million (106) clock ticks per second.

A 700 MHz Pentium processor checks binary values 700 million times in each second. In between these times values are allowed to change and settle down. The faster a processor chip is,

the more times per second values can be tested, and the more decisions per second can be made.

Recent processor chips have clock speeds measured in gigahertz, GHz, which is a billion (109)clock ticks per second.

QUESTION 11:

Which is faster, a 400 MHz Pentium processor or a 800 MHz Pentium processor?

Answer:

The 800 MHz processor, since it checks values 800 million times per second (twice as many asthe 400 MHz processor).

(However, if the processors are different types there are other factors besides clock speed thatdetermine how much each processor can do in a second.)

Page 27: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 27/293

 

Advantage of Binary 4: Representing

AnythingRecall that last advantage of binary:

• Anything that can be represented with patterns can be represented withpatterns of bits.

Since data of all kinds is stored in computer memory (main and secondary) using the sameelectronic methods, this means that endless perfect copies can be made of any type of data or  program.

This idea is that any system of symbols can be translated into bit patterns. An example is howEnglish characters are represented as eight-bit patterns. The agreement about what patternsrepresent what characters is called ASCII. The hardware and the software of a computer system(usually) follow this agreement when the data is "text". (You will learn more about this later).Other types of data (non-character data) are represented using other methods.

QUESTION 12:

Can characters from alphabets other than English be represented?

Answer:

Of course. Any type of symbol at all can be assigned a binary pattern to represent

it.

More on Representing Anything in Binary

Japanese and Chinese characters, also, have been translated into bit patterns, and computers canmanipulate those symbols just as easily as ASCII. Unicode is an agreement created by aninternational committee on how to represent characters using 16 bits. Here are 16 bits

111110011111110 and here is the character it represents in Unicode:

Say that the international committee decides to represent a new Chinese character. How can theydo this? Easy: they find a bit pattern not yet used to represent any symbol and assign the newcharacter to that pattern.

Page 28: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 28/293

 

The correspondence between human language symbols and bit patterns is arbitrary. All you haveto do is be sure that you are using enough bits so that all the symbols of the language have aunique bit pattern to represent them.

QUESTION 13:

Can printed music be represented using binary?

Answer:

Sure — any symbols can. There are "music processor" programs for printed music that work likeword processor programs for printed text.

Symbols and Patterns

Recall that last advantage of binary:

• Anything that can be represented with patterns can be represented withpatterns of bits.

What about representing things other than the written characters of a language? This is a deeptopic, and entire books have been written on it. Here is a very sloppy discussion: Pick some

subject. Use English sentences to describe it. Represent those sentences in ASCII (charactersencoded as byte patterns.) Now the subject is represented in binary. If something can berepresented in English, then it can be represented in binary.

 Notice that this says nothing about "meaning" or "understanding." Printed books don'tunderstand their own contents. A digital version of the book (say on CD ROM) doesn'tunderstand the book, either. It mearly holds the information, waiting for a human mind to do theunderstanding. However the book has been represented as bit patterns.

 Nobody said that binary representations are easy to use. Some representation methods are veryuseful for computers (for instance, using binary patterns to represent numbers), others are nearly

usless. Much of the work that computer scientists do is figuring out how to represent things using binary in ways that are useful. For example, much work has been done in the last ten years infiguring out how best to represent image and audio data.

Important Point:

Computer memory (of all types) holds bit patterns, and nothing else. What those bit

patterns represent depends on how they are used.

Page 29: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 29/293

 

QUESTION 14:

Sometimes people say, "A computer only works with numbers. It doesn't understand anything

else." Do you think that this is correct?

Answer:

 No. Any type of symbolic data can be represented using binary, not just numbers. At theelectronic level, everything is a bit pattern (which some people call a "number"), so the statementis sort-of correct.

End of this chapter.You may wish to review the following terms. Click on the hypertext phrase to go the page wherethe term was discussed.

• What "binary" means. • What a "bit" is. •  The advantages of using binary in a computer.• What "analog" means. • How thresholds are used. •  The master clock of a computer. • Memory contents as bit patterns. 

You have reached the end of the chapter.

CHAPTER 3 — Computer Memory

Chapter Topics:

• Bits and Bytes• Kilobytes, megabytes, gigabytes• Main memory and addresses• Secondary memory• Files

Recall from chapter one that the major hardware components of a computer system are:

• Processor

Page 30: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 30/293

 

• Main memory• Secondary memory devices• Input/output devices

This chapter looks at main and secondary memory.

QUESTION 1:

(Educated Guess: ) If you bought a new computer, about how much main memory would youexpect it to have: 200 bytes, 2 kilobytes, 2 megabytes, or 2 gigabytes?

Answer:

A new desktop computer should have at least 2 gigabytes, and more if possible. Top-end PCshave up to 12 gigabytes of main memory (as of 2010).

Characteristics of Computer Memory

Main memory is as vital as the processor chip to a computer system. Fast computer systems have both a fast processor and a large, fast memory. Here is a list of some characteristics of computer memory. Some characteristics are true for both kinds of memory; others are true for just one.

Characteristic

True for

Main

Memory

True for

Secondary

Memory

Very closely connected to

the

processor.

Holds programs and data

that the

processor is actively

working with.

Used for long term storage.

 The processor interacts

with it

millions of times per

second.

Page 31: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 31/293

 

 The contents is easily

changed.

Relatively low capacity.

Relatively huge capacity.

Fast access.

Slow access.

Connected to main

memory.

Holds programs and data.

Usually its contents are

organizedinto files.

QUESTION 2:

What do you remember about computer memory? In the table, decide what is true for mainmemory and for secondary memory. (Click on the buttons to see if you are correct.)

Answer:

Click!

Bit

Page 32: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 32/293

 

A punched card (about half size).

In both main and secondary memory, information is stored as patterns of bits. Recall fromchapter two what a bit is:

A bit is a single on/off value. Only these two values are possible.

The two values may go by different names, such as true/false, or 1/0. There are many ways inwhich a bit can be implemented . Here are some ways that bits are implemented:

• A mechanical electrical switch (like a light switch.)• Voltage on a wire.• A single transistor (used in main memory).• A tiny part of the surface of a magnetic disk.

Page 33: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 33/293

 

• A tiny part of the surface of a magnetic tape.• A hole punched in a card.• A tiny part of the light-reflecting surface of a CD.• Part of a radio signal.• Many, many more ways

The implementation of bits is different in main memory and secondary memory, but logically, both types of memory store bits.

QUESTION 3:

(Thought question:) Does the information change when a bit is copied from one form of storageto another? For example, does the information change when a bit implemented as a voltage levelon a wire is copied to a tiny part of a disk?

Answer:

 No. The different ways of storing a bit do not change the information that is being stored.

Copied Information

Information stored in binary form does not change when it is copied from one medium (storagemethod) to another. And an unlimited number of such copies can be made (remember theadvantages of binary.) This is a very powerful combination. You may be so accustomed to thisthat it seems commonplace. But when you (say) download an image from the Internet, the datahas been copied many dozens of times, using a variety of storage and transmission methods.

It is likely, for example, that the data starts out on magnetic disk and is then copied to mainstorage of the web site's computer (involving a voltage signal in between.) From main storage itis copied (again with a voltage signal in between) to a network interface card, which temporarilyholds it in many transistors. From there it is sent as an electrical signal down a cable.

Along the route to your computer, there may be dozens of computers that transform data from anelectical signal, into main memory transistor form, then back to an electrical signal on another cable. Your data may even be transformed into a radio signal, sent to a satellite (with its owncomputers), and sent back to earth as another radio signal. Eventually the data ends up as data inyour video card (transistors), which transforms it into a TV signal for your monitor.

The point of all of this is that the actual information (in this example the picture) does not changefrom one medium to the next.

Page 34: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 34/293

 

QUESTION 4:

 Analog data (continuously changing signals) such as on LP records or audio tape also can becopied from medium to medium. Does the information of analog data change when it is copiedto a different medium?

Answer:

Usually we don't want it to (and for audio data use "high fidelity" electronics to minimize thechange.) But always some information is lost.

Byte

Name Number of Bytes

powerof 2

byte 1 20

kilobyte 1024 210

megaby

te1,048,576 220

gigabyt

e1,073,741,824 230

terabyt

e

1,099,511,627,

776240

One bit of information is so little that usually computer memory is organized into groups of eight bits. Each eight bit group is called a byte. When more than eight bits are required for some data,a whole number of bytes are used. One byte is about enough memory to hold a single character.

Often very much more than eight bits are required for data, and thousands, millions, or even billions of bytes are needed. These amounts have names, as seen in the table.

If you expect computers to be your career, it would be a good idea to become familiar with thistable. The only number you should remember from the middle column is that a kilobyte is 1024 bytes. Often a kilobyte is called a "K", a megabyte is called a "Meg", and a gigabyte is called a"Gig".

Page 35: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 35/293

 

The table lists the number of bytes, not bits. So one K of memory is 1024 bytes (which happensto be 1024*8 == 8,192 bits). Usually you are not particuarly interested in the exact number of 

 bits.

QUESTION 5:

How many 10 Meg files would it take to fill a 500 Gig hard drive?

Answer:

(500 x 230) / (10 x 220) == 50 x 210 == 50K files

Bytes, not BitsIt will be very useful in your future career to be sure you know how to multiply powers of two.

2M * 2N = 2(M+N) 

In the above, * means multiplication. For example:

26 * 210 = 216 

QUESTION 6:

Locations in a digital image are specified by a row number and a column number (both of theseare integers). Say that a particular digital image is 1024 rows by 1024 columns, and that eachlocation holds one byte. How many megabytes are in that image?

Locations in a digital image are specified by a row number and a column number (both of themintegers). A particular digital image is 1024 rows by 1024 columns, and each location holds one byte. How many megabytes are in that image?

Answer:

1024 * 1024 = 210 * 210 = 2(10+10) = 220 = one megabyte

Page 36: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 36/293

 

Picture of Main Memory

Main memory consists of a very long list of bytes. In most modern computers, each byte has anaddress that is used to locate it. The picture shows a small part of main memory:

Each box in this picture represents a single byte. Each byte has an address. In this picture theaddresses are the integers to the left of the boxes: 0, 1, 2, 3, 4, ... and so on. The addresses for most computer memory start at 0 and go up in sequence until each byte has an address.

Each byte contains a pattern of eight bits. When the computer's power is on, every byte containssome pattern or other, even those bytes not being used for anything. (Remember the nature of  binary: when a binary device is working it is either "on" or "off", never inbetween.)

The address of a byte is not explicitly contained in memory. When the processor needs to accessthe byte at a particular address, the electronics of the computer "knows how" to find that byte in

memory.

QUESTION 7:

Decide which of the following are true:

Page 37: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 37/293

 

• Each byte of main memory has a unique address.• If main memory cotains 4 megabytes, there will be 4 * 220 addresses.

Answer:

Each byte of main memory has a unique address. True• If main memory is 4 megabytes large, there will be 4 * 220 addresses. True

Contents of Main Memory

Main memory (as all computer memory) stores bit patterns. That is, each memory locationconsists of eight bits, and each bit is either "0" or "1". For example, the picture shows the firstfew bytes of memory.

The only thing that can be stored at one memory location is eight bits, each with a value of "0" or "1". The bits at a memory location are called the contents of that location.

Sometimes people will say that each memory location holds an eight bit binary number. This isOK, as long as you remember that the "number" might be used to represent a character, or anything else.

Page 38: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 38/293

 

Remember that what a particular pattern represents depends on its context (ie., how a program isusing it.) You cannot look at an arbitrary bit pattern (such as those in the picture) and say what itrepresents.

QUESTION 8:

In the picture, what is the contents of:

• Memory location 0?• Memory location 4?

Answer:

In the picture, what is the contents of:

• Memory location 0? 0100 1111• Memory location 4? 0000 0000

(It is customary to show bit patterns with a space every 4 bits. The space is not actually part of the pattern.)

Reading and Writing Memory

Page 39: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 39/293

 

The processor can do two fundamental things with in main memory:

1. It can write to a byte at a given memory location.o  The previous bit pattern in that location will be destroyed.o  The new bit pattern is now saved for future use.

2. It can read a byte from a given location.o  The processor gets the bit pattern stored at that location.o  The contents of that location are NOT changed.

For example, if the processor needs to get the byte stored at location 5, it can read it. It gets the byte "0110 1110" as the data it needs (but location 5 in memory does not change.)

Most processors can write (and read) more than a single byte at a time. This speeds things up.

But the two operations above are fundamental. You may have heard talk about the new 64-bit processors and 128-bit processors. A 64-bit processor can read and write 64/8 = 8 bytes at a time.

Page 40: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 40/293

 

QUESTION 9:

Say that later on the processor needs to save the byte "1111 1111" and picks location 7 for this.How will main memory be changed?

Answer:

The answer is in the picture below.

Programs and Memory

The processor has written a byte of data at location 7. The old contents of that location are lost.Main memory now looks like the picture.

When a program is running, it has a section of memory for the data it is using. Locations in thatsection can be changed as many times as the program needs. For example, if a program is addingup a list of numbers, the sum will be kept in main memory (probably using several bytes.) Asnew numbers are added to the sum, it will change and main memory will have to be changed,too.

Page 41: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 41/293

 

Other sections of main memory might not change at all while a program is running. For example,the instructions that make up a program do not (usually) change as a program is running. Theinstructions of a running program are located in main memory, so those locations will notchange.

When you write a program in Java (or most other languages) you do not need to keep track of memory locations and their contents. Part of the purpose of a programming language is to dothese things automatically.

QUESTION 10:

(Review Question:) Where are programs and data kept for long-term storage?

Answer:

In secondary storage (usually the computer system's hard disk.)

Hard Disks

The hard disk of a computer system records bytes on a magnetic surface much like the surface of audio tape. The recording (writing) and reading of the data is done with a read/write head similar to that used with audio tape.

The picture shows one disk and one read/write head at the end of a movable arm. The arm movesin and out along a radius of the disk. Since the disk is rotating it will record data in a circular track on the disk. Later on, to read the data, it must be moved to the right position, then it must

Page 42: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 42/293

 

wait until the rotating disk brings the data into position. Just as with audio tape, data can be readwithout changing it. When new data it recorded, it replaces any data that was previouslyrecorded at that location. Unlike audio tape, the read/write head does not actually touch the disk  but skims just a little bit above it.

Usually the component called the "hard disk" of a computer system contains many individualdisks and read/write heads like the above. The disks are coated with magnetic material on bothsides (so each disk gets two read/write heads) and the disks are all attached to one spindel. Allthe disks and heads are sealed into a dust-free metal can. Since the operation of a hard disk involves mechanical motion (which is much slower than electronic processes), reading andwriting data is much slower than with main memory.

QUESTION 11:

(Thought Question:) Why does not the read/write head of a hard disk touch its surface?

Answer:

Since the disk is constantly rotating when the computer is on it would soon wear out if theread/write head were in contact with it.

Files

Hard disks (and other secondary memory devices) are used for long-term storage of large blocksof information, such as programs and data sets. Usually disk memory is organized into files.

A file is a collection of information that has been given a name and is stored in

secondary memory. The information can be a program or can be data.

The form of the information in a file is the same as with any digital information---it consists of  bits, usually grouped into eight bit bytes. Files are frequently quite large; their size is measuredin kilobytes or megabytes.

If you have never worked with files on a computer before you should study the documentationthat came with your operating system, or look at a book such as Windows for Dummies (or whatever is appropriate for your computer.)

One of the jobs of a computer's operating system is to keep track of file names and where theyare on its hard disk. For example, in DOS the user can ask to run the program DOOM like this:

C:\> DOOM.EXE

Page 43: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 43/293

 

The "C:\>" is a prompt; the user typed in "DOOM.EXE". The operating system now has to findthe file called DOOM.EXE somewhere on its hard disk. The program will be copied into mainstorage and will start running. As the program runs it asks for information stored as additionalfiles on the hard disk, which the operating system has to find and copy into main memory.

QUESTION 12:

Where does a program typically put its results for long-term storage?

Answer:

Usually in a file in secondary storage. If the file does not already exist, the program will ask theoperating system to create it.

Files and the Operating System

Most collections of data outside of main storage are organized into files. Keeping track of all thisinformation is one of the jobs of the operating system. If the computer is part of a network,keeping track of all the files on all the computers is a big job, and involves all the operatingsystems on the network.

Application programs (including programs that you might write) do not directly read, write,

create, or delete files. Since the operating system has to keep track of everything, all other  programs ask it to do file manipulation tasks. For example, say that a program has just calculateda set of numbers and needs to save them. The following might be how it does this:

1. Program: asks the operating system to create a file with a nameRESULTS.DAT 

2. Operating System: gets the request; finds an unused section of the diskand creates an empty file. The program is told when this has beencompleted.

3. Program: asks the operating system to save the numbers in the file.4. Operating System: gets the numbers from the program's main memory,

writes them to the file. The program is told when this has been completed.

5. Program: continues on with whatever it is doing.

So when an application program is running, it is constantly asking the operating system to perform file manipulation tasks (and other tasks) and waiting for them to be completed. If a program asks the operating system to do something that will damage the file system, theoperating system will refuse to do it. Modern programs are written so that they have alternativeswhen a requests is refused. Older programs were not written this way, and do not run well onmodern computers.

Page 44: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 44/293

 

QUESTION 13:

In modern computer systems, only the operating system can directly do anything with disk files.

How does this:

1. affect the security of the system?2. affect computer games?3. affect the ease in creating programs?

(You might not be certain about your answers, but please think about the questions.)

Answer:

In modern computer systems, only the operating system can directly do anything with disk files.How does this:

1. affect the security of the system?o  The security is increased because programs that try to do dangerous

or stupid things to files can't. They have to ask the operating system,which will only do safe and sensible things.

2. affect computer games?o Older computer games did their file manipulation themselves without

asking the operating system (old DOS was stupid and slow and manyapplication programs ignored it.) Those games won't run on moderncomputers.

3. affect the ease in creating programs?

o Program creation is easier because the work of dealing with files isdone by the operating system.

Types of Files

As far as the hard disk is concerned, all files are the same. At the electronic level, there is nodifference between a file containing a program and a file containing data. All files are namedcollections of bytes. Of course, what the files are used for is different. The operating system can

take a program file, copy it into main memory, and start it running. The operating system cantake a data file, and supply its information to a running program when it asks.

Often then last part of a file's name (the extension) shows what the file is expected to be used for.For example, in mydata.txt the .txt means that the file is expected to be used as a collection of 

text, that is, characters. With doom.exe the .exe means that the file is an "executable," that is, a

 program that is ready to run. With program1.java the .java means that the file is a source

Page 45: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 45/293

 

 program in the language Java (there will be more about source programs later on in these notes.)To the hard disk, each of these files is the same sort of thing: a collection of bytes.

QUESTION 14:

What happens when a file is used in a way other than its intended use? For example, whathappens if you try to use a word processor on an ".EXE" file?

Answer:

Something will likely go wrong. The information contained in the file is not appropriate for aword processor.

End of the Chapter

You have reached the end of the chapter. If you have trouble with your own memory, and needto review a topic, click on it in the list below to go to where it was discussed.

•  Types of computer memory and their characteristics.• Bit. • Byte, kilobyte, megabyte, gigabyte, terabyte. • Multiplication rule for exponents.• Picture of main memory. • Contents of main memory, •  Two things that the processor can do with main memory.• Picture of a hard disk. • Files. • Operating system and file I/O. 

You have reached the end of the chapter.

CHAPTER 4 — The ProcessorChapter Topics:

• Machine operations and machine language• Example of machine language• Different types of processor chips• High level programming languages

Page 46: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 46/293

 

• Language translators (compilers)• Language interpreters

From previous chapters you know that the major hardware components of a computer systemare:

• Processor• Main memory• Secondary memory devices• Input/output devices

This chapter examines the "brain" of the computer system — the processor. Then it shows howthe programs you write are translated into instructions for the processor.

QUESTION 1:

What component of a computer system is directly responsible for running a program?

Answer:

The processor.

Electronic Operations of a Processor

When a program is running on a computer the processor is constantly performing very many tinyelectronic operations. For example, one such operation reads one byte of data from main memoryinto the processor. Another operation tests if one of the bits in a byte is a "1" bit or a "0" bit.Most processors are able to perform several hundred types of tiny operations like these, and can perform billions of them per second.

Those are the only things that a processor can do. It has a set of tiny electronic operations that itcan to perform, and that is all. These tiny electronic operations are performed one at a time. But billions of them are performed per second, and billions of small operations can add up to a largeand useful action.

Everything that a processor does is built out of these tiny operations! Luckily, you don't need toknow the details of these operations to write programs in Java. The purpose of a "high-levellanguage" like Java is to organize the tiny electronic operations into large, useful unitsrepresented by program statements.

Page 47: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 47/293

 

QUESTION 2:

(Thought question:) When you click on a hyperlink on a Web page, your Web browser (acomputer program) finds and displays a new page. About how many tiny electronic operationsdoes the processor perform in doing this?

• 1• 10• 100• 100,000

Answer:

I would guess about 100,000 operations. Certainly not as few as 100. All these tiny operationsadd up to a useful big operation: displaying a new Web page.

Machine Instructions

Users and programmers of computers usually don't think about the billions of tiny electronicoperations that go on each second. The situation is (very roughly) similar to when you aredriving your car. You think about the "big operations" it can perform, such as "accelerate", "turnleft", "brake", and so on. You don't think about tiny operations, such as the valves in your engineopening and closing 24,000 times per minute or the crankshaft spinning at 3000 revolutions per minute.

Each tiny electronic operation that a processor core can perform is called a machine operation.A processor (a "machine") performs these one at a time, but billions of them in a second.

A machine instruction consists of several bytes in memory that tell the processor to performone machine operation. The processor looks at machine instructions in main memory one after another, and performs one machine operation for each machine instruction. The collection of machine instructions in main memory is called a machine language program or (morecommonly) an executable program.

Don't panic if the above seems incomprehensible. It takes some getting used to. (And to really

understand it all takes several courses.)

QUESTION 3:

When they are running, are machine langage programs located in main memory along with data?

Page 48: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 48/293

 

Answer:

Yes. Programs and data are both in main memory when they are active.

Example of Machine Language

Let us say that an electric toothbrush has a processor and main memory. The processor can rotatethe bristles left and right, and can check the on/off switch. The machine instructions are one bytelong, and correspond to the following machine operations:

Machine

InstructionMachine Operation

0000 0000 Stop

0000 0001 Rotate bristles left

0000 0010 Rotate bristles right

0000 0100 Go back to start of program

0000 1000 Skip next instruction if 

Page 49: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 49/293

 

switch is off 

Here (let us pretend) is the main memory for the toothbrush system:

Addre

ss

Machine

Instruction

0

1

2

3

4

The toothbrush is wired so that when the switch is first turned on the instruction at address zerois performed. Then, instructions are performed one at a time, in order, until the "Stop" instructionis encountered.

The "Skip" instruction checks the on/off switch and skips over one instruction if the switch is"off".

The "Go back" instruction causes the processor to start again with the instruction at address 0.

You want a program for the toothbrush. The bristles should repeatedly move back and forth, leftand right, while the switch is on. When the switch is moved to "off" the bristles should stopmoving.

QUESTION 4:

Fill in main memory starting at address 0 with the machine instructions to control the toothbrush.Copy and paste from the list of machine instructions.

(Please take the time to do this. If you do, you will be able to tell people that the first programyou ever wrote was for an electric toothbrush. You do not want to pass up this opportunity.)

Answer:

The embedded control program for the dental appliance is given below.

 

þÿ

þÿ

þÿ

þÿ

þÿ

Page 50: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 50/293

 

Machine Language Program

There are at least two sensible programs for the toothbrush. The table shows one of them.

In the electronic memory of the toothbrush the program is stored as a sequence of bytes:

0000 00010000 00100000 10000000 01000000 0000

The processor starts at the beginning and performs the action described by that code andcontinues through the bytes in sequence until it reaches the one (at address 3) that says to start

over. If the switch is moved to the "off" position, the processor skips that instruction and instead performs the "stop" instruction at address 4.

This is, of course, a silly example. Electric toothbrushes are not controlled by computer  processors. And, the machine instructions of actual processors are much more detailed. But theessential ideas of the example are these:

• A machine language program is a sequence of machine language instructionsin main memory.

• A machine instruction consists of one or more bytes (in this example, onlyone).

 The processor runs a program one machine instruction at a time.• All the little machine operations add up to something useful.

If toothbrush user leaves the switch "on" for a while, the program repeats its operations manytimes. This is how most programs in real computers run — many little operations add up to auseful function, which is then repeated many times.

Addre

ss

Machine

InstructionMeaning

0 0000 0001 Rotate bristles left

1 0000 0010 Rotate bristles right

2 0000 1000Skip next instruction if 

switch is off 

3 0000 0100 Go back to start of program

4 0000 0000 Stop running

Page 51: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 51/293

 

QUESTION 5:

Will the toothbrush stop immediately when the switch is turned off? (Follow through the

 program to see if this happens.)

Answer:

 No. The program may run for several instructions before the switch is tested.

Executing Instructions

The word "execute" is often used to mean "perform the machine operation that an instructionasks for." So you can say that "executing the instruction 0000 0000 stops the toothbrush," or "billions of instructions execute per second." "Execute" is also used for an entire program or partof a program: "to execute the program, turn the switch to on."

Most programs have groups of instructions that are executed again and again. The toothbrush program does this with an instruction that causes the processor to return to the beginning of the program and so to repeat what it just did.

A group of machine instructions that executes repeatedly is called a loop.

A modern processor executes billions of instructions per second. A program without loops wouldexecute for only a few seconds, even if it had billions of instructions.

A typical processor is made up of many millions of transistors on a small wafer of silicon calledan integrated circuit (also called a chip.) The toothbrush processor could probably be built with just a few hundered transistors. Integrated circuits are used for other electronic parts of acomputer. For example main memory is implemented with memory chips.

Most modern processor chips have two or more processors on them. Each of the processors onthe chip is called a "processor core" or often just called a core. Each core has the same set of tinyelectronic operations and runs programs independently of the other cores. When a program is

running, it runs on a single core, which performs the tiny electonic operations of the program oneat a time.

QUESTION 6:

Say that a computer has four billion bytes of memory and that memory is entirely filled with asingle program. Each instruction is one byte long, and the processor can execute one billioninstructions per second.

Page 52: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 52/293

 

How long will the program run if execution starts with the first byte and their are no loops in the program?

Answer:

Four billion / one billion = 4 seconds

In fact, most instructions are longer than one byte, most desktop computers execute more thanone billion instructions in a second, and most programs are much shorter than four billion bytes.So without loops, most programs would run for a fraction of a second.

Different Processors

There are many types of processors used in computer systems. You probably know somethingabout the processors used in most desktop computers, Intel Corporation's Pentium processors.But there are other types of processors, such as the processors used in cell phones and gamemachines. A computer system is designed around its processor. The electronics of a computer system are designed for a particular type of processor.

Different types of processors have different machine operations and different machine languages.A machine language program for a typical desktop system (with a Pentium processor) wouldmake no sense to a computer built around a different processor type.

However, the machine operations available with all types of processors can be used to build the

same things. All processor types have enough power in their little machine operations to createthe same large applications. Anything one processor can do with its machine language program,another processor can do with a program written in its machine language. For example, cell phones are built around a variety of processor types, but all cell phones can do the same things.

The architecture of a processor is the choices that have been made for its machine operations,how they have been organized and implemented, and how it interacts with main memory andother components. Architecture is concerned with the general plan and functions of a processor;it is not much concerned with electronic details. A course in computer architecture is required inmost computer science departments.

QUESTION 7:

(Thought question:) Say that you are looking at two different processor chips. The first processor has twice as many types of machine operations as the second chip. Is the first processor necessarily the best one?

Page 53: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 53/293

 

Answer:

 No—the smaller chip might have a well chosen set of operations that work together better andfaster than the poorly chosen operations of the other processor.

High Level Programming Languages

It is rare for programmers to write programs in machine language like we did for the electrictoothbruch. The executable files (the directly runnable machine language programs) for mostapplications contain hundereds of thousands (or even millions) of machine language instructions.It would be very hard to create something like that from scratch.

As an experiment, look through your hard disk with the file listing utility (the "Explorer" on

Microsoft systems.) Look at the size of the something .EXE files. There are about four bytes per machine instruction on Intel processors, so divide by four to get the number of instructions.

Most programs are created using a high level programming language such as Java, C, C++, or BASIC. With a high level language, a programmer creates a program using powerful, "big"operations which will later be converted into many little machine operations.

For example, here is a line from a program in the language C:

int sum = 0;

This declares and initializes a variable to zero (a big operation).

The machine operations that correspond to this big operation set up a part of main memory tohold a number, store the number zero there, and arrange things so other parts of the program canuse it. It might take a hundred machine operations to do all this. Obviously, it is easier for ahuman programer to ask for all these operations using C.

QUESTION 8:

Say that a corporation pays programmers $50 an hour. Will the corporation want programmers to program in machine language or in a high level language?

Answer:

A high level language. Programmers can create programs in much less time (costing much lessmoney) by using a high level language.

Page 54: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 54/293

 

Source Programs

Programers create programs by writing commands in a high level language. A high levellanguage program consists of lines of text that have been created with a text editor and are keptin a file on the hard disk. For example, here is a complete program in C (Java will be discussedlater):

#include <stdio.h>main(){int sum = 0;sum = 2 + 2;printf( "%d\n", sum );

}

This program could be saved on the hard disk in a file called addup.c. Like all files, it consists

of a sequence of bytes. Since it is a text file, these bytes represent character data. You can editthe file with a text editor and print the file on a printer. It does not contain machine instructions.If the bytes are copied into main memory, they cannot run as a program without some extra work  being done.

A source program is a text file that contains instructions written in a high level

language. It can not be executed (made to run) by a processor without some

additional steps.

A source program is also called a source file, source code, or sometimes, just source.

Usually a source program is translated into a machine language program. An application program called a translater takes a source program as input and produces a machine language program as output.

A machine language program is also called an executable program, executable file, or sometimes, just executable.

For example, the C program addup.c could be translated into an executable program. The

executable program might be called addup.exe and can be saved on the hard disk. Now the

executable version of the program can be copied into main memory and executed.

The word compile means the same thing as translate. So one can say that a source program iscompiled into an executable program.

Page 55: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 55/293

 

QUESTION 9:

Say that a source program has been translated into an executable program. The executable program has been run a few times, and the programer decides to make a change to the program.Where is the change made? To the source program or to the executable program?

Answer:

To the source program, where the change is easy to make with a text editor. The changed source program is then translated into a new executable program.

Program Translation

The picture shows what usually happens with programs written in C (Java is different; it will bediscussed in the next chapter.) Here is an overview:

1. The source program is created using a text editor.o It contains instructions in a high level language.o It contains bytes that represent characters.o  The source program is kept on the hard disk.o  The source program can not be run by the processor.

Page 56: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 56/293

 

2. A translator (compiler) program translates the source program into anexecutable program.

o  The source program remains unchanged; a new executable program iscreated.

o  The executable program contains machine instructions.o A translator translates from a specific high level language (like C) into

machine instructions for a specific processor type (like Pentium).o  The executable program is also kept on hard disk.

3. The program is run by copying machine language from the executableprogram on disk into main memory. The processor directly executes thesemachine language instructions.

QUESTION 10:

Can the processor directly execute the machine language that the program has been translatedinto?

Answer:

For languages like C, the answer is "yes".

Program Execution

Page 57: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 57/293

 

Once the source program has been translated into machine code (the executable program), themachine code can be directly executed by the processor. This is like the tooth-brush processor directly executing its machine code. The source program is only a means to create the machinecode.

For commercial software like games and word processors, the machine code is the product that issold to the user. The user does not get a copy of the source program.

A student learning programming, or a programmer developing an application, creates source programs and translates them (with a compiler) into executable programs.

The above is what goes on with languages like Ada, Pascal, C, C++, FORTRAN and others. Javaadds a few more steps, which will be discussed in the next chapter.

QUESTION 11:

Say that you have a source program written in C. You copy the program onto the hard disk of aPentium-based computer and also copy it onto the hard disk of an Motorola-based computer.What must you do so both computers can execute the program?

Answer:

Each copy of the source program must be translated into an executable program that is correctfor each machine:

Page 58: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 58/293

 

• On the Pentium: A C translator that outputs machine language for Pentiumprocessors is used.

• On the Motorola-based computer: A C translator that outputs machinelanguage for Motorola processors is used.

Portability

Ideally, only one program needs to be written in the high level language. That source file canthen be translated into several executable files, each containing the correct machine instructionsfor its intended processor. This is how the same game can be made for desktop computers andgame machines.

The idea of using one source file for executable programs that run on different processors iscalled software portability. You would like to write a program just once (in a high levellanguage) and then to run it on any computer system by translating it into that system's machinelanguage.

Usually, unfortunately, things do not work out that nicely. There are enough little problems sothat it takes a substantial amount of human effort to get a source program running on a severaldifferent systems. Sometimes it is months before a game program that has been released for PCsis released for game consoles.

One of the big advantages of Java is that it is automatically portable between computer systemsthat have Java support. No human effort is involved at all.

QUESTION 12:

Say that a corporation pays programmers $50 an hour to write application programs that will runon both Apple and Windows computers. Will the corporation want programmers to program inJava or in some other high level language?

Answer:

Java. The time (and expense) of getting the program to run on other computers is avoided.(Actually, sometimes things do not work out as nicely as this.)

Interpreter

Page 59: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 59/293

 

Programs written in a high level language are never directly executed by the processor. You havealready seen one way to execute such a program: use a translator to create a machine language program that can be executed directly.

Another way to is to use an interpreter for the language. An interpreter is an executable program that runs directly on the processor. An interpreter reads through a source programwritten in a high level language and performs the actions that the source program asks for.

This is a fairly complicated thought. The figure might help.

In this figure, the source program program.bas has been written in BASIC (a programming

language) by a programmer with a text editor. It is being interpreted by the BASIC interpreter,which is an executable program running on the processor.

The BASIC interpreter works by reading in commands of the BASIC source program one byone. Each time it reads in a command, the interpreter does what the command asks. A BASICcommand might ask to add two numbers together. That is fine. The BASIC interpretter is a program, and programs can easily add together two numbers. The BASIC program might thenask to write the sum to the monitor. Still fine. The BASIC interpretter can easily do that.

The BASIC interpretter uses the fundamental machine operations of the processor to perform theactions requested in the BASIC source program. But the source program itself is not translated

into machine language.

This is like a cook who can't read, who hires an assistant who can read (but can't cook). Theassistant reads the instructions of a recipe one by one to the cook, who performs them one by oneas they are read.

You have probably done this many times without realizing it. It is exactly accurate (although anunusual use of the words) to say that the computer game Free Cell Solitare (or any computer 

Page 60: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 60/293

 

game) is an interpreter for the commands that you enter using the mouse and keyboard. Thecommands for the game Free Cell are not the usual commands used in a general-purpose programming language, but none the less, they are commands expressed in a formal language.You enter commands, and the interpreter (the game) executes them one by one. The set of commands and the rules for how to use them correctly form a programming language for the

Free Cell interpreter.

In playing a computer game, you are writing a program that solves a problem. (Usually the problem is to get to the end of the game.) If you recorded every move you made, you would havea program that the game, acting as an interpretter, could run to solve the problem.

(Of course, each time you play solitaire, the problem is a randomly selected initial arrangementof cards, so you need a different program for each problem.)

QUESTION 13:

An interpreter runs directly on the processor. What type of instructions must an interpreter consist of?

Answer:

An interpreter is an executable program, which consists of machine instructions, like all programs that execute directly on the processor.

Of course, a programmer creates an interpreter by writing it in a high level language and

compiling it into the executable program.

Virtual Machine

Page 61: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 61/293

 

When an interpreter is running a BASIC source program, both the interpreter and the source program are in main memory. The interpreter consists of machine instructions that the hardwarecan execute directly. The BASIC source program consists of commands that the interpreter can perform.

From the perspective of the BASIC program, it looks like the commands in BASIC are being 

directly executed by some sort of machine. The figure has been modified to show this.

This is really the same as the previous figure, but now a box has been drawn around the actual(hardware) processor and the interpreter that it is executing. The combination looks like amachine that can directly execute BASIC commands. It is as if BASIC commands are themachine language for combination of processor and interpreter.

The word virtual is used in situations where software has been used to make something look likethe real thing. In this case it looks like we have a machine that can directly execute BASIC, sowe can say that we have a BASIC virtual machine.

QUESTION 14:

Do you think that a BASIC source program could be translated into an executable file of machine instructions?

Page 62: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 62/293

 

Answer:

Yes. There are both translators and interpreters for most high level language. Which you usedepends on how you use the high level program.

Speed

The situation with computer languages is somewhat like that with human languages:

• Translator: takes a complete document in one language and translates itinto a complete document in a second language, which can then be used by areader of the second language.

• Interpreter: acts as an intermediate between a speaker of one languageand a speaker of another language. Usually an iterpreter works one sentenceat a time. Immediately after a sentence is spoken in the first language, thetranslator converts it into the second language. You and your Frenchtranslator (say) could in combination be regarded as a "virtual Frenchspeaker".

Using a human interpreter as an intermediate is slower than conversing directly in a particular language. The same is true with computer language interpreters. The interpreter has to do quite a bit of work to deal with the language it is interpreting. The extra work makes it look like thevirtual processor is much slower than the real one.

QUESTION 15:

Is it always important for a program to run as fast as possible? (Hint: take some time to answer this question.)

Answer:

 No. Programs should get their work done in a timely fashion, but often moderately slow is fastenough.

For example, your Web browser mostly does nothing as it waits for your commands. It is aninterpreter for the commands you enter using the mouse and keyboard. It would be only a slightimprovement to make it run much faster.

End of the Chapter!

Page 63: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 63/293

 

You may wish to review the following. Click on a subject that interests you to go to where it wasdiscussed.

• Machine operations and machine instructions.• Executing a program.•

Differences in types of processor chips.• High level programing language. • Source program. • Program translation.• Program interpretation.• Portability. 

The next chapter will discuss how the language Java fits into the concepts this chapter hasdiscussed.

You have reached the end of the chapter.

CHAPTER 5 — Introduction to Java

Chapter Topics:

• Hello World program•  Java Bytecodes•  Java compiler and Java virtual machine• Using Notepad to create a source program

• Running a Java program

The previous chapters have discussed computer hardware, computer software, bits and bytes,machine language, language translation, language interpretation, and virtual machines. Thischapter assumes that you know all that and are ready to look at Java.

These notes are written for Java 2 Standard Edition version 5.0 or higher. Many features wereadded to this edition and previous versions will not work as well with these notes. If you areinstalling Java for the first time on your computer, install Java 2 Standard Edition version 6.0 or higher. See Appendix B for information on how to do this.

QUESTION 1:

Can the processor of a computer system directly execute source programs written in Java?

Page 64: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 64/293

 

Answer:

 No. (If you got this question wrong, or don't even know what it asks, you need to study Chapter Four.)

Simple Java Program

Here is an example Java program. It is about as small as a Java program can be. When it runs, itwrites Hello World! on the computer monitor. The details will be explained later.

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

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

}

This program can be created using a text editor such as the Notepad editor that comes withWindows. (Details later.) This source program is a text file saved on a hard disk. The file isnamed Hello.java.

A source program is a text file that contains a program (such as above) written in a programming language. Since it contains ordinary text (stored as bytes) it can not be directlyexecuted (run) by the computer system. As a text file, you can print it, display it on the monitor,

or alter it with a text editor.

QUESTION 2:

(Review of Chapter 4:) What are the two ways that a source program can be run on a computer system?

Answer:

1. Translation (into machine instructions, which are then directly executed bythe processor)2. Interpretation (by an interpreter program)

Bytecodes

Page 65: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 65/293

 

Java combines these ideas in a way that will take some explaining. To run a Java program thesource file is first translated into a file of bytecodes.

A Java bytecode is a machine instruction for a Java processor. A file of bytecodes is a machinelanguage program for a Java processor.

The picture shows the Java compiler translating the sample Java program Hello.java into

 bytecodes. The file of bytecodes (machine language for the Java processor) is calledHello.class. 

In this picture, the source program Hello.java is examined by a program called javac running

on your computer. The javac program is a compiler (a translator) that translates the source program into a bytecode file called Hello.class. 

Important Idea: The bytecode file will contain exactly the same bytecodes no

matter what computer system is used.

The architecture of the processor that executes Java bytecodes is well-documented and is

available to anyone. The Java compiler on a Macintosh will produce the exact same bytecodes asthe Java compiler on an Intel system.

QUESTION 3:

Could a processor chip be built that executes Java bytecodes directly, just as a Pentium executesits machine language directly?

Answer:

Yes. Hardware Java processor chips have been created out of silicon and can execute bytecodefiles just as a Pentium exectues files of its machine language.

Java Virtual Machine

Page 66: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 66/293

 

Usually, however, people do not have hardware Java processor chips. They have ordinary PCsand Macintoshes.

 Now for the clever part: the Java processor can be implemented as software! It is implemented asa program that reads the bytecodes and performs the operations they specify. (This type of  program is called an interpreter.) The Java bytecode interpreter is an executable program thatruns on whatever computer system you have.

The "Java interpreter" in the picture is an executable program that is running on an ordinarycomputer system, such as a desktop Pentium system. Each type of computer system has its ownJava interpreter that can run on that system. The "Actual Processor" is the actual, hardware processor chip of that computer system.

(Another) Important Idea: When the Java interpreter is running on a computer

system, that system acts just like a hardware Java bytecode processor. It is a Java

Virtual Machine. 

Any computer system can execute a Java bytecode program by using a Java interpreter. The Javainterpreter has to be specifically written for that particular computer system, but once that is

done, the computer system can become a Java virtual machine. That is, it looks like a computer with a hardware Java processor chip and can run Java bytecodes.

When a Java program is translated into bytecodes, the bytecodes are exactly the same no matter what computer system is used. This means the bytecodes on a Sun computer can be sent to anIntel based computer and they will run without a problem.

Page 67: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 67/293

 

QUESTION 4:

Say that Apple has just come out with a new computer and wants this computer to run Java programs. What must Apple do?

Answer:

Apple must write a Java interpreter for their new system.

Portability

Once Apple writes the interpreter and includes it on their new system, the system can run anyJava program. Nothing new needs to be done with those programs.

Java programs are portable, which means that the same bytecode program can run on anycomputer system that has a Java interpreter. Also, a source program can be compiled into bytecodes on any computer that has a Java compiler.

The source program does not have to be changed to meet the particular needs of variouscomputer systems. No matter what computer you have, you can write the same Java programs.

This is unlike most other programming languages, where a different version of a program must be made for each variety of computer, and an executable program that runs on one type of computer will not run on another.

QUESTION 5:

Can bytecodes be sent from computer to computer over the Internet?

Answer:

Yes.

Applets

An applet is a Java bytecode program that runs on a Web browser. Most up-to-date Web browsers include a Java interpreter. A Web page may contain an applet, which means that part of what the page displays is controlled by Java bytecodes. The computer that hosts the Web page

Page 68: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 68/293

 

sends Java bytecodes to a client computer (like yours) that has asked for the page. The Web browser on the client runs the Java applet using its built-in interpreter.

Applets are used for user interaction, graphics, and animation. Applets will be discussed in later chapters of these notes. For now, let us concentrate on Java programs that get input from the

keyboard and write output to the command prompt window of the monitor. These are called Javaapplication programs.

QUESTION 6:

Is the Java used to write applets the same Java as that used to write applications?

Answer:

Yes.

Creating a Java Source Program

Page 69: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 69/293

 

To start out, use the Notepad editor that comes with Microsoft Windows operating systems. Notepad is simple to use and good for getting started. After you see how things work using Notepad, move on to a better text editor (such as Crimson or Notepad++) or to a Java integrateddevelopment environment (IDE) (such as BlueJ or Dr. Java). For now, our goal is to create a textfile called Hello.java containing the text at right.

On a Windows computer, first start up the command prompt. Look for the "Command Prompt"icon. Click on the "Start" button in the lower left of your screen. Then click "All Programs" andthe "Accessories". You should now see a menu of choices similar to the picture.

Recent Windows operating systems will add the Command Prompt icon to the first start menuonce you have used it. The more recent the Windows system, the harder it is to find thecommand prompt. When you find it, click on the "Command Prompt" icon to start a command prompt window.

Page 70: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 70/293

 

class Hello{public static void main ( String[] args ){System.out.println("Hello World!");

}}

QUESTION 7:

Will you see exactly the same things as above on your computer system?

Answer:

 No. You will see different choices, depending on what programs you have installed, and what programs you have recently run.

Command Interpreter Window

After you start the command prompt window you can enter commands as if you were running anold-time DOS computer. You should see something like the picture. The line of text

C:\>

Page 71: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 71/293

 

is a prompt. You are expected to enter commands to the system after it. Depending on how your computer has been set up, you may see a prompt something like this:

C:\WINNT\System32>

This prompt means that the command interpreter is automatically expecting to use files in thedirectory C:\WINNT\System32. This is called the default directory. (A directory is a section of 

the disk that has a name. A directory can hold many files.) You should not use theC:\WINNT\System32 directory.

It doesn't matter where you start out because you can always move to where you want to beusing the CD command. For now, let us create a Java program in the C:\Temp directory. To get to

this directory type the following commands:

C:CD \Temp

Type these commands after whatever command prompt you see. The prompt changes to showthe current default directory. The first command C: switches to the C: disk (which is the hard

disk of the system if you have only one). The second command CD \Temp makes C:\Temp the

default directory.

QUESTION 8:

Can you create a directory?

Answer:

Yes. If you know how, create a new subdirectory (perhaps "C:\JavaPrograms") and use the CDcommand to move to it.

With the command prompt window, the command to create a new directory is:

MD directoryName

If you want, you can create a new directory using Windows Explorer and then use CD to move to

it in the command prompt window.

Starting Notepad

Page 72: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 72/293

 

We will use the Notepad text editor which comes with Microsoft operating systems. Click on the"Start" button in the lower left, then on "All Programs" then on "Accessories", and then on"Notepad". As you might expect, different versions of Windows put Notepad in different places.You may have to hunt.

Roughly similar things can be done on Mac and Linux systems.

After clicking on the icon, Notepad starts. Another way is to start it from the command prompt:

C:\TEMP> notepadC:\TEMP>

QUESTION 9:

Is all this getting to be just too much?

Page 73: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 73/293

 

Answer:

•  Yes — Find a Web site that explains basic computer use and DOS commands,or find a suitable book in your library. You will only need to look at the firstone or two chapters. Better yet, find a friend that knows all this and is happyto show off.

• No — Good.

Notepad

Once Notepad is running, just type in the program, as in the picture.

To enter characters, just type them. You can move around the text using the mouse or arrowkeys. To delete mistakes, use the "backspace" key or the "delete" key. To start a new line, just hit"Enter".

In typing in the program, make sure upper and lower case letters and all punctuation are exactly

correct. You do not have to get the spaces exactly correct.

 Now you need to save the file to the hard disk. One of the selections in the menu bar at the top of the Notepad window is used to do this.

Page 74: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 74/293

 

QUESTION 10:

Which of the menu selections (in the menu bar at the top of the Notepad window) do yousuppose is used to save the file?

Answer:

The "File" menu.

Saving the Source File

Move the mouse pointer to "File" and click on it. You will get a sub-menu. Now click on "SaveAs". As the picture shows, you may not start out in the C:\Temp directory. If not, you will haveto use the various controls at the top of the "Save As" dialog to get to the directory you want.

When you see it, click on the "Temp" directory to say that it is where you wish to save your  program. The "Temp" directory is intended for temporary files and will usually be full of manydifferent files.

Page 75: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 75/293

 

QUESTION 11:

If you save the file in a different directory than the one being used for the DOS window, will

there be a problem?

Answer:

Yes. You want the source file Hello.java to be saved in the disk directory that is the default

directory for the command prompt window.

Naming the File

The name of the source file should be the same as the name that follows the word class in the

 program (match upper and lower case), and should be given the extension .java (lower case).

For example, our program contains the line:

Page 76: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 76/293

 

class Hello

so the file name must be Hello.java. When you get to the Temp directory (or whatever default

directory you are using):

1. Type the file name into the box.2. The file name should be Hello.java 

o For some versions of Notepad you should put quote marks around thefile name like this: "Hello.java" even though the quote marks will notbe part of the file name.

o Sometimes Notepad automatically uses the extension ".txt" and youmay need to struggle to name the file what you want.

3. Select "Save as all files" by clicking on the little down arrow it the box belowthe file name box.

4. Select "Encoding: ANSI" in the bottom box.5. Click on "Save"

Your system is likely to be slightly different. Experiment with different choices until you areable to create a text file that contains the sample Java program.

Fussy, bothersome, irksome, irritating details. Yes, I know... Some people actually like this stuff.But if you can tie your shoes or drive a car you can do this. It might take some practice.

QUESTION 12:

So, finally your Java program source file is saved. What must you do to run it?

Answer:

Compile it into Java bytecodes, then run the bytecode file with the Java interpreter.

Running the Program

To do all that, find the DOS command prompt window you started up a while back. It should still be positioned in the C:\Temp directory (or other directory of your choice). To check that you put

the source file Hello.java in this directory, enter the command dir *.java. You should see

the source file, as below.

C:\TEMP>dir *.javaVolume in drive C has no label.Volume Serial Number is 7C68-1E55

Page 77: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 77/293

 

Directory of C:\TEMP

08/23/98 01:07a 115 Hello.java1 File(s) 115 bytes

2,448,368,640 bytes free

To compile the source file (thereby producing a file of bytecodes) enter the command javacHello.java.

C:\TEMP>javac Hello.javacompiling: Hello.java

 Notice that this command is javac, java-with-a-c which invokes the Java compiler. If you see thefollowing

C:\TEMP>javac Hello.javaThe name specified is not recognized as aninternal or external command, operable program or batch file.

then the PATH environment variable has not been set correctly. Look at Appendix C for information about this. A temporary alternative is to tell the command promt exactly where tofind javac:

C:\Temp> C:\Program Files\Java\jdk1.6.0_07\bin\javac Hello.java

Adjust the above command to match whatever directory your version of Java has been installedin. Finally, to run the program, enter the command java Hello.

C:\TEMP>java Hello

Hello World!

C:\TEMP>

 Notice that this command is java, java-without-a-c which invokes the Java interpreter. Again, if PATH is incorrect, you can run java by using the full path name to its location.

QUESTION 13:

After all of this, what did the Java program actually do?

Answer:

The example Java program wrote the words "Hello World!" in the command interpreter window.

Page 78: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 78/293

 

Result of Running the Example Java

Program

The picture shows my system when everything has worked correctly (which happens every time,of course).

Your program may not have run correctly. It is possible that you did not type in exactly the rightcharacters. Spaces don't particularly matter. But check especially characters like [ and { and

( and ". You have to use the correct ones. Check that upper case and lower case characters match

the sample program.

Fuss around for a while to get the program to work. If you just can't get it to work, give up andmove on. Probably there is some trival detail that you have overlooked and will see clearly later on. This happens all the time in programming.

If everything worked out perfectly, then go back and do something wrong. This will help youunderstand what happened later on when you unintentionally do something wrong.

Page 79: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 79/293

 

QUESTION 14:

Had enough, for now?

Answer:

Yes.

End of the Chapter!

Hopefully this chapter explained just exactly what you needed to know to run Java programs,and everything worked out perfectly, and you can now create Java source programs, and compilethem into bytecodes, and execute them using the Java interpreter.

Well.... one can hope. If something was less than perfect, find a friend that knows more aboutthese things and is happy to help. Or, start again and go through everything once again. Or, moveon and come back to this chapter later.

You may wish to review the following. Click on a subject that interests you to go to where it wasdiscussed.

The next chapter discusses how the example program worked.

• Example Java program. 

•  Java bytecodes. •  Java virtual machine. • Applets. • Starting the command prompt. • Starting Notepad. • Saving the source code to a file. • Running the program. 

You have reached the end of the chapter.

CHAPTER 6 — Small Java Programs

Chapter Topics:

• Small example programs• Names for source files and class files• Syntax errors

Page 80: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 80/293

 

• Bugs•  The Edit, Compile, and Run cycle• Matching braces• Neat indenting

The previous chapter discussed the mechanics of creating and running a Java program. Thischapter is an overview of Java using the example program from that chapter.

QUESTION 1:

(Review:) What role in Java programming does each of the following files play?

• Source code file• Bytecode file

Answer:

• Source code file:o a text file in the Java language created by a programmer with a text

editor• Bytecode file:

o a file of machine language for the Java virtual machine created by a Java compiler

Example Source Programclass Hello{public static void main ( String[] args ){System.out.println("Hello World!");

}}

Above is the source program (source file) from the previous chapter. The purpose of this

 program is to type the characters Hello World! on the monitor.

The file must be named Hello.java to match the name of the class. On most computer systems,

the upper and lower case characters of the file name are important. (So if the file is namedhello.java with a small h it will not work). On all computers, upper and lower case inside the

 program are important.

The first line

Page 81: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 81/293

 

class Hello

says that this source program defines a class called Hello. A class is a section of a program. (A

 better definition will come later on in these notes.) Small programs often consist of just oneclass. When the program is compiled, the compiler will make a file of bytecodes called

Hello.class.

QUESTION 2:

Here is the first line of another Java program:

class AddUpNumbers

1. What should the source file be named?2. What is the name of the bytecode file the compiler creates?

Answer:

1. What should the source file be named?o AddUpNumbers.java

2. What is the name of the bytecode file the compiler creates?o AddUpNumbers.class

Identifiers and Reserved Wordsclass Hello{public static void main ( String[] args ){System.out.println("Hello World!");

}}

Most classes contain many more lines than this one. Everything that makes up a class is placed

 between the first brace { and its matching last brace } .

The name of the class (and therefore the name of the file) is up to you. In programming, thename for something like a class is called an identifier. An identifier consists of alphabeticalcharacters and digits. The first character must be alphabetical, the remaining characters can bemixed alphabetic characters and digits (plus the two characters '_' and '$' underscore and dollar sign). No spaces are allowed inside the name. Chapter nine discusses this in more detail.

Page 82: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 82/293

 

Usually a class name starts with a capital letter, but this is not required. A source file shouldalways end with .java in lower case.

A reserved word is a word like class that has a special meaning to the system. For example,

class means that a definition of a class immediately follows. You must use reserved words only

for their intended purpose. (For example, you can't use the word class for any other purposethan defining a class.)

QUESTION 3:

Which of the following look like good identifiers?

1. ExcitingGame2. Lady Luck3. x324. lastChance5. x/y

Answer:

1. ExcitingGame OK: mixed upper and lower case is allowed2. Lady Luck BAD: no spaces allowed inside an identifier3. x32 OK: identifiers must start with an alphabetical character, but the rest

can be digits.4. lastChance OK: class names usually start with a capital, but identifiers

don't have to.

5. x/y BAD: the slash is not allowed inside an identifier

Between the Braces

class Hello{public static void main ( String[] args ){System.out.println("Hello World!");

}}

The small Java programs in this chapter all look like this:

class Hello{

}

Page 83: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 83/293

 

Everything that a program does is described between the first brace and the final brace of a class.To start with, we will have only one class per source code file, but in later chapters there may beseveral classes per source code file.

The example program writes Hello World! to the monitor. It looks like a lot of program for such

a little task! But, usually, programs are much longer and the details you see here help to keepthem organized. The line

public static void main ( String[] args )

shows where the program starts running. The word main means that this is the main method — 

where the Java virtual machine starts running the program. The main method must start with thisline, and all of its parts must be present. Wherever there is one space it is OK to have anynumber of spaces. The spaces surrounding the parentheses in the third line are not required. Thefifth line shows parentheses not surrounded by spaces (but you could put them in).

QUESTION 4:

Is the following acceptable?

public static void main(String[] args )

Answer:public static void main(String[] args )

The Java compiler would accept the line. But it looks sloppy to human eyes.

 println()

class Hello{public static void main ( String[] args ){System.out.println("Hello World!");

}}

There are rules about where spaces may be used, and optional style rules about how to make a program look nice. Rather than look at a list of rules, look at some Java programs and pick up therules by example.

The main method of this program consists of a single statement:

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

Page 84: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 84/293

 

This statement writes the characters inside the quotation marks to the monitor of the computer system. (The quotation marks are not written.)

A statement in a programming language is a command for the computer to do something. It islike a sentence of the language. A statement in Java is followed by a semicolon.

Methods are built out of statements. The statements in a method are placed between braces { and

} as in this example.

The part "Hello World!" is called a string. A string is a sequence of characters. This program

writes a string to the monitor and then stops.

QUESTION 5:

(Review: ) Say that the file Hello.java contains the example program. The file is contained inthe subdirectory C:\Temp on the hard disk. In order to run it, what two things must be done?

Answer:

(1) The program must be compiled into bytecode with the Java compiler, then (2) run using theJava interpreter.

Review of Running a Java ProgramCopy and paste the example program into a text editor (like Notepad or Crimson), and then saveit to a file called Hello.java in the current directory. (Microsoft calls "directories" by the name

"folders".)

To run the program, check that the default directory of the command interpreter contains thesource file. Do this by using the command DIR *.java to list the files in the directory. One of 

the files should be Hello.java. To see all the files, just type the command DIR.

C:\TEMP>DIR *.java

Volume in drive C has no label.Volume Serial Number is 7C68-1E55

Directory of C:\TEMP

08/23/98 01:07a 115 Hello.java1 File(s) 115 bytes

2,448,368,640 bytes free

Page 85: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 85/293

 

If you don't see the source file, use the Change Directory command CD to get to the correctsubdirectory. To compile the source file (thereby producing a file of bytecodes) enter thecommand javac Hello.java. Finally, to run it, enter the command java Hello.

C:\TEMP>javac Hello.javacompiling: Hello.java

C:\TEMP>java Hello

Hello World!

C:\TEMP>

QUESTION 6:

• What is the command that runs the Java compiler?• What is the command that runs the Java interpreter?

Answer:

• What is the command that runs the Java compiler?o  javac

• What is the command that runs the Java interpreter?o  java

Syntax ErrorsIt is likely that you will do something wrong. Here is the sample program with a deliberate error:

Class Hello{public static void main ( String[] args ){System.out.println("Hello World!");

}}

QUESTION 7:

What is the error? (Don't spend much time looking; it is really small.)

Answer:

The reserved word "class" has been changed to "Class" with a capital "C".

Page 86: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 86/293

 

A Capital Mistake

The reserved word "class" has been changed to "Class" with a capital "C". This is called a syntaxerror. A syntax error is a "grammatical error" in using the programming language. Here is whathappens when the mistaken program is compiled:

The compiler tried to translate the source code into bytecode but got confused when it got to acapital "C" it did not expect. The error message is not very clear. They never are. But at least itshows where the compiler got confused. The compiler did not create a new bytecode file becauseit stopped translating when it got to the error.

C:\Temp>javac Hello.java

compiling: Hello.javaHello.java:1: Class or interface declaration expected.Class Hello^1 error

QUESTION 8:

To fix this error and run the program what must you do?

Answer:

To fix the error, use a text editor to fix the source file.

Fixing Errors

Page 87: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 87/293

 

Usually you will have two windows open on your computer: one for a text editor (such as Notepad or Crimson) and one for the command interpreter.

To fix the syntax error, change the "C" to a "c" and save the file. Now use javac to compile the

source file, and if there are no errors, use java to run it.

QUESTION 9:

If you forget to save the file after making the change, and then enter the command javac

Hello.java, what will happen?

Answer:

You would compile the old, uncorrected version of the source file on hard disk and get the same

error message.

When you use a text editor you change the source program that is in main memory. If you don'tsave your changes, the file on disk does not change. The compiler javac uses the file that is

currently on the hard disk.

This is a common mistake.

Page 88: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 88/293

 

Edit, Compile, Run Cycle

Until your program runs correctly:

1. Edit the program (the source file).2. Save the program to the hard disk with the "Save" or "Save As" command of 

the editor.3. Compile the program with the javac command.4. If there are syntax errors, go back to step 1.5. Run the program with the java command.6. If there are bugs, go back to step 1.7. When it runs correctly, quit.

This is called the "edit-compile-and-run" cycle. Expect to go through it many times per program.

A Java development environment like Eclipse or BlueJ is more sophisticated, but you still gothrough the same fundamental cycle.

QUESTION 10:

If a source program compiles correctly in step 3, does that mean that it will run correctly?

Answer:

 No.

Bugs

class Hello{public static void main ( String[] args ){System.out.println("Hello Neptune!");

}}

Just because a program compiles and runs does not mean that it is correct. For example, say thatyour assignment is to create a program that writes "Hello World!" on the computer monitor. Butyou write the above program.

Page 89: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 89/293

 

When a program compiles without any syntax errors, but does not perform as expected when itruns, the program is said to have a bug.

QUESTION 11:

1. Will this program compile without syntax errors?2. Will this program run?3. Does the program meet the assignment?

Answer:

1. Will this program compile without syntax errors?o  Yes.

2. Will this program run?o  Yes.

3. Does the program meet the assignment?o No — it has a bug.

Longer Example Program

class Emily{public static void main ( String[] args ){System.out.println("A bird came down the walk:");System.out.println("He did not know I saw;");System.out.println("He bit an angle-worm in halves");System.out.println("And ate the fellow, raw.");

}}

Usually bugs are much more difficult to find than the one in this program. The longer a programis, the more bugs it is likely to have, and the more difficult it is to find them. It is a good idea to practice with short programs where syntax errors and bugs are more easily seen before movingon to longer programs.

Above is a somewhat longer example program.

The program is much like the "Hello World!" program but the main method has more statements

inside of it. Create this program with a text editor, compile and run it.

Save the program in a file called Emily.java. The compiler will create a bytecode file called

Emily.class.

Page 90: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 90/293

 

QUESTION 12:

What does this program write to the monitor when it is run?

Answer:

Each System.out.println statement writes out the characters inside the quote marks:

A bird came down the walkHe did not know I saw;He bit an angle-worm in halvesAnd ate the fellow, raw.

Another Exampleclass Haiku{public static void main ( String[] args ){

System.out.println( ); 

System.out.println( ); 

System.out.println( );}

}

 Now say that your assignment is to create a program that writes the following to the computer monitor:

On a withered branchA crow has just alighted:Nightfall in autumn.

Above is the program that is to perform this task, but with some blank boxes for you to fill in.

The extra lines between program statements don't hurt. Blank lines often make a program easier to read.

QUESTION 13:

Fill in the blanks of the program. (You can do this using your mouse with copy and paste.)

þÿ

þÿ

þÿ

Page 91: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 91/293

 

Answer:

The completed program is given below:

Finished Program

Here is the completed program. Be sure that you put the quote marks where they belong. If youforget just one of them, the compiler will become confused and will not translate your program!

class Haiku{public static void main ( String[] args ){System.out.println("On a withered branch");

System.out.println("A crow has just alighted:");System.out.println("Nightfall in autumn.");

}}

If you have been creating the example programs and compiling and running them, you may havenoticed that spaces and new lines in the program are not critical. (However, you can't put spacesin the middle of a word, and spaces inside the quote marks do matter.) For example, thefollowing version of the program will compile correctly and will do exactly the same thing as theoriginal version when it is run:

class

Haiku{public static void main(String[] args ){

System.out. println( "On a withered branch");System . out.println("A crow has just alighted:" );

System.out.println("Nightfall in autumn.");}}

The compiler does not "see" the two dimensional layout of the program. It regards the programas a stream of characters, one following the other.

However, humans are sensitive to the layout of text, and it is important to be neat and consistent

when you create a source file. Although the second version of the program runs correctly, it ismuch harder for a person to understand.

QUESTION 14:

If there were a slight mistake in the poorly laid-out program, would it be easy to find?

Page 92: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 92/293

 

Answer:

 No. Everything is so confused, a slight mistake is easily overlooked.

Comments

// Write three lines of a poem to the computer monitorclass Haiku{public static void main ( String[] args ){System.out.println("On a withered branch" );System.out.println("A crow has just alighted:");System.out.println("Nightfall in autumn.");

}

}

A comment is a note written to a human reader of a program. A comment starts with the twocharacters // (slash slash). Those characters and everything that follows them on that one line

are ignored by the java compiler.

The program compiles and runs exactly the same as before. The green color in the above program was added by hand. However, most program editors (such as Crimson and Notepad++)are smart enough to recognize comments and will display them in color. Of course, the text filecontains only the characters you have entered.

QUESTION 15:

Are comments included in the bytecode translation of a Java program?

Answer:

 No. Remember, the compiler completely ignores them. Comments are just for humans.

Many Comments

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

Page 93: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 93/293

 

System.out.println("On a withered branch" ); // Write first line ofthe poem

System.out.println("A crow has just alighted:"); // Write 2nd line ofthe poem

System.out.println("Nightfall in autumn."); // Write 3rd line ofthe poem}

}

Comments can be placed after a program statement to explain what it does, as here.

As with all comments, the // and everything after it on that line are ignored by the compiler. The

 program statement in the start of the line is not affected by the comment.

QUESTION 16:

Would you ever want to write an entire paragraph of comments?

Answer:

Yes.

Many-line Comments

/* Program 1Write out three lines of a poem.The poem describes a single moment in time,using 17 syllables.*/

class Haiku{public static void main ( String[] args ){System.out.println("On a withered branch" );System.out.println("A crow has just alighted:");System.out.println("Nightfall in autumn.");

}}

Often you want to write a comment that spans several lines, as above.

With this style of comment, everything between the two characters /* and the two chracters */

are ignored by the compiler.

Page 94: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 94/293

 

The / and the * must not have any character between them. There can be many lines of 

comments between the /* pair and the */ pair.

The /* and the */ can start and stop anywhere on a line. Everything between the pair is a

comment ignored by the compiler.

QUESTION 17:

Is the following correct?

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

System.out.println /* print a line containing the following string */("On a withered branch" );System.out.println("A crow has just alighted:");System.out.println("Nightfall in autumn.");

}}

Answer:

Yes, although it is ugly and not commonly done.

Commenting Out Code

class BuggyHaiku{public static void main ( String[] args ){System.out.println("On a withered branch" );

/*System.out.println("A crow has just alighted:");System.out.println("Nightfall" in autumn.");

*/

}}

Comments are useful for debugging. For example, the above program has a syntax error. Let'ssay that you are having problems finding the error. One way to narrow down the problem is toremove some of the code from consideration by turning it into a comment. Compile and run the program.

Page 95: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 95/293

 

If the modified program works as expected, the error must be in the commented section.Gradually decrease the commented section until you find the error.

QUESTION 18:

Why would you ever want to use comments to help a person understand your program?

Answer:

The person might be you. Comments are often notes to yourself about what something is, or whyyou did something the way you did.

Bracesclass Haiku{public static void main ( String[] args ){System.out.println( "On a withered branch" );System.out.println( "A crow has just alighted:" );System.out.println( "Nightfall in autumn." );

}}

Examine the program. For every left brace

there is a right brace

that matches. Usually there will be sets of matching braces inside other sets of matching braces.The first brace in a class (a left brace) will match the last brace in that class (a right brace). A

 brace can match just one other brace.

Use indenting to show how the braces match (and thereby show the logic of the program). Look at the example.

Increase the indenting by two spaces for statements inside a left and right brace. If another pair of braces is nested within those braces, increase the indenting for the statements they contain byanother two spaces. Line up the braces vertically.

Page 96: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 96/293

 

There are many styles of laying out a program. If you are reading a printed text book in additionto these notes, it may use a different style.

QUESTION 19:

Mentally circle the matching braces in the above program.

Answer:

The matching braces are indicated in color, below:

Matching Pairsclass Haiku{public static void main ( String[] args )

  {System.out.println( "On a withered branch" );System.out.println( "A crow has just alighted:" );System.out.println( "Nightfall in autumn." );

  }}

 Notice that in addition to pairs of braces that match, there are pairs of parentheses (), and pairs

of brackets [] that match. Large programs will have many of these matching pairs, which areused to group sections of the program together.

Format your program as you write it. This helps you see the logic you are creating, and is atremendous help in programming.

Text editors intended for program creation (called program editors) and more sophisticated programming environments always have ways to show matching braces. This is really valuable.You should definitely learn to use this feature with whatever editor or environment you areusing.

QUESTION 20:

If a program is missing just one brace, will it compile?

Page 97: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 97/293

 

Answer:

 No. But if you have been neat, it is easy to find where the missing brace should go.

End of the Chapter

Brace yourself! you have reached the end of the chapter. You may wish to review the following.Click on a subject that interests you to go to where it was discussed.

• Hello World example program.• methods and classes. • Syntax Errors. • Edit, compile, and run cycle. •

Program bugs. • Importance of spaces and newlines in programs.• Comments• Multiline Comments• Matching braces. 

The next chapter will discuss a way to run the programs in these notes without actually typingthem in, and discusses details of using Notepad.

You have reached the end of the chapter.

CHAPTER 7 — Running Example Programs

Chapter Topics:

• How to copy, paste, compile, and run programs• Starting Notepad and the command prompt• Copying text to the clipboard• Pasting text from the clipboard to Notepad• Saving the text as a source file

• Running a program

These notes show many example programs. You need to run them and play with them. The mosteffective way to learn programming is to fiddle around with example programs.

You don't have to type in the programs to run them. If you can see the program in a browser window, then you can easily copy it to Notepad (or other editor) and then save the text to a file.Once that is done, you can compile and run the program as described in the previous chapter.

Page 98: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 98/293

 

If this is perfectly clear skip this chapter. If not, this chapter walks you through these steps.

Super Easy Way to Run Java: The web site http://ideone.com/ lets you copy-and-paste Javacode into a web page text box, then compile and run it completly within your browser. This isideal for playing with the example programs in many of these chapters.

QUESTION 1:

Is it sometimes beneficial to type in a program rather than just copying it?

Answer:

Yes — sometimes typing in a program forces you to see details you would otherwise miss. Other times it is a waste of effort. Of course, not running the program at all is a supreme waste of 

opportunity.

Notes

1. The steps are shown for a computer running Windows XP. Nearly the same steps can be usedfor other varieties of Windows. The software used in these notes is the minimum possiblerequirement, free on all Windows computers. Even if you have better software it is wise to startout using this minimum.

2. If you use an integrated programming environment (IDE) such as Eclipse or  BlueJ you cancopy programs into your environment and run them. But most IDEs expect you to make a program part of a project and require several preliminary steps before you can run it. To quicklycopying a program and run it, the steps described here are best.

3. Rather than use Notepad, you can use the Crimson programming editor. It is free, simple andeasy to use, but it is a big improvement over Notepad. See www.crimsoneditor.com.

4. Another popular programming editor is Notepad++ . See notepad-plus-plus.org.

5. For writing big programs, a free Java IDE such as  BlueJ may be your best choice. Seewww.bluej.org. Other IDEs are described here:

http://www.apl.jhu.edu/~hall/java/IDEs.html.

If you decide to use an IDE you will have to learn how to use it. For short programs, Notepad (or Crimson) and the DOS command line are easiest.

Page 99: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 99/293

 

QUESTION 2:

Can Microsoft Word be used as a program editor?

Answer:

 No, not easily. Word processors such as Word create files that compilers cannot use. (Actually,Word can be forced to create a suitable file, but it is not worth the effort.)

Copying and Pasting

class HelloPlanets{public static void main ( String[] args ){String[] planets = {"Mercury", "Venus", "Earth", "Mars", "Jupiter",

"Saturn", "Uranus", "Neptune", "Pluto"}; 

for ( int j=0; j< planets.length; j++ ){System.out.println("Hello " + planets[j] +"!" );

}}

}

Above is an example Java program. Just for fun, the program is different than the previousexamples. The details won't be explained until later chapters.

Here is an outline of how to copy and run the program. You can try this now, or continue readingthis chapter (which shows the method step-by-step).

For Most Windows Operating Systems:

1. Start Notepad and a command prompt window.2. In the command window, use the CD command to go to a convenient

subdirectory.o In this example, C:\Temp will be used.

"Subdirectory" is the another word for "folder".o COPY: Copy the program into the clipboard .

11 In the browser window (this window), put the mousepointer on the "c" of "class" in the sample program.

Page 100: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 100/293

 

11 Push down on the left mouse button, then drag downthorugh the final "}" . The text you dragged over will behighlighted.

11 Lift up on the mouse button.11 Click on the "Edit" menu of the browser and then click on

"Copy". This makes a copy of the program in the clipboard , a

section of the computer's main memory.o PASTE: Click inside the Notepad window to make it active. Go to its

"Edit" menu and click on "paste." You should now have have a copy of the program in Notepad.

o SAVE: Click on the "File" menu of Notepad and "Save As"HelloPlanets.java.

 You will have to "navigate" to the same subdirectory as in step2.

Be sure to match upper and lower case letters with the classname.

o RUN: Run the program:

a1 Click in the DOS window. Type DIR to check thatHelloPlanets.java is there.

b1 Compile the program: C:\Temp> javac HelloPlanets.javac1 Run the program: C:\Temp> java HelloPlanets

QUESTION 3:

How do you start Notepad?

Answer:

Start Notepad by using the Start button in the bottom left of your screen and following the pathto Notepad: Start-Programs-Accessories-Notepad.

Step 1: Start Notepad and the Command

PromptHere is what this looks like on my Windows computer as I start Notepad. (Your computer shouldlook about the same, except that you might have better taste in wallpaper.)

Windows puts icons for recently used programs in the left-hand menu bar, so you might find Notepad there. Otherwise you may have to hunt for it. Try: Start/All Programs/Accessories/.

Page 101: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 101/293

 

If you are using another programming editor (such as Crimson or Notepad++) find it the sameway you find Notepad. But often a shortcut to the editor is located on the desktop. If so, justdouble click it.

After Notepad starts you should see this:

Page 102: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 102/293

 

QUESTION 4:

(Review:) How do you start the command prompt window (also called the DOS window)?

Answer:

Start the DOS window (the command prompt window) by beginning with the Start button, also.The DOS icon will be one of the first choices if you have used it recently.

Step 1 (Continued)

Page 103: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 103/293

 

Look for the command prompt window under Start/All Programs/Accessories/ — the samelocation as for Notepad. Above is what it looks like when both Notepad and DOS are running.

 Notepad and DOS each run in their own window. This is the bare minimum setup that these Javanotes assume.

The command prompt window starts up in some default subdirectory. (Exactly which directorydepends on your system.) When you type a command into the command prompt window it willautomatically apply to only the files in the default directory. For example, if you type javac

MyProg.java the system will expect MyProg.java to be in that directory.

QUESTION 5:

Is the directory that DOS starts up in the one you want?

Answer:

Usually not. You need to change the default directory to the one you want.

Page 104: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 104/293

 

Step 2: Use CD to change the Default

Directory

This example uses the subdirectory called C:\Temp which should already exist on your 

computer. (If it does not exist, create it using Window's Explore, or other means.) Temp is asubdirectory that is used for temporary files. Use it for example programs that you don't want tokeep permanently. Use CD to Change the default Directory.

Details: 

If you have some other subdirectory that you wish to use, use CD to make it the default instead of 

\Temp.

If DOS starts up with a default directory on a disk other than C use CD to go to the Tempdirectory on that disk. You might want to check with people to see if this is OK.

If DOS starts up with a default directory on a disk other than C, but you want to use C, enter C:

to switch disks:

D:\Mystery\>C:C:\>C:\>CD TempC:\Temp>

QUESTION 6:

Should you use C:\Temp for your important programming projects?

Page 105: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 105/293

 

Answer:

 No... later on, create another directory to hold your projects.

Step 3: Copy the Program

Step 3 is to copy the characters of the program from the Web browser's window into theclipboard. The clipboard is a section of the computer's main memory that is used to copy data between various application programs.

Later (in step 4) the characters will be copied from the clipboard into Notepad. Here is theexample program, again:

class HelloPlanets{public static void main ( String[] args ){String[] planets = {"Mercury", "Venus", "Earth", "Mars", "Jupiter",

"Saturn", "Uranus", "Neptune", "Pluto"}; 

for ( int j=0; j< planets.length; j++ ){System.out.println("Hello " + planets[j] +"!" );

}}

}

First, the characters of the program must be "highlighted" by clicking the mouse on the firstcharacter, and dragging to the last character:

1. In the browser window (this window), put the mouse pointer on the "c" of "class".

2. Push down on the left mouse button. Without lifting up on the mouse button,drag down until the final "}" of the program is covered.

3. Lift up on the mouse button.

Be careful not to click the mouse again in the window or you will cancel your selection. (But youcan always start over.) After you have done this, you should see something like the following:

Page 106: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 106/293

 

The last part of Step 3 is to copy the selected text into the clipboard.

QUESTION 7:

Look at the top menu bar of your browser window. Is there a menu labeled "Edit" ?

Answer:

That is the menu you want.

Last Part of Step 3

Page 107: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 107/293

 

These notes show copy and paste with Firefox, but the same will work with other browsers. The

last part of Step 3 is:

• Click on the "Edit" menu of the browser and then click on "Copy". This makesa copy of the program in the clipboard , a section of the computer's mainmemory.

The characters that you have selected in the browser window are now also held in the clipboard.

QUESTION 8:

What is it called when you copy characters from the clipboard into another application?

Answer:

Paste.

Step 4: Paste into Notepad

Step 4 is:

• PASTE: Click inside the Notepad window to make it active. Go to its "Edit"menu and click on "paste." You should now have have a copy of the programin Notepad.

At right is what Notepad looks like as you are pasting into it and what it looks like after pasting.

Page 108: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 108/293

 

The margins are often not as nice as in the original. Also, my Notepad window is too small toshow the complete program, but the complete program is there. You can make your Notepadwindow bigger by clicking and dragging on its lower right corner.

QUESTION 9:

Can you save the text in Notepad to a disk file?

Answer:

Yes.

Step 5: Save the Program

Page 109: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 109/293

 

The next step is to save the text in Notepad to a source file.

• SAVE: Click on the "File" menu and "Save As"

You will have to "navigate" to the default subdirectory of the command prompt window (seestep 2). You will get a window that allows you to navigate to the subdirectory where the fileshould be saved.

For this example, the subdirectory is C:\Temp. If you see this directory, click on it. (If you don't,

use the various controls to move around until you do see it.) There will probably bemiscellaneous strange files in this directory, but they don't hurt.

The file should be given the name that is the same as the class that contains the "main" method.Our first programs will contain only one class, so use that class name. The last part of the filename should be .java (don't forget the period.) Here is the start of this step:

Page 110: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 110/293

 

Type in the name of the source file:

HelloPlanets.java

in the "File Name" text box. Now Select "All Files" in the "Save as Type" text box. Finally, click on the "Save" button.

Warning (1): In some versions of Notepad you must use quote marks around the name of thefile. So in the above you would type "HelloPlanets.java" (quotes included) into the File name box.

Warning (2): Be sure that you Save as type All Files 

Warning (3): Be sure that you pick Encoding ANSI 

QUESTION 10:

Hopefully, the file HelloPlanets.java has been saved to the subdirectory C:\Temp, the same

one that the command prompt window is using. How can you confirm that this indeed happened?

Answer:

Click in the command prompt window to bring it forward and to make it the active window.Then enter the command DIR to list the files.

Page 111: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 111/293

 

Step 6: Run the Program

If there are too many files in the subdirectory, enter the command DIR *.java to see just those

files that end in .java 

If you see the file HelloPlanents.java.txt then you need to put quote marks around the

filename in Notepad. To complete Step 6, compile and run the program:

• RUN: Run the program:1. Click in the command prompt window . Do a DIR to check that

HelloPlanets.java is there.2. Compile the program: C:\Temp> javac HelloPlanets.java 3. Run the program: C:\Temp> java HelloPlanets

The following shows this being done:

Page 112: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 112/293

 

Well, that is the method. It uses skills that users of Windows application programs are familiar with. They will have found this process fairly easy. If you did not, it is merely a matter of  practice.

QUESTION 11:

Is Pluto a planet?

Answer:

It was when I first wrote the program.

 Now, it is not.

It may seem strange that a correctly written program can become buggy without being altered.But this is actually common. Circumstances external to a program often change, so the programmust be revised. Much of what professional programmers do is program maintainance: keeping programs up to date with changing requirements.

End of the Chapter

You have reached the end of the chapter. If you are unclear about it, take a break, and then read

the chapter again. Or find a friend that knows how to do this, perhaps the same friend youannoyed at the end of the previous chapter. This stuff is much easier if you see someone do it afew times.

You may wish to review the following. Click on a subject that interests you to go to where it wasdiscussed.

• Outline of the method.•

Step 1: Starting Notepad and the command prompt.• Step 2: Using CD to go to a Subdirectory.• Step 3: Copying the program.• Step 4: Paste into Notepad.• Step 5: Save the program to a file.• Step 6: Run the program.

The next chapter will discuss the beginning elements of the Java language (at last!).

Page 113: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 113/293

 

You have reached the end of the chapter.

CHAPTER 8 — Primitive DataComputer memory stores arbitrary bit patterns. Making sense of these patterns involves the useof data types.

Chapter Topics:

• Data Types• Primitive Data vs. Objects•  The Eight Primitive Data Types of Java• Numeric Data Types• Character and Boolean Data Types

QUESTION 1:

Say that you came across the following torn slip of paper. What can it mean?

What can this mean?

MIX

Answer:

 Not easy to say, without knowing more.

Data Types

Page 114: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 114/293

 

You would like to see the rest of the paper, or know where it came from. Without knowing thecontext, it is hard to say what MIX means. It could be 1009 in Roman numerals, or it could bethe English word "mix" (which itself has several meanings), or it could be the last name of theold-time radio hero Tom Mix. It could be part of a label on a music CD, "MTV Dance MIX", or  part of a label on a bottle, "BLOODY MARY MIX". Or maybe you are looking at it upside

down and it should be "XIW". Of course, it might not be English at all. Without knowing thecontext, a string of letters has little meaning.

Computer memory stores arbitrary bit patterns. As with a string of letters, the meaning of a stringof bits depends on how it is used. The scheme being used for a particular string of bits is its data

type. 

A data type 

• Is a scheme for using bits to represent values.• Values are not just numbers, but any kind of data that a computer can

process.• All values in a computer are represented using one data type or another.

For example

0000000001100111

is a pattern of 16 bits that might be found somewhere in computer memory. What does itrepresent?

Without knowing more about how the above pattern is being used, it is impossible to say what itrepresents. The type short is one of Java's data types. If the pattern is of data type short, then it

represents the value 103 (one hundred and three).

QUESTION 2:

What does the following 16 bit pattern represent?

0000000000000000

Page 115: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 115/293

 

Answer:

Without knowing more about how the pattern is being used, it is impossible to say.

There are Many Data Types

You might be tempted say that the pattern 0000000000000000 represents "zero". But it doesn'tnecessarily. Even such an obvious pattern has no automatic meaning.

If you were told that the above pattern were of type short, then you would know that it

represents the integer zero. Here is another pattern:

1111111110011001

As a short, this pattern represents -103 (negative one hundred three).

There are uncountably many types of data that can be represented in the memory of a computer.If specific patterns always had specific meanings, then only a few types of data could berepresented. This would be much too restrictive. Many data types are invented by programmersas they write programs. Without this flexibility computers would be much less useful.

The main memory of a general purpose computer (such as a desktop or a laptop computer)contains very many bits. Programs can use this memory with whatever data types they need. For example, one program may use data type int with four bytes of memory, and data type double

with another eight bytes of memory. A different program may use the same memory withdifferent data types.

 Not all machines use memory this way. A simple electronic calculator, for example, usesmemory for one purpose only: to store floating point numbers. It uses only one data type, andcan do only those few things with that data type that it has been wired to do. The engineers whodesigned the calculator decided how to represent numbers with bit strings, and then designed theelectronics to work with just those strings. This is too restrictive for a general purpose computer.

QUESTION 3:

Do you imagine that the computers of the 1960's were built to handle audio data?

Answer:

 No — certainly this was not a common use for computers then.

Page 116: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 116/293

 

Primitive Data Types

byte

short

int

long

float

double

char

boolean

But some 1960's computers did deal with audio data; it was merely a case of inventing a way torepresent audio with bit patterns and then writing the programs for it.

It would be awkward if every time you used data you had to invent your own scheme torepresent it with bits. There are types of data that are so fundamental that ways to represent themare built into Java. These are the primitive data types. The eight primitive data types are: byte,short, int, long, float, double, char, and boolean.

Upper and lower case characters are important in these names. So "byte" is the name of a primitive data type, but "BYTE" is not. Computer languages where case is important are calledcase sensitive. Some languages are not case sensitive, especially old languages that weredesigned when data entry equipment did not have lower case characters.

In the phrase primitive data type the word primitive means "a fundamental component that isused to create other, larger parts." This word is used frequently in computer science. To solve alarge problem, you look for the primitive operations that are needed, then use them to build thesolution.

QUESTION 4:

(Trick Question: ) Is Int a primitive data type?

Is Int a primitive data type?

Answer:

 No — it is not on the list of primitive data types (the word that starts with a small "i" is on the

list: int). Remember that Java is case sensitive.

Objects

Page 117: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 117/293

 

All data in Java falls into one of two categories: primitive data and objects. There are only eight primitive data types. However, Java has many types of objects, and you can invent as manyothers as you need. Any data type you invent will be a type of object.

Much more will be said about objects in future chapters (since Java is a object oriented 

 programming language). The following is all you need to know, for now:

• A primitive data value uses a small, fixed number of bytes.•

 There are only eight primitive data types.• A programmer can not create new primitive data types.

• An object is a big block of data. An object may use many bytes of memory.• An object usually consists of many internal pieces.•  The data type of an object is called its class.• Many classes are already defined in Java.• A programmer can invent new classes to meet the particular needs of a

program.

A (crude) analogy is that a primitive data value is like a nut or a bolt, but an object is like awhole machine. If you want to learn more about objects right away, it would not hurt to jump

ahead to the Chapter On Objects and read a few pages.

QUESTION 5:

Are numbers of fundamental importance to computer programs?

Answer:

Yes.

Numeric Primitive Data Types

 Numbers are so important in Java that 6 of the 8 primitive data types are numeric types.

Page 118: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 118/293

 

There are both integer and floating point primitive types. Integer types have no fractional part;floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do. But in main memory, there are no decimal points: even floating point values arerepresented with bit patterns. There is a fundamental difference between the method used torepresent integers and the method used to represent floating point numbers.

Each primitive type uses a fixed number of bits. This means that if you are using a particular datatype then the same number of bits will be used no matter what value is represented.

For example, all values represented using the short data type use 16 bits. The value zero (as a

short) uses 16 bits and the value thirty thousand uses 16 bits.

All values represented using the long data type use 64 bits. The value zero (as a long) uses 64

 bits, the value thirty thousand uses 64 bits, and the value eight trillion uses 64 bits.

Values that are large in magnitude (negative or positive) need more bits to be represented. This is

similar to writing out numbers on paper: large numbers need more digits. If a value needs more bits than a particular data type uses, then it cannot be represented using that data type.

In the tables, E means "ten to the power of". So 3.5E38 means 3.5 x 1038 

Integer Primitive Data Types

Typ

eSize Range

byte 8 bits -128 to +127

short

16bits

-32,768 to +32,767

int32

bits

-2 billion to +2 billion

(approximately)

long64

bits

-9E18 to +9E18

(approximately)

Floating Point Primitive

Data Types

Type Size Range

float32

bits

-3.4E38 to

+3.4E38

doubl

e

64

bits

-1.7E308 to

1.7E308

Page 119: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 119/293

 

QUESTION 6:

Say that you want to deal with the number 1,023,004 in your computer program. Would datatype short be an appropriate choice?

Can data type short hold the value 1,023,004 ?

Answer:

 No. Data of type short can be only in the range -32,768 to +32,767.

More Bits for More Range

Larger ranges of numeric values require more bits. The different sizes for integer data enable youto pick an appropriate size for the data you are working with. Usually you should pick a datatype that has a range much greater than the range of numbers you expect to deal with. If a program uses only a few dozen variables it will run just as fast and take up about as much mainmemory no matter what size is used for its variables.

Why do the small sized data types exist, then? Well, many real-world programs deal withmassive amounts of data (billions of data items) and then using the smaller sizes may save

significant amounts of space and time. But we will not use that much data in these notes. Usuallyyou should use int or double for your numeric data. When you write a program you do not have

to know how to represent a number in bits. You can type the number just as you would on atypewriter. This is called a literal. The word "literal" means that a value is explicitly shown inthe program.

For example, 125 literally repesents the value one hundred twenty five. Integer  literals in a program are written as in a book, except there are no commas:

125 -32 16 0 -123987

All of the above examples are 32 bit int literals. A 64 bit long literal has a upper case 'L' or lower case 'l' at the end. However, NEVER use the lower case 'l' because it is easily confusedwith a digit '1'.

125L -32L 16L 0l -123987l

The last two examples use lower case 'l' and are very confusing.

Page 120: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 120/293

 

QUESTION 7:

Is the following an integer literal?

197.0

Is the following an integer literal? 197.0

Answer:

 No — it has a decimal point.

Floating Point TypesIf you use the literal 197.0 in a program, the decimal point tells the compiler to represent thevalue using a floating point primitive data type. The bit pattern used for floating point 197.0 isvery much different than that used for the integer 197. There are two floating point primitivetypes.

Data type float is sometimes called "single-precision floating point". Data type double has

twice as many bits and is sometimes called "double-precision floating point". These phrasescome from the language FORTRAN, at one time the dominant programming language.

In programs, floating point literals have a decimal point in them, and no commas (no thousand'sseparators):

123.0 -123.5

-198234.234 0.00000381

Note: Literals written like the above will automatically be of type double. Almost always, if you

are dealing with floating point numbers you should use variables of type double. Then the data

type of literals like the above will match the data type of your variables. Data type float should

 be used only for special circumstances (such as when you need to process a file of data

containing 32 bit floats).

Floating Point Primitive

Page 121: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 121/293

 

Data Types

Type Size Range

float32

bits

-3.4E+38 to

+3.4E+38

doubl

e

64

bits

-1.7E+308 to

1.7E+308

QUESTION 8:

(Thought question: ) Do you think that using float instead of double saves a significant amount

of computer memory?

(Thought question: ) Do you think that using float instead of double saves a significant amountof computer memory?

Answer:

 No. For most programs using variables of type double will cost only a few extra bytes in a

 program thousands of bytes long.

Floating Point LiteralsSometimes you need to explicily ask for a single-precision float literal. Do this by putting a

lower case 'f' or upper case 'F' at the end, like this:

123.0f -123.5F

-198234.234f 0.00000381F

Sometimes you need to explicily ask for a double-precision double literal. Do this by putting a

lower case 'd' or upper case 'D' at the end, like this:

123.0d -123.5D

-198234.234d 0.00000381D

Remember, that without any letter at the end, a floating point literal will automatically be of typedouble.

Page 122: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 122/293

 

QUESTION 9:

Do you think that the following is legal?

8912D

Do you think that the following is legal?

8912D

Answer:

Yes. The 'D' will make the literal a double (even though it lacks a decimal point). However, to

avoid confusion, always include a decimal point in a floating point literal, even where it is notrequired.

Scientific Notation

You will sometimes see scientific notation. The following are all double-precision literals:

1.23E+02 -1.235E+02

-1.98234234E+05 3.81E-06

The big "E" means "times 10 to the power of" . The integer that follows it says what power of ten

to multiply the rest of the number by.

Another way to say this is that the integer that follows "E" says in which direction and for howmany places to shift the decimal point. Positive integers mean right shifts; negative integersmean left shifts.

QUESTION 10:

What is the usual way to write this number: 1.9345E+03

1.9345E+03

Answer:

1934.5

The +03 says to move the decimal point three places right.

Page 123: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 123/293

 

Precision of Floating Point Numbers

Consider writing the value 1/3 in decimal notation:

0.333333333333333333

There is no limit to the number of 3's required for complete accuracy. With a limited amount of  paper, you can not be completely accurate. With a data type, there is a limited number of bits.Those bits cannot accurately represent a value that requires more than that number of bits.

The data type float has 23 bits of precision. This is equivalent to only about 7 decimal places.

(The rest of the 32 bits are used for the sign and size of the number.)

The number of places of precision for float is the same no matter what the size of the number.Data type float can represent numbers as big as about 3.4E+38. But the precision of these large

numbers will also be about 7 decimal digits.

Remember: data type float has about the range and precision of a cheap electronic calculator.

This is usually not sufficient.

QUESTION 11:

What is wrong with the following constant, expected to be of type float?

1230.00089F

What is wrong with this float?

1230.00089F

Answer:

There are nine decimal places of precision. Data type float can't handle that. (The compiler will

round the number into a value that can fit in a float).

Precision of Double

Page 124: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 124/293

 

You might wish to argue that there are only five places used in the above number: the placesused by the digits 1, 2, 3, 8, and 9. However, the four 0's in the middle do count. It takes bits torepresent them, even if they are zeros.

Primitive data type double uses 64 bits, and has a much greater range, -1.7E+308 to +1.7E+308.

It also has a much greater precision: about 15 significant decimal digits.

Because of this, if you write a literal like 2.345 in a Java program, it will automatically beregarded as a double, even though a float might be good enough. The other numbers in the program might need to be double, so we might as well make them all double.

QUESTION 12:

Do you suspect that characters are important enough to be one of the eight primitive data types?

Do you suspect that characters are important enough to be one of the eight primitive data types?

Answer:

Yes.

The char Primitive Data Type

Computer programs frequently work with character data. The primitive data type for charactersin Java is named char. The char type represents a character using 16 bits. In many programming

languages, only 8 bits are used for this purpose. Java uses 16 bits so that a very large number of characters can be represented, nearly all of the characters in all of the World's languages. Themethod used is called Unicode.

For example, here is a 16 bit pattern:

0000000001100111

If you know that these 16 bits are of data type char, then you could look in a table and discover that they represent the character 'g'. If you have a really good memory, you might recall that thesame 16 bits represent the integer 103 if they are regarded as data type short. Knowing the data

type of a pattern is necessary to make sense of it.

Upper and lower case characters are represented by different patterns. Punctuation and specialcharacters are also char data. There are also special characters, like the space character that

separates words.

Page 125: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 125/293

 

Control characters are bit patterns that show the end of a line or where to start pages. Other control characters represent the mechanical activities of old communications equipment (such asteletypes) that are rarely used these days. Many of these control characters are no longer used for their original purpose.

Primitive type char represents a SINGLE character. It does not include any font information.When you want to deal with more than one character at a time (almost always), you need to useobjects that have been built out of char data.

QUESTION 13:

Is each of the following a different character?

0 O o

(Depending on the fonts your browser is using, you may have to look carefully.)

Is each of the following a different character?

0 O o

Answer:

Yes. Each of the above (zero, Capital 'O', and lower case 'o') is a different character and has itsown 16 bit code.

Character Literals

In a program, a character literal is surrounded with an apostrophe on both sides:

'm' 'y' 'A'

In a program, control characters are represented with several characters inside the apostrophes:

'\n' '\t'

Each of these is what you do in a program to get a single char. The first one represents the 16 bitnewline character and the second one represents the tabulation character. You will rarely use anycontrol characters other than these two. Several others are listed in the Java documentation.

Warning: The following is not a character literal:

Page 126: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 126/293

 

"Hello"

This is a String, which is not primitive data. It is, in fact, an object. Strings are surrounded by

double quote marks ", not by apostrophes.

QUESTION 14:

What is wrong with the following char literal:

"W"

Answer:

The character is not surrounded by apostrophes. It should be: 'W' .

With double quotes, "W", you get a String that contains a single character. This is not the sameas a primitive single character. A String is represented as an object and may consist of several

hundred bytes. A primitive character data item is always only two bytes.

Primitive Data Type boolean

Another of the primitive data types is the type boolean. It is used to represent a single true/false

value. A boolean value can have only one of two values:

true false

In a Java program, the words true and false always mean these boolean values. The data type

boolean is named after George Boole, a nineteenth century mathematician, who discovered that

a great many things can be done with true/false values (otherwise known as bits).

QUESTION 15:

Would you like a data type named after you someday?

true false

Answer:

Maybe.

Page 127: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 127/293

 

End of Chapter

You have reached the end of the chapter. You may wish to review the following. Click on asubject that interests you to go to where it was discussed.

• Data type.• Primitive data type.• Case sensitive computer languages.• Objects and primitive data types.• Numeric data types.• Integer literals.• Floating point literals.•  The precision of a floating point number.• Data type char.• Data type boolean

The next chapter will discuss variables and assignment statements.

You have reached the end of the chapter.

CHAPTER 9 — Variables and Assignment

Statements

In all but the smallest programs, an executing program is constantly working with values. Thesevalues are kept in little sections of main memory called variables.

Chapter Topics:

• Variables• Assignment Statements

Page 128: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 128/293

 

• Expressions• Arithmetic Operators

QUESTION 1:

Do you imagine that a variable can change its value?

Answer:

Yes — that is why is is called a variable.

VariablesThe billions of bytes of main storage in your home computer are used to store both machineinstructions and data. The electronic circuits of main memory (and all other types of memory)make no distinction between the two. When a program is running, some memory locations areused for machine instructions and others for data. Later, when another program is running someof the bytes that previously held machine instructions may now hold data, and some that previously held data may now hold machine instructions.

Using the same memory for both instructions and data was the idea of John von Neumann, acomputer pioneer. (If you are unclear about bytes and memory locations, please read Chapter 3.)

variable — a named location in main memory which uses a particular data type to

hold a value.

Recall that a data type is a scheme for using bit patterns to represent a value. Think of a variableas a little box made of one or more bytes that can hold a value using a particular data type.

To put a value in memory, and later to get it back, a program must have a name for eachvariable.

Variables have names such as payAmount. (Details will be given in a few pages.)

Page 129: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 129/293

 

QUESTION 2:

Must a variable always have a data type?

Yes. Otherwise it would not be clear what its bits represent.

Declaration of a Variable

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

long payAmount = 123; //the declaration of the variable

System.out.println("The variable contains: " + payAmount );}

}

The example program uses the variable payAmount. The statement

long payAmount = 123;

is a declaration of a variable. A declaration of a variable is where a program says that it needs avariable. For our small programs, place declaration statements between the two braces of the

main method.

The declaration gives a name and a data type for the variable. It may also ask that a particular value be placed in the variable. In a high level language (such as Java) the programmer does notneed to worry about how the computer hardware actually does what was asked. If you ask for avariable of type long, you get it. If you ask for the value 123 to be placed in the variable, that is

what happens. Details like bytes, bit patterns, and memory addresses are up to the Java compiler.

In the example program, the declaration requests an eight-byte section of memory namedpayAmount which uses the primitive data type long for representing values. When the program

starts running, the variable will initially have the value 123 stored in it.

A variable cannot be used in a program unless it has been declared. A variable can be declaredonly once.

Page 130: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 130/293

 

QUESTION 3:

What do you think the program prints on the monitor? (You should be able to figure this out.)

What does the program print on the monitor when it runs?

Answer:

The variable contains: 123

Simulated Java Program

To get the most out of these notes, copy the program to a text editor, save it to a file called

Example.java, compile it, and run it. See Chapter 7 on how to do this. For a simulation of running the program, enter an integer in the text box below and click on "Compile", then click on"Run". (Note: if this does not work, your browser does not have JavaScript enabled.)

This is just a simulation (using JavaScript), so it is not exactly like compiling and running a realJava program. Don't take it too seriously. Please do the real thing if you can.

 Your browser is not set up to run Javascript. You can probably change this in its

options menu."

class Example{public static void main ( String[] args ){long payAmount = ; // declaration of a variable

 System.out.println("The variable contains: " + payAmount );

}}

 

Simulated Monitor

Page 131: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 131/293

 

 

QUESTION 4:

Try entering something like "rats" in the declaration. Does the program compile successfully?

Answer:

 No.

Syntax of Variable Declaration

The word syntax means the grammar of a programming language. We can talk about the syntaxof just a small part of a program, such as the syntax of variable declaration.

There are several ways to declare variables:

dataType variableName;

•  This declares a variable, declares its data type, and reserves memory for it. Itsays nothing about what value is put in memory. (Later in these notes youwill learn that in some circumstances the variable is automatically initialized,and that in other circumstances the variable is left uninitialized.)

dataType variableName = initialValue ;

 This declares a variable, declares its data type, reserves memory for it, andputs an initial value into that memory. The initial value must be of the correctdata type.

dataType variableNameOne, variableNameTwo ;

•  This declares two variables, both of the same data type, reserves memory foreach, but puts nothing in any variable. You can do this with more than twovariables, if you want.

Page 132: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 132/293

 

dataType variableNameOne = initialValueOne,variableNameTwo = initialValueTwo ;

•  This declares two variables, both of the same data type, reserves memory,and puts an initial value in each variable. You can do this all on one line if there is room. Again, you can do this for more than two variables as long as

you follow the pattern.

If you have serveral variables of different types, use several declaration statements. You caneven use several declaration statements for several variables of the same type.

QUESTION 5:

Is the following correct?

int answer;double rate = 0.05;

Is the following declaration correct?

int answer;double rate = 0.05;

Answer:

Yes — as long as the names answer and rate have not already been used.

Names for Variables

The programmer picks a name for each variable in a program. Various things in a program aregiven names. A name chosen by a programmer is called an identifier. Here are the rules for identifiers:

• Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9',character '_', and character '$'.

o An identifier can not contain the space character.• Do not start with a digit.• An identifier can be any length.• Upper and lower case count as different characters.

o SUM and Sum are different identifiers.• An identifier can not be a reserved word.• An identifier must not already be in use in this part of the program.

Page 133: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 133/293

 

A reserved word is a word which has a predefined meaning in Java. For example int, double,

true, and import are reserved words. Rather than worry about the complete list of reserved

words, just remember to avoid using names that you know already mean something, and be prepared to make a change if you accidentally use a reserved word you didn't know.

As a matter of programming style, a name for a variable usually starts with a lower case letter. If a name for a variable is made of several words, capitalize each word except the first. For example, payAmount and grandTotal. These conventions are not required by syntax, but make

 programs easier to read.

QUESTION 6:

Which of the following variable declarations are correct?

int myPay, yourPay;

long good-by ;

short shrift = 0;

double bubble = 0, toil= 9, trouble = 8

byte the bullet ;

int double;

char thisMustBeTooLong ;

int 8ball;

float a=12.3; b=67.5; c= -45.44;

Answer:

There are some syntax errors:

int myPay, yourPay; // OK

long good-by ; // bad identifier: "-" not allowed

short shrift = 0; // OK

double bubble = 0, toil= 9, trouble = 8 // missing ";" at end.

byte the bullet ; // bad identifier: can't contain a space

int double; // bad identifier: double is a reserved word

char thisMustBeTooLong ; // OK in syntax, but a poor choice// for a variable name

Page 134: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 134/293

 

int 8ball; // bad identifier: can't start with a digit

float a=12.3; b=67.5; c= -45.44; // bad syntax: don't use ";" to separatevariables

Example Program

class Example{public static void main ( String[] args ){long hoursWorked = 40;double payRate = 10.0, taxRate = 0.10;

System.out.println("Hours Worked: " + hoursWorked );

System.out.println("pay Amount : " + (hoursWorked * payRate) );System.out.println("tax Amount : " + (hoursWorked * payRate * taxRate) );

}}

The example program, containis three variable declarations. The variables are given initialvalues.

The character * means multiply. In the program,

(hoursWorked * payRate)

means to multiply the number stored in hoursWorked by the number stored in payRate.

Important Idea: When used as part of an expression, the name of a variable

represents the value it holds.

(An expression is a part of a statement that asks for a value to be calculated.)

When it follows a character string, + means to add characters to the end of the character string.

So

"Hours Worked: " + hoursWorked

makes a character string starting with "Hours Worked: " and ending with characters for the valueof hoursWorked.

The program prints:

Hours Worked: 40pay Amount : 400.0

Page 135: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 135/293

 

tax Amount : 40.0

Remember that if you want to see this program run, copy it from your Web browser, paste it into Notepad or other text editor, save it to a file, compile, and run it. (See Chapter 7.)

QUESTION 7:

Why did the program print the first 40 without a decimal point, but printed the second one with a

decimal point as 40.0 ?

(Hint: look at the variable declarations.)

Why did the program print the first 40 without a decimal point, but printed the second one with a

decimal point as 40.0 ?

Answer:

The first value was stored in a variable of data type long, an integer type. Integers do not have

fractional parts. The second forty was the result of a calculation involving a variable of data typedouble, a floating point type, which does have a fractional part. (Here, the fractional part was

zero.)

Calculationclass Example{public static void main ( String[] args ){long hoursWorked = 40;double payRate = 10.0, taxRate = 0.10;

System.out.println("Hours Worked: " + hoursWorked );  System.out.println("pay Amount : " + (hoursWorked * payRate) );

System.out.println("tax Amount : " + (hoursWorked * payRate * taxRate) );}

}

Look carefully at the statement highlighted in red. The parentheses around

(hoursWorked * payRate)

force the multiplication to be done first. After it is done, the result is converted to characters andappended to the string "pay Amount : ".

Page 136: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 136/293

 

When you have a calculation as part of a System.out.println() statement, it is a good idea to

surround the calculation with parentheses to show that you want it done first. Sometimes this isnot necessary, but it does not hurt, and makes the program more readable.

QUESTION 8:

Would it be better to write some of those statements on two lines instead one one?

Answer:

Yes.

Several Lines per StatementYou can use several lines for a statement. Anywhere a space character is OK you can split astatement. This means you can't split a statement in the middle of a name, nor between the quotemarks of a string literal, nor in the middle of a numeric literal. Here is the program with somestatements correctly put on two lines:

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

long hoursWorked = 40;double payRate = 10.0,

taxRate = 0.10;

System.out.println("Hours Worked: " +hoursWorked );

System.out.println("pay Amount : "+ (hoursWorked * payRate) );

System.out.println("tax Amount : " + (hoursWorked* payRate * taxRate) );}

}

Although correct, the division of statements is confusing to humans. It is also true that anywhereone space is OK any number of spaces are OK. Here is a better style for the program:

class Example{public static void main ( String[] args ){long hoursWorked = 40;double payRate = 10.0,

Page 137: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 137/293

 

taxRate = 0.10;

System.out.println("Hours Worked: " +hoursWorked );

System.out.println("pay Amount : " +(hoursWorked * payRate) );

System.out.println("tax Amount : " +(hoursWorked * payRate * taxRate) );

}}

It is a good idea to indent the second half of a split statement further than the start of thestatement.

QUESTION 9:

Is the following correct?

class Example

{

public static void main ( String[] args ){long hoursWorked = 40;double payRate = 10.0, taxRate = 0.10;

System.out.println("HoursWorked: " + hoursWorked );

System.out.println("pay Amount : " + (hoursWorked * payRate) );

System.out.println("tax Amount : " + (hoursWorked * payRate * taxRate) );

}}

Answer:

 No. The incorrect splittings are highlighted in red:

class Example

{

public static void main ( String[] args ){long hoursWorked = 40;double payRate = 10.0, taxRate = 0.10;

System.out.println("Hours

Page 138: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 138/293

 

Worked: " + hoursWorked );

System.out.println("pay Amount : " + (hoursWorked * payRate) );

System.out.println("tax Amount : " + (hoursWorked * payRate * taxRate) );

}

The last statement is correct, although not done in a good style for easy human comprehension.The extra blank lines are OK.

Assignment Statements

So far, the example programs have been using the value initially put into a variable. Programscan change the value in a variable. An assignment statement changes the value that is held in avariable. Here is a program that uses an assignment statement:

class AssignmentExample{public static void main ( String[] args ){long payAmount ; // payAmount is declared without an initial value

payAmount = 123; // an assignment statementSystem.out.println("The variable contains: " + payAmount );

}

}

The assignment statement puts the value 123 into the variable. In other words, while the programis executing there will be a 64 bit section of memory that holds the value 123.

Remember that the word "execute" is often used to mean "run". You speak of "executing a program" or "executing" a line of the program.

QUESTION 10:

What does the program print to the monitor?

What does the program print to the monitor?

Answer:

The variable contains: 123

Page 139: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 139/293

 

The program prints out the same thing as the first example program. However, this program didnot initialize the variable and so had to put a value into it later.

Assignment Statement SyntaxAssignment statements look like this:

variableName = expression ;

•  The equal sign = is the assignment operator.• variableName is the name of a variable that has been declared previously in

the program.• expression is a collection of characters that calls for a value.

Here are some example assignment statements (assume that the variables have already beendeclared):

total = 3 + 5;

price = 34.56;

tax = total*0.05;

In the source file, the variable must be declared before any assignment statement that uses thatvariable.

QUESTION 11:

Is the following correct?

int sum;

sum = 42 - 12 ;int sum;sum = 42 - 12 ;

Answer:

Yes, the statements are syntactically correct.

Assignment Statement Symantics

Page 140: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 140/293

 

The syntax of a programming language says what programs look like. It is the grammar of howto arrange the symbols. The symantics of a programming language says what the program doesas it executes. It says what the symbols mean.

This page explains the symantics of the assignment statement. An assignment statement does its

work in two steps: 

1. First, do the calculation on the RIGHT of the equal sign.o If there is nothing to calculate, use the value on the right.

2. Next, replace the contents of the variable to the LEFT of the equal sign withthe result of the calculation.

For example:

total = 3 + 5;

1. Do the calculation 3+5 to get 8.

2. Put 8 in the variable named total.

It does not matter if total already has a number in it. Step 2 will replace whatever is already in

total .

For example:

points = 23;

1. Use the value 23.2. Put 23 in the variable named points.

QUESTION 12:

What happens FIRST when the following statement executes?

value = 2*3 ;

Answer:

FIRST, do the multiplication 2*3 to get the value 6.

Two Steps

FIRST, do the multiplication 2*3 to get the value 6.

Page 141: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 141/293

 

 NEXT, put the result of the calculation into the "litte box of memory" used for the variable

value:

It will really, really help you to think carefully about these two steps. Sometimes even secondyear computer science majors get confused about this and write buggy code.

QUESTION 13:

What will this program fragment write?

value = 2*3;

System.out.println( "value holds: " + value );value holds: 6

More Practice

Here is another program fragment:

int extra;extra = 5;

The assignment statement is correct. It matches the syntax:

variableName = expression;

The expression is the literal 5. No calculation needs to be done. But the assignment statement

still takes two steps.

FIRST, get the 5:

Page 142: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 142/293

 

 NEXT, put the 5 in the variable:

QUESTION 14:

What does the following fragment write?

int quantity = 7;

quantity = 13;System.out.println( "quantity holds: " + quantity );int quantity = 7;quantity = 13;

System.out.println( "quantity holds: " + quantity );

Answer:quantity holds: 13

The assignment statement replaced the value that was originally in quantity with the value 13.

Adding a Number to a Variable

Assume that extra already contains the value 5.

Page 143: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 143/293

 

Here is another statement:

value = extra + 2;

The statement will be performed in two steps (as always). The first step performs the calculation

extra + 2 by first copying the 5 from extra, and then adding 2 to it:

The result of the calculation is 7. The second step puts 7 into the variable value:

QUESTION 15:

What will the following program print out:

// Example assignment statementsint extra, value;

extra = 5;value = extra + 2;System.out.println( "value now holds: " + value );

Answer:

The program will print out:

value now holds: 7

Page 144: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 144/293

 

Same Variable Twice in an Assignment

Statement

Look at the statements:

value = 5;value = 12 + value;

Assume that value has already been declared. The two statements execute one after the other,

and each statement performs two steps.

The first statement:

1. Gets the number on the RIGHT of the equal sign: 52. Puts the 5 in the variable called value.

The second statement:

1. Does the calculation on the RIGHT of the equal sign: 12 + value.o Look into the variable value to get the number 5.o Perform the sum: 12 + 5 to get 17

2. Look on the LEFT of the equal sign to see where to put the result.o Put the 17 in the variable value.

Page 145: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 145/293

 

Note: A variable can be used on both the LEFT and the RIGHT of the = in the same assignment

statement. When it is used on the right, it provides a number used to calculate a value. When it isused on the left, it says where in memory to save that value.

The two roles are in separate steps, so they don't interfere with each other. Step 1 uses the

original value in the variable. Then step 2 puts the new value (from the calculation) into thevariable.

QUESTION 16:

What does the following program fragment write?

value = 5;System.out.println("value is: " + value );

value = value + 10;System.out.println("value is: " + value );

Answer:

The program will print out:

value is: 5value is: 15

Page 146: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 146/293

 

A Sequence that Counts

Look at this program fragment:

int count = 0; // statement 1System.out.println( count ) ; // statement 2

count = count + 1; // statement 3System.out.println( count ) ; // statement 4

Here is how the program works:

1. Statement 1 puts 0 into count.2. Statement 2 writes out the 0 in count.

3. Statement 3 first gets the 0 from count, adds 1 to it, and puts the result backin count.

4. Statement 4 writes out the 1 that is now in count.

When the fragment runs, it writes:

01

QUESTION 17:

Think of a way to write 0, 1, and 2.

Answer:

Put a copy of statements 3 and 4 at the end.

Counting Higher

The following fragment:

int count = 0; // statement 1System.out.println( count ) ; // statement 2

count = count + 1; // statement 3System.out.println( count ) ; // statement 4

count = count + 1;

Page 147: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 147/293

 

System.out.println( count ) ;

 prints out

01

2

The statement

count = count + 1;

increments the number in count. Sometimes programmers call this "incrementing a variable"although (of course) it is really the number in the variable that is incremented.

QUESTION 18:

What does the following assignment statement do:

sum = 2*sum ;

(What are the two steps, in order?)

What does the following assignment statement do:

sum = 2*sum ;

Answer:

1. Evaluate the expression: get the value in sum and multiply it by two.2. Then, put that value into sum.

Expressions

Sometimes you need to think carefully about the two steps of an assignment statement. The first

step is to evaluate the expression on the right of the assignment operator.

An expression is a combination of literals, operators, variable names, and

parentheses used to calculate a value.

This (slighly incomplete) definition needs some explanation:

• literal — characters that directly give you a value, like: 3.456

Page 148: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 148/293

 

• operator — a symbol like plus + or times * that asks for an arithmeticoperation.

• variable — a section of memory containing a value.• parentheses — ( and ).

This might sound awful. Actually, this is stuff that you know from algebra, like:

(32 - y) / ( x + 5 )

In the above, the character / means division. Not just any mess of symbols will work. The

following

32 - y) / ( x 5 + )

is not a syntactically correct expression. There are rules for this, but the best rule is that anexpression must look OK as algebra.

However, multiplication must always be shown by using a * operator. You can't multiply twovariables by placing them next to each other. So, although xy might be correct in algebra, you

must use x*y in Java.

QUESTION 19:

Which of the following expressions are correct? (Assume that the variables have been properlydeclared elsewhere.)

Expression 53

12 -3)

x +34

*z99

sum +value

Correct or

Not?

Answer:

Expression 53 12 - 3)x +

34*z 99

sum +

value

Correct or

Not?

Corre

ct

NOT

Correct

Corre

ct

NOT

Correct Correct

More Practice

Let's try some more. Again, assume that all the variables have been correctly declared.

Page 149: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 149/293

 

Expressionsum +

* 3

(12 -

3)

sum *

34 / 2

emf * (

e

3.14

y

Correct or

Not?

 

QUESTION 20:

Why is the last expression not correct?

Answer:

Multiplication must be shown with a * operator. (Another answer is that 3.14y is not a correctvariable name.)

Spaces Don't Much Matter

An expression can be written without using any spaces. Operators and parentheses are enough toseparate the parts of an expression. You can use one or more spaces in an expression to visuallyseparate the parts without changing the meaning. For example, the following is a correctexpression:

(hoursWorked*payRate)-deduction

The following means exactly the same:

(hoursWorked * payRate) - deduction

Use spaces wisely to make it clear what the expression means. By making things clear, youmight save yourself hours of debugging. Spaces can't be placed in the middle of identifiers.

The following is NOT correct:

( hours Worked * pay Rate) -deduction

It is possible (but unwise) to be deceptive with spaces. For example, in the following:

12-4 / 2+2

Page 150: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 150/293

 

it looks as if 4 is subtracted from 12, and then that the result, 8, is divided by 4. However, thespaces don't count, and the expression is the same as:

12 - 4/2 + 2

This arrangement of spaces makes it clear what the expression means.

QUESTION 21:

Based on what you know about algebra, what is the value of this expression:

12 - 4/2 + 2

What is the value of: 12 - 4/2 + 2 

Answer:

12, since the expression means: 12 - 2 + 2 

Arithmetic Operators

An arithmetic operator is a symbol that asks for doing some arithmetic. As the previousquestion illustrates, if several operators are used in an expression, the operations are done in aspecific order. Operators of higher precedence are done first. The table shows the precidence of some Java operators.

Some operators have equal precedence. For example, addition + and substraction - have the

same precedence.

The unary minus and unary plus operators are used as part of a negative or a positive number.For example, -23 means negative twenty-three and +23 means positive twenty-three. More on

this later.

When both operands (the numbers) are integers, these operators do integer arithmetic. If oneoperand or both operands are floating point, then these operators do floating point arithmetic.This is especially important to remember with division, because the result of integer division isan integer. For example:

5/2 is 2 (not 2.5)

5/10 is 0 (not 0.5).

Page 151: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 151/293

 

More on this later.

Operat

orMeaning

precede

nce

- unaryminus highest

+ unary plus highest

*multiplicati

onmiddle

/ division middle

% remainder middle

+ addition low

- subtraction low

QUESTION 22:

What is the value of the following expressions? In each expression, do the highest precedenceoperator first.

Express

ion

16 - 12 /

4

2 + 6 /

2

8 +

4*2

8+4 *

2

12/2 -

3

6/8 +

2

Value

Answer:

Express

ion

16 - 12 /

4

2 + 6 /

2

8 +

4*2

8+4 *

2

12/2 -

3

6/8 +

2

Value 13 5 16 16 3 2

The last result is correct. First 6/8 is done using integer division, resulting in 0. Then that 0 isadded to 2.

Evaluation by Rewriting

Page 152: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 152/293

 

When evaluating an expression, it can be helpful to do it one step at a time and to rewrite theexpression after each step. Look at:

16 - 12 / 4

Do the division first, since it has highest precedence. Next, rewrite the expression replacing thedivision with its value:

16 - 3

 Now evaluate the resulting expression:

13

You can write the process like this:

16 - 12 / 4

------16 - 3---------

13

The dashed lines show what was done at each step.

QUESTION 23:

What is the value of the following expression?

24 / 2 - 8

Answer:24 / 2 - 8------12 - 8---------

4

Evaluate Equal Precedence from Left toRight

When there are two (or more) operators of equal precedence, evaluate the expression from left toright.

Page 153: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 153/293

 

2 * 7 * 3-----14 * 3-------

42

Since both operators are *, each has equal precidence, so calculate 2 * 7 first, then use thatresult with the second operator.

4 - 2 + 5-----2 + 5-------

7

Here the operators are different, but they both have the same precidence, so they are evaluatedleft to right.

Usually it doesn't matter if evaluation is done left to right or in any other order. In algebra itmakes no difference. But with floating point math it sometimes makes an important difference.Also, when an expression uses a method it can make a very big difference. (Methods arediscussed in part 6 of these notes.)

QUESTION 24:

What is the value of the following expression?

2 + 4/2 + 1

Answer:2 + 4/2 + 1

---2 + 2 + 1------4 + 1---------

5

Unary Minus

If you look in the table of operators you will see that the character - is listed twice. That is

 because - is used for two purposes. In some contexts, - is the unary minus operator. In other 

contexts, - is the subtraction operator.

The unary minus is used to show a negative number. For example:

Page 154: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 154/293

 

-97.34

means "negative ninety seven point thirty four." The subtraction operator is used to show asubtraction of one number from another. For example:

95 - 12

asks for 12 to be subtracted from 95.

The unary minus operator has high precedence. Addition and subtraction have low precedence.For example

-12 + 3

means add 3 to negative 12 (resulting in -9). The unary minus is done first, so it applies only tothe twelve.

unary plus + can be applied to a number to show that it is positive. It also has high precedence.It is rarely used.

QUESTION 25:

What is the value of the following expression?

+24 + 3 * -4

Answer:+24 + 3 * -4------

+24 + -12-----------

12

The first + is a unary plus, so it has high precidence and applies only to the 24.

The - is a unary minus, so it applies only to the 4.

 Next in order of precidence is the *, so three times negative four is calculated yielding negative

twelve.

Finally the low precidence + combines the postive twenty four with the negative twelve.

Arrange what you want with Parentheses

Page 155: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 155/293

 

To say exactly what numbers go with each operator, use parentheses. For example

-1 * ( 9 - 2 ) * 3

means do 9 - 2 first. The "( )" groups together what you want done first. After doing the

subtraction, the ( 9 - 2 ) becomes a 7:

-1 * 7 * 3

 Now follow the left-to-right rule for operators of equal precedence:

-1 * 7 * 3-------7 * 3--------

-21

QUESTION 26:

What is the value of each of the following expressions?

Express

ion

(8 - 2) /

2

(2 + 6) / 2

- 9

(8 + 4)

* 2

8 + 4

* 2

8 + (4 *

2)

Value

Answer:

Expression

(8 - 2) /2

(2 + 6) / 2- 9

(8 + 4)* 2

8 + 4* 2

8 + (4 *2)

Value 3 -5 24 16 16

Extra Parentheses

 Notice that the last expression (above) did not need parentheses. It does not hurt to use parentheses that are not needed. For example, all of the following are equivalent:

a + b + c

* d

a + b + (c

* d)

(a + b) + (c

* d)

((a + b) + (c

* d))

Warning! Look out for division. The / operator is a constant source of bugs! Parentheses will

help.

Page 156: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 156/293

 

QUESTION 27:

What is the value of each of the following expressions?

Express

ion

8 + 2 / 2

+ 3

(8 + 2) / (2

+ 3)

(8 + 2) / 2

+ 3

8 + 2 / (2

+ 3)

Value

Answer:

Express

ion

8 + 2 / 2

+ 3

(8 + 2) / (2

+ 3)

(8 + 2) / 2

+ 3

8 + 2 / (2

+ 3)

Value 12 2 8 8

The last answer is correct. It is done like this:

8 + 2 / (2 + 3 )--------

8 + 2 / 5-----

8 + 0-----8

2/5 is 0 with integer division.

Nested Parentheses

Sometimes in a complicated expression one set of parentheses is not enough. In that case useseveral nested sets to show what you want. The rule is:

 The innermost set of parentheses is evaluated first.

Start evaluating at the most deeply nested set of parentheses, and then work outward until thereare no parentheses left. If there are several sets of parentheses at the same level, evaluate themleft to right. For example:

( ( ( 32 - 16 ) / ( 2 * 2 ) ) - ( 4 - 8 ) ) + 7-----------

( ( 16 / ( 2 * 2 ) ) - ( 4 - 8 ) ) + 7

Page 157: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 157/293

 

---------

( ( 16 / 4 ) - ( 4 - 8 ) ) + 7---------------------------

( 4 - ( 4 - 8 ) ) + 7-------

( 4 - -4 ) + 7--------------------------------------------- 

8 + 7----------------------------

15

Ordinarily you would not do this in such detail.

QUESTION 28:

What is the value of this expression:

(12 / 4 ) + ( 12 / 3)

Answer:

7

End of the Chapter

Here is a list of subjects you may wish to review. Click on a high precedence subject to go towhere it was discussed.

• What variables are.• Declaring variables.• Syntax of declaring variables. • Names for variables.• Reserved words.• Assignment statements• Symantics• Expressions.•  Table of operators and their precedence.• How parentheses change the order of evaluation. 

Page 158: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 158/293

 

The next chapter will continue with arithmetic expressions.

You have reached the end of the chapter.

CHAPTER 9B — Expressions and

Arithmetic Operators

This chapter continues the discussion of arithmetic expressions, integer operators, and floating point operators.

Chapter Topics:

Review of Expressions• Arithmetic Operators• Integer operators• Floating point operators• Mixed Floating point and Integer Expressions• Constants

QUESTION 1:

(Review: ) Is the following correct?

13 * 6 -

(Review: ) Is the following correct?

13 * 6 -

Answer:

 No.

Expressions

The literals (the integers) and the operators are out of order in the above incorrect expression.(One legal arrangement is 13 * -6 for 13 times minus 6.)

Page 159: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 159/293

 

An expression is a combination of literals, operators, variable names, and

parentheses used to calculate a value.

Expressions contain operators and operands. You already know what an operator is (a symbolsuch as +, -, *, or / that calls for an arithmetic operation).

An operand is a value that is acted upon by an operator.

The parts of an expression must be arranged correctly. The syntax of Java describes the correctarrangements. The rules for correct Java expressions are about the same as for algebra.Essentially,

1. Each operator must have the correct number of operands.o Multiplication *, Division /, Addition +, Subtraction - should have two

operands, one on each side.o Negation - and unary plus + should be followed by one operand.

2. Parentheses () can surround a legal expression to make it an operand.

In Java expressions, operators and operands must be explicit. In 13 - 5 the 13 and the 5 are the

operands and the - is the operator.

In 14*sum 14 and sum are the operands. The star for multiplication must be present. The

expression 14sum is incorrect.

The details of expression syntax are in the Java documentation, should you care to dig through it.The best way to learn these rules is to study some examples.

QUESTION 2:

Which minus sign in the following stands for "subtraction" and which stands for "negation"?

-23 - 3

Answer:-23 - 3

The first minus sign is "negation" and the second minus sign is "subtraction". The spaces in the

expression emphasize the different roles, but are not necessary. The following expression isequivalent:

-23-3

Practice

Page 160: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 160/293

 

Examine the following expressions. Assume that each variable has already been correctlydeclared. Decide if the expression is correct, then click on the button.

ExpressionCorrect or Not

Correct?Expression

Corrector Not

Correct?

25 25 - value

2( a - b ) (a-b) * (c-d)

A - b/c + D -sum + partial

( (x+y) / z ) / ( a

- b )

( (m - n) + (w-x-z) /

(p % q )

 

QUESTION 3:

Are arithmetic expressions the only kind of expression?

Answer:

 No. For example, the following is also an expression:

"This is" + " a string" + " expression"

The above expression creates a new string that is the concatenation of all the strings.

Arithmetic Operators

Operat

orMeaning

precede

nce

-unary

minushighest

+ unary plus highest

*multiplicati

onmiddle

Page 161: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 161/293

 

/ division middle

% remainder middle

+ addition low

- subtraction low

But arithmetic expressions are especially important. As you have seen, Java has many operatorsfor arithmetic:

All of these operators can be used on floating point numbers and on integer numbers. (However,the % operator is rarely used on floating point.) For instance, / means integer division if both

operands are integers, and means floating point division if one or both operands are floating point.

An integer operation is always done with 32 bits or more. If one or both operand is 64 bits (datatype long) then the operation is done with 64 bits. Otherwise the operation is done with 32 bits,

even if both operands are smaller than 32 bits.

For example, with 16 bit short variables, the arithmetic is done using 32 bits:

short x = 12; // 16 bit shortint result; // 32 bit int

result = x / 3; // arithmetic will be// done using 32 bits

The expression x / 3 divides a 32-bit 12 by a 32-bit 3 and puts the 32-bit answer in result.The literal 3 automatically represents a 32-bit value.

QUESTION 4:

Does it really matter that 12 was converted to 32 bits?

Answer:

 Not in this example. But sometimes it does, when values are close to the limit of what can berepresented in 16 bits.

Another Example

Page 162: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 162/293

 

Here is another example:

short x = 12;short y = 3;short value;

value = x / y;

The expression x / y divides a 32-bit 12 by a 32-bit 3, even though the variables x and y are

only 16 bits wide. The calculation produces a 32-bit result. Because the 32-bit result does not fitin the 16 bits of value the compiler will not compile the last statement. This can be completely

 baffling when it happens to you.

C:\Private>javac ShortStuff.javaShortStuff.java:9: possible loss of precisionfound : intrequired: short

result = x / y;

^1 error

C:\Private>

For professional programmers, details like these are sometimes important. But for most programs, just use int or long for integers and double for floating point. This will keep you out

of trouble (usually). If you can't avoid the problem, use a type cast , as described in chapter 28.

QUESTION 5:

Do you expect that a modern electronic calculator will give you the same answer as Java for theexpression (31.5 - 12)/4.1 ?

Do you expect that a modern electronic calculator will give you the same answer as Java for theexpression (31.5 - 12)/4.1 ?

Answer:

Yes. The meaning of operators and parentheses is about the same in electronic calculators and inJava. But Java does integer and floating point math, and sometimes this can make a difference.

Weird Integer Arithmetic

The division operator / means integer division if there is an integer on both sides of it. If one or 

two sides has a floating point number, then it means floating point division. The result of 

Page 163: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 163/293

 

integer division is always an integer. Integer division determines how many times one number goes into another. The remainder after integer division is simply dropped, no matter how big itis.

There is a difference between what Java will do and what a calculator will do. A calculator will

do floating point arithmetic for the expression:

7/4

A calculator will show this as 1.75. Java will regard this as integer arithmetic and give you:

7/4 = 1

 because 4 goes into 7 just once. The result is not rounded up to 2. The remainder after division,3, is simply dropped.

QUESTION 6:

What is the result of evaluating the following expression:

199/50

Answer:199/50 = 3

50 goes into 199 three times and the remainder, 49, is dropped.

Mixed Integer and Float

Integer division is easy enough to see when it is by itself, but here is a more confusing case of the same thing:

1.5 + 7/2

The division is done first, because / has higher precedence than +. The result, 3, is an integer. Now the floating point 1.5 is added to integer 3 to get floating point 4.5.

Integer arithmetic might be used in some parts of an expression and not in others, even thoughthe final value of the expression is floating point.

Page 164: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 164/293

 

QUESTION 7:

What is the result of evaluating the following expression:

1/2 + 1/2

Answer:1/2 + 1/2 = 0

It looks as though this is a mistake, but no: each 1/2 calls for integer division, resulting in an

integer 0. The two zeros are added to get the final answer, zero.

Copy-and-Paste Program

If you really want to add one half to one half you should write 1.0/2.0 + 1.0/2.0 because now

the decimal points make each number a double. Here is some Java code that illustrates these points:

class IntegerDivision{public static void main ( String[] args ){System.out.println("The result is: " + (1/2 + 1/2) );

}}

Copy this program to a file IntegerDivision.java, compile, and run it. See a previous chapter for details on doing this. Make some changes to the program using your text editor then run it tosee the effect.

 Notice the parentheses around (1/2 + 1/2). These are necessary so that the arithmetic is done

first, then the result is converted to characters and appended to the string.

QUESTION 8:

What is the value of the expression 99/100 ?

Answer:

99/100 = 0

It is tempting to think that the answer must be 1, but it is not. 100 goes into 99 zero times, so thatis the result.

Page 165: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 165/293

 

Practice

The normal rules of arithmetic are used to determine the sign of the result of division:

+num/+div ==

+result

-num/+div ==

-result

+num/-div ==

-result

-num/-div ==

+result

It is easiest to first calculate the result as if num and div were positive, then apply the aboverules. For example:

17/5

== 3

-17/5 ==

-3

17/-5 ==

-3

-17/ -5

== 3

Of course, you are eager to practice this right away! Mentally (or with scratch paper) decide onthe value of each expression. Then click on the button to see the correct value.

Express

ionResult

Express

ionResult

12 3 -12 3

-10 5 10 -6

129 100 -19 -10

17 2 -19 2

QUESTION 9:

What is the value of the expression 3/4 ?

What is the value of the expression 3/4 ?

Answer:

0

 

þÿ þÿ

þÿ þÿ

þÿ þÿ

þÿ þÿ

Page 166: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 166/293

 

Subexpressions

The expression 3/4 calls for integer division because both the operands are integers. Theexpression 3.0/4.0 calls for floating point division because both the operands are floating point.

Most of the operators we are interested in take two operands. In each of the following examplesthe operator has two operands:

34 +

1219/3

90 -

sumval * x

However, unary operators take just one operand:

+93 -72 +sum-

Math.PI

A binary operator will always have exactly two operands. However, sometimes one or bothoperands of a binary operator is a subexpression.

A subexpression is a part of an expression that is by itself a correct expression.

Sometimes a subexpression is a constant, like "8". Any expression can be a subexpression of alarger expression. In the following, both operands of the red operator are subexpressions.

2*3 +

8

(x - y) /

2.3

(sum - 2) * (sum

+ 3)

QUESTION 10:

In an expression like 34.12 / 68.0 how do you know if the / means integer division or means

 floating point division ?

Answer:

You look at the operands of the operator.

Mixed Floating Point and Integer

Expressions

Page 167: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 167/293

 

But what if one operand is an integer and the other is a floating point? The rule is:

If both operands are integers, then the operation is an integer operation. If any

operand is floating point, then the operation is floating point.

For example, the following are integer operations (assume that a and b are int variables):

12 *

b

a -

2

56%

a

Each operation in the following expressions is a floating point operation (assume that a and b are

int variables, and that x and y are floating point variables):

x *

b

(a -

2.0)

56*

y

In more complicated expressions, an operand of a particular operator might be a subexpression.But the rule still applies: if one or both operand is a floating point type then the operation isfloating point. In the following, each / operation is floating point:

(12.0 * 31) /

12

(a -

2.0) / b

56*x/

3

In that last example, the 56*x is a floating point subexpression that is one of the operands for the

division operator. (Because * and / have equal precedence, so evaluation is done from left to

right.)

QUESTION 11:

What type (integer or floating point) of operator is the / in the following:

(12 + 0.0) / 7

What type (integer or floating point) of operator is the / in the following:

(12 + 0.0) / 7

Answer:

Floating point. Adding floating point 0.0 to the integer 12 results in a floating point 12.0. Nowthe division is floating point because one of its operands is. This is a common programmingtrick.

Page 168: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 168/293

 

Mixed Expression Gotcha!

Look again at the rule:

If both operands are integers, then the operation is an integer operation. If any

operand is floating point, then the operation is floating point.

The rule has to be applied step-by-step. Consider this expression:

( 1/2 + 3.5 ) / 2.0

What is the result? Apply the rules: innermost parentheses first, within the parentheses thehighest precedence operator first:

( 1/2 + 3.5 ) / 2.0---do first

Since both operands are integer, the operation is integer division, resulting in:

( 0 + 3.5 ) / 2.0

 Now continue to evaluate the expression inside parentheses. The + operator is floating point

 because one of its operands is, so the parentheses evaluates to 3.5:

3.5 / 2.0

Finally do the last operation:

1.75

This is close to the result that you might have mistakenly expected if you thought both divisionswere floating point. An insidious bug might be lurking in your program!

QUESTION 12:

Surely you want to try another! What is the result of evaluating this expression:

( a/b + 4) / 2

Assume that a contains 6 and b contains 12.0

Page 169: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 169/293

 

Assume that a contains 6 and b contains 12.0

Answer:(a/b + 4) / 2 == (6/12.0 + 4) / 2 == (0.5 + 4) / 2 == 4.5/2 == 2.25

Fun with Mixed Expressions

Examine each expression in the following list. Decide if the operator in the button is an integer operation or a floating point operation. Then click on the operator to see if you are correct.

12 35

5.6 -14

( 12 + 0.01 ) 2

( 18.0 - 23.3 ) /

( 73 23 )

-19.45 2.93

( 34 - 12 ) ( 9 / 10 )

Warning: These questions ask if the operator is floating point or integer. The value of the

complete expression may be of a different type than one of its operators.

QUESTION 13:

What is the remainder after dividing 13 by 5 (with integer division)?

What is the remainder after dividing 13 by 5?

Answer:

3

Remainder Operator

 

þÿ

þÿ

þÿ

þÿ

þÿ

þÿ

Page 170: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 170/293

 

You may recall how in grade school you did division like this:

13 / 5 == 2 with a remainder of 3. This is because 13 == 2*5 + 3. The symbol for finding the

remainder is % (percent sign). This symbol is also called the modulo operator. If you look in the

table of operators you will see that it has the same precedence as / and *. Here is a program that

is worth study:

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

{int quotient, remainder;

quotient = 17 / 3;remainder = 17 % 3;

 System.out.println("The quotient : " + quotient );System.out.println("The remainder: " + remainder );System.out.println("The original : " + (quotient*3 + remainder) );

}}

Copy this program to a file and play with it. Change the 17 and 3 to other numbers and observe

the result.

QUESTION 14:

Why were the innermost set of parentheses used in the statement:

System.out.println("The original : " + (quotient*3 + remainder) );

Why were the innermost set of parentheses used in the statement:

System.out.println("The original : " + (quotient*3 + remainder) );

Answer:

The parentheses force evaluation of the entire arithmetical expression (quotient*3 +

remainder). Then the result is converted to characters and appended to the string. Without the

 parentheses, the subexpressions are evaluated independently, converted to characters, andappended to the string.

Page 171: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 171/293

 

Taking an Integer Apart

The integer division operator / and the remainder operator % take an integer apart.

theInteger / divisor quotient

theInteger % divisor remainder

The original integer can be put back together again:

quotient * divisor + remainder theInteger

In many calculations, it is convenient to do everything with integers, so both / and % are needed.

QUESTION 15:

If you exchange 372 pennies for dollar bills, how many bills do you get? How many pennies areleft over?

If you exchange 372 pennies for dollar bills, how many bills do you get? How many pennies areleft over?

Answer:

• Number of dollar bills is 372 / 100 == 3 • Left over pennies is 372 % 100 == 72 

Practice with Remainder Operator

For positive numbers, INT % X means to fit as many X as you can into INT, and then the left over 

amount is the value of the expression. Try that with the following:

Express

ionResult

Express

ionResult

7 3 7 5

10 5 10 6

 

þÿ þÿ

þÿ þÿ

Page 172: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 172/293

 

129 1001999

100

17 2 18 2

QUESTION 16:

If X is odd, what is X%2?

Answer:

One. This is a common programming trick. Often you need to know the oddness and eveness of an integer.

Remainder with Negative Integers

The remainder operator can be used with negative integers. The rule is:

1. Perform the operation as if both operands were positive.2. If the left operand is negative, then make the result negative.3. If the left operand is positive, then make the result positive.4. Ignore the sign of the right operand in all cases.

For example:

17 % 3 == 2 -17 % 3 == -217 % -3 == 2 -17 % -3 == -2

You may wish to practice with the following:

Express

ionResult

Express

ionResult

7 -3 -7 5

-10 5 10 -6

-129 100-1999

-100

-17 2 -18 2

 

þÿ þÿ

þÿ þÿ

þÿ þÿ

þÿ þÿ

þÿ þÿ

þÿ þÿ

Page 173: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 173/293

 

QUESTION 17:

Five pirates find a chest of 123 gold coins and wish to divide the 123 coins evenly amoung

themselves. How many coins does each pirate get?

The parrot gets any leftover coins. How many coins does the parrot get?

Answer:

123 coins / 5 pirates is 24 coins per pirate.

123 % 5 is 3 coins left over for the parrot.

Constants

Often in a program you want to give a name to a constant value. For example you might have atax rate of 0.045 for durable goods and a tax rate of 0.038 for non-durable goods. These areconstants, because their value is not going to change during a run of the program. It is convenientto give these constants a name. This can be done:

class CalculateTax{public static void main ( String[] arg )

{  final double DURABLE = 0.045;  final double NONDURABLE = 0.038;

. . . . . .}

}

The reserved word final tells the compiler that the value will not change. The names of constantsfollow the same rules as the names for variables. (Programmers sometimes use all capital lettersfor constants; but that is a matter of personal style, not part of the language.) Now the constantscan be used in expressions like:

taxamount = gross * DURABLE ;

But the following is a syntax error:

DURABLE = 0.441; // try (and fail) to change the tax rate.

Page 174: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 174/293

 

In your programs, use a named constant like DURABLE rather than using a literal like 0.441.There are two advantages in doing this:

1. Constants make your program easier to read and check for correctness.2. If a constant needs to be changed (for instance if the tax rates change) all

you need to do is change the declaration of the constant. You don't have tosearch through your program for every occurence of a specific number.

QUESTION 18:

Could an ordinary variable be used to give a value a name? What is another advantage of usingfinal?

Answer:

Yes. But final prevents any accidental change to a constant.

End of the Chapter

The remainder of this chapter is a list of subjects you may wish to review. Click on a subject thatinterests you to go to where it was discussed.

•  Table of operators and their precedence. • What an operand is. • What a subexpression is. • Rule for whether an operator is floating point or integer.• Integer division. •  The remainder operator. •  The final  reserved word. 

The next chapter tells how to get data from the keyboard into your program.

You have reached the end of the chapter.

http://chortle.ccsu.edu/java5/index.html#09

http://www.cafeaulait.org/course/

Page 175: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 175/293

 

CHAPTER 9C — Object Data

This chapter briefly discusses objects and how to use them. The objects discussed here aredefined in the standard software packages that come with Java. Later chapters discuss how youcan define your own objects.

Chapter Topics:

• Classes• Objects• Reference variables• String objects• Running methods of objects• Methods that create String objects•  Type wrappers• Packages

Chapter 25 and following discuss objects in greater detail than this chapter.

QUESTION 1:

(Review: ) What are the two divisions of data in Java?

Answer:

Objects and primitive data.

Objects and Primitive Data

A primitive data type uses a small amount of memory to represent a single item of data using bit patterns. For example, primitive type int represents integers using 32 bits. There are only eight

 primitive data types in Java: byte, short, int, long, float, double, char, and boolean. It isnot possible for a Java program to define any other primitive data types.

Page 176: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 176/293

 

An object is a large chunk of memory that can potentially contain a great deal of data along withmethods (little programs) to process that data. There are thousands of object classes that comestandard with Java, and a programmer can easily create additional classes. (Although there arethousands of standard classes, for this course you only need become familiar with a dozen or soclasses.)

Objects are so useful that we need to start using them now, even though they will not be fullydiscussed until chapter 25.

QUESTION 2:

Can objects contain primitive data?

Answer:

Yes, this is very common. Many objects consist of primitive data along with methods that usethat data.

Picture of an Object

Page 177: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 177/293

 

An object consists of both data and methods. The picture illustrates a conceptual object. Thelittle yellow bricks represent bytes of memory. The methods of the object and the data of theobject are constructed out of bytes. This object contains the characters "Elementary, my dear Watson!" and contains several methods to manipulate that data.

A class is a description of a kind of object. It is the data type of that kind of object. A classdescribes what an object of a particular type is made of, its data and its methods. A class ismerely a description. It is like a plan for a house. Before you build a house, you should have a plan. Once you have a plan, however, you can build any number of houses that follow that plan.

The picture represents an object of class String. Such an object contains a string of characters

and various methods that can do things with those characters. (There are several dozen methodsin a String object. Only a few are shown in the picture.)

QUESTION 3:

What do you suppose that the length() method of a String object does?

Answer:

It counts the number of characters in that String.

Creating an ObjectThe Java virtual computer creates an object by following the description contained in its class.Here is a program that creates a String object:

class StringDemo1{public static void main ( String[] args ){String str ;

str = new String( "Elementary, my dear Watson!" );}

}

When the program runs, the expression

new String( "Elementary, my dear Watson!" )

creates a new String object by following the description contained in the String class. This

description is contained in a standard software package that comes with Java. The particular 

Page 178: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 178/293

 

object created in this case contains characters "Elementary, my dear Watson!". The new objectcontains all the methods and features that are described in the String class.

All objects of the same class contain the same methods. All objects of the same class contain thesame types of data, although the values of the data will be different from object to object. For 

example, all String objects contain the same methods. All String objects contain a string of characters, but the characters will be different from object to object.

The program could now use the methods of this object to do some things with the characters.However, this program does nothing further. After it stops running, the object no longer exists.The memory out of which it was made can now be used for other purposes.

QUESTION 4:

Mentally change the program so that it creates a String object containing the characters "Youknow my methods, Watson."

Answer:str = new String( "You know my methods, Watson." );

Objects are Created at Run Time

Before the program runs, there is no object. The new String object is created as the program

runs. 

class StringDemo1{public static void main ( String[] args ){String str;

str = new String( "Elementary, my dear Watson!" );

}}

The declaration

String str;

creates a reference variable, but does not create a String object. The variable str is used to

refer to a String after one has been created. The next statement

str = new String( "Elementary, my dear Watson!" );

Page 179: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 179/293

 

is an assignment statement that creates an object and puts a reference to that object in str.

After the program stops running, the String object no longer exists. Its memory is reclaimed by

the computer system for other uses.

QUESTION 5:

(Review: ) What are the two steps in an assignment statement?

Answer:

An assignment statement asks for the computer to perform two steps, in order: 

1. Evaluate the expression on the right of the = 

2. Store the value in the variable on the left of the = 

Object Reference

Here is the assignment statement we are considering:

str = new String( "Elementary, my dear Watson!" );

It works like this:

1. Evaluate the expression. 

The expression

new String( "Elementary, my dear Watson!" )

is evaluated. This constructs (creates) a new object.

A constructor for an object has the same name as the class and is used with the new operator.

Sometimes (as in this example) a constructor requires parameters. A reference to an objectdescribes its location in memory. It enables the Java virtual computer to find the object.

2. Store the value in the variable. 

In the second step, the reference is stored in the reference variable:

str = The reference to the string just created 

Page 180: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 180/293

 

 Now whenever the program needs to refer to the object it uses the variable str.

A reference is like a cell phone number. Someone who has your number can send you a message,and ask you to do something, no matter where you are. Think of your boss calling you andsending a message, "Start working on that report!" This is like using an object reference to ask 

the object to run a method.

Sometimes the variable str is called the "name" of the object. This is sloppy and can lead to

confusion if you are not careful. The object, the reference variable, and the reference are threedifferent things.

QUESTION 6:

Are you and your cell phone number different things?

Answer:

Of course.

Analogy

Objects and references to objects are very common in the real world. But sometimes the

distinction is hard to see in a program. Here is an analogy that may help:

object you

reference your cell phone number

reference a slip of paper with your cell phone number on it,variable held by someone who wants to send messages to you

 

Page 181: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 181/293

 

QUESTION 7:

Could a slip of paper be blank?

Answer:

Of course. This is like an object reference variable that does not (yet) hold an object reference.

Before and After

Here is the statement we are considering:

str = new String( "Elementary, my dear Watson!" );

And here are pictures of the action. The picture on the left shows the program just as it starts torun. No objects have been created yet, but the reference variable exists. The slash through thevariable means that it does not yet refer to an object. Then the assignment statement executes:

str = new String( "Elementary, my dear Watson!" );

This creates an object, fills it with data, and puts a reference to it in str. This is shown on the

right. The reference is shown as an arrow that leads to the object, and this is a good way to think of it. (Although in reality it is just a bit pattern, like everything else in computer memory.)

Page 182: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 182/293

 

The variable will continue to hold the reference to the object until some other assignmentstatement changes it or the program ends.

QUESTION 8:

The object now exists. Can you run its methods?

Answer:

Yes.

Running a MethodHere is the example program, now with additional statements:

class StringDemo2{public static void main ( String[] args ){String str;int len;

str = new String( "Elementary, my dear Watson!" );

len = str.length(); // call the length() method of the object

System.out.println("The length is: " + len );

}}

The expression

Page 183: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 183/293

 

str.length();

runs the length() method of the object referred to by str. This method counts the number of 

characters in the data of the object. In our object, it counts the number of characters in"Elementary, my dear Watson!" which is 27. That value is then assigned to the int variable len.

Space characters and punctuation characters are included in the length of a string.

Calling a method means asking a method to run. This program called the length() method.

(Sometimes the phrase invoking a method is used to mean the same thing.)

QUESTION 9:

Complete the last line of of the analogy:

object you

reference your cell phone number

variable piece of paper with your cell phone number written on it

method call ???

Answer:object youreference your cell phone numbervariable piece of paper with your cell phone number written on itmethod call someone calls you and asks you to do something

Dot Notation

The various things an object contains—its variables and its methods—are called the members of that object. The members of an object are accessed using dot notation, which looks like this:

objectReference . memberName

Usually the objectReference is contained in a variable, but not always. If you want to run amethod of the object, use the method name. If it needs parameters (values supplied to the

method), they go inside ( ) like this:

objectReference . methodName( parameter )

Always use ( ) with a method name, even if it needs no parameters.

Page 184: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 184/293

 

QUESTION 10:

Does the length() method need a parameter?

Answer:

 No. The example program called the method like this:

str.length();

 No parameters are supplied.

Declaring a Reference Variable

There are several ways to declare a reference variable:

ClassName variableName;

•  This declares a reference variable and declares the class of the object it willlater refer to. No object is created.

ClassName variableName = new ClassName( parameter, parameter, ... ) ;

•  This declares a reference variable and declares the class of the object. Butnow, at run time, a new object is constructed and a reference to that object is

put in the variable. Sometimes parameters are needed when the object isconstructed.

ClassName variableNameOne, variableNameTwo ;

•  This declares two reference variables, both potentially referring to objects of the same class. No objects are created. You can do this with more than twovariables, if you want.

ClassName variableNameOne = new ClassName( parameter, parameter, ... ),variableNameTwo = new ClassName( parameter, parameter, ... ) ;

•  This declares two reference variables. At run time, two objects are createdand their references are assigned to the variables. Again, you can do this formore than two as long as you follow the pattern.

Page 185: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 185/293

 

QUESTION 11:

Is the following correct?

String stringG = new String("You know my methods, Watson.");String stringG = new String("You know my methods, Watson.");

Answer:

Yes.

A Method that Creates a String

Many of the methods of String objects create other String objects.

For example, the substring(int begin) method creates a new String that contains a copy of 

 part of the data in the original string. Here is a program that uses this method:

class StringDemo3{public static void main ( String[] args ){String str = new String( "Golf is a good walk spoiled." ); // create the

original object

String sub = str.substring(8); //create a new object from the original

System.out.println( sub );

}}

The expression

str.substring(8)

creates a new String object. That object contains its own data, which are characters copied from

the original string. The original string is not changed. The copy starts with character number 8 of 

the original string and continues to the end. Character numbering starts at zero, so character number 8 in the original string is the first 'a'.

The substring of the original string is contained in a new String object. A reference to that new

string is assigned to the reference variable sub.

Page 186: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 186/293

 

QUESTION 12:

What characters are contained in the new object?

Answer:

a good walk spoiled.

A New String

Here are pictures of what happens as the program runs. When the program starts there are tworeference variables, but no objects. When the first statement executes,

String str = new String( "Golf is a good walk spoiled." ); // create theoriginal object

it creates a String object and puts a reference to that object in the variable str. (The picture

shows only the data part of the objects.)

When the second statement executes,

String sub = str.substring(8); //create a new object from the original

a new object is created that contains a substring of the characters in the first object. The variablesub is assigned a reference to this object.

Page 187: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 187/293

 

QUESTION 13:

Does running the substring() method of a String object change that String object?

Answer:

 No. Running a String object's method does not change that object, but creates a new String

object.

Objects Creating Objects

It seems a little odd that an object can create another object. This is not how real-world objectsusually behave. Bricks do not create other bricks. Cars do not create other cars. But software

objects often create new objects.

Software objects are created:

1. By using a constructor.2. By calling a method that constructs an object.

There is no difference between objects created one way or the other.

The substring() method of a String object creates a new object by asking the Java virtual

computer to create a new object. The virtual computer creates the new object in the usual way by

following the instructions contained in the class.

QUESTION 14:

Do you imagine that there are other String methods that create new String objects?

Answer:

Yes.

Other Methods of String

There are many String methods. The following list contains just a few. For the complete list,

and for detailed descriptions, see the Java documentation on the web. Java Documentation 

Page 188: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 188/293

 

public char charAt( int index )public String concat( String str )public boolean endsWith( String suffix )

public boolean equals( Object anObject )public boolean equalsIgnoreCase( String anotherString )

public int indexOf( int ch )public int indexOf( String str )

public int length()public boolean startsWith( String prefix )

public String substring( int beginIndex )public String substring( int beginIndex, int endIndex )public String toLowerCase()

public String toUpperCase()public String trim()

Some of these methods are described in the exercises and in future chapters. For now, just noticethat some of these methods return data about the string (such as length()) and some create new

strings based on the original string (such as toLowerCase()).

QUESTION 15:

Do any of these methods change the String object that contains them?

Answer:

 No. Once a String object has been created you cannot change its data. (Although you can create

a new String object that is an altered version of the original.)

Packages

A group of related classes is often put into a collection called a package. Many packages comestandard with Java. For example, the String class is part of the package called java.lang.

Several useful classes are part of that package. You can use the classes in this package withoutdoing anything special.

Other standard packages also come with Java. To use a class from one of these packages your  program must tell the compiler what package contains the class. One way to do this is to use the package name with the class. Here is a program that explicitly mentions where the String class

is found:

Page 189: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 189/293

 

class ImportDemo01{public static void main ( String[] args ){java.lang.String str;int len;

str = new java.lang.String( "Elementary, my dear Watson!" );

len = str.length();System.out.println("The length is: " + len );

}}

This program works the same way as the previous version. The package java.lang does not

need to be explicitly mentioned when you need to use String, although it does not hurt to do so.

QUESTION 16:

The class Scanner is not part of the java.lang package. Does a program that creates a Scanner

object need to tell the compiler where that class can be found?

Answer:

Yes. For most of the classes that come with Java you need to tell the compiler where they arefound.

import

Here is a program that creates a Scanner object. The program does nothing with this object (the

next chapter will do that).

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

java.util.Scanner scan ; scan = new java.util.Scanner( System.in );

 // do something with the Scanner object (see next chapter)

}}

Page 190: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 190/293

 

The compiler is told that the class Scanner is in the package java.util. Another way to do this

is to import the class, as in the following program:

import java.util.Scanner;

class ImportDemo03

{public static void main ( String[] args ){Scanner scan ;

 scan = new Scanner( System.in );

 // do something with the Scanner object (see next chapter)

}}

In the second version of the program, the statement:

import java.util.Scanner;

tells the compiler that the Scanner class is found in the java.util package, so the rest of the

 program does not need to include the package name each time Scanner is used.

QUESTION 17:

The package java.util contains various utility classes. Might a program need more than one of 

them?

Answer:

Yes.

Importing All Classes in a Package

Often a program will need more than one class from a particular package like java.util. It is

convenient in this case to import all the classes in the package at once, as the following programdoes:

import java.util.*;

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

Page 191: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 191/293

 

Scanner scan ; // a class in java.utilRandom rand ; // another class in java.util

 scan = new Scanner( System.in );rand = new Random( );

 // do something with the Scanner and Random objects (see following

chapters)}

}

The part import java.util.* means to import all the classes in the package. It does not hurt to

do this, even if you only need one or two of them.

QUESTION 18:

Is there ever (do you suppose) a need to make an object out of a primitive int?

Answer:

Yes. Sometimes your data is an int, a primitive, but you need the data in an object.

For example, a method might require an object for a parameter, but what you have is an int.

Type WrappersThere is a division between primitive data and objects. The division sometimes needs to becrossed. For each primitive type, there is a corresponding wrapper class. A wrapper class isused to put primitive data value into an object. Think of wrapping up the data with an object, likewrapping up a gift.

Wrapper classes can also go the other direction. Objects (of a wrapper class) can be convertedinto primitive data. The table shows primitive types and their wrapper classes. Java is casesensitive, so byte and Byte are different types.

As an example, the value 103 could be held in 32 bit section of memory that is of primitive datatype int. The same value could be held in an object that is of type Integer. The object will use

many more than 32 bits.

The wrapper classes are defined in the package java.lang and so (like all classes in that

 package) are automatically available to your programs.

primitive Wrapper

Page 192: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 192/293

 

type type

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

QUESTION 19:

Is String a wrapper class?

Answer:

 No. The only wrapper classes that exist are the eight classes in the table, one per each of theeight primitive types.

Example Wrapper

Here is a program that creates two wrapper objects, then prints out the values they hold. This program could easily be written without wrapper classes. Better uses for wrapper classes willoccur later in these chapters.

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

{Integer value = new Integer( 103 ); // hold the value 103

// inside an Integer objectDouble dvalue = new Double( -32.78 ); // hold a double precision

// value inside a Double object 

System.out.println( "Integer object holds: " + value );System.out.println( "Double object holds: " + dvalue );

}}

Page 193: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 193/293

 

QUESTION 20:

Was an import statement needed in this program?

Answer:

 No, because wrapper classes (and all other classes in java.lang) are automatically imported.

End of Chapter

That about wraps it up for this chapter. You may wish to review the following. Click on a subject

that interests you to go to where it was discussed.

• What an object is.• Picture of an object.• How objects are created.• Saving a reference in a reference variable.• Running a method of an object.• Dot notation.• Declaring a reference variable.• Methods that create objects.• Packages• Importing a package.•  Type wrappers.

The next chapter will discuss standard input and output.

CHAPTER 10 — Input and Output

This chapter discusses input and output for Java 5.0 and above. Most programs input data, process it, and then output the results. This chapter discusses ways to input data from thekeyboard and output results to the monitor. Later chapters will discuss input and output fromdisk files and other media.

Chapter Topics:

• Input and Output Streams•  The standard I/O streams• Scanner class• Exceptions• Converting character data to type int

Page 194: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 194/293

 

Note: Some books show input done using classes written by the book's author. To use them, youmust install a package from a CD or from a web site. This is OK. You can use these notes (withstandard Java methods) along with your text without any interference.

QUESTION 1:

When a computer program does an input operation, in which direction does the data flow?

• From an outside device into the program?• From the program out to some device?

• When a computer program does an input operation, in which direction does the dataflow?

Answer:

• From an outside device into the program.•

I/O• Input and output are so common that an abbreviation has been created: I/O (pronounced

eye-oh). I/O operations are very complicated, both at the software level and at theelectronic level. Part of the problem is that the way in which data is organized outside thecomputer is different from the way it is organized inside the computer. Lots of computation is needed to convert data between its various forms. Luckily, most of thecomplication has been hidden inside methods that your program can use.

• These notes use methods of the class java.util.Scanner for doing input. Scanner is

new to Java 5.0. Scanner is not part of the fundamental Java language, but is part of a package, java.util, that you can include in your program. A package is a collection of 

classes which may used in your program. Think of a package as a tool box and the classeswithin it as tools. Different programs need different tools and include different packages.

• It may seem odd to you that Java itself does not have I/O built into it. The reason for thisis that there are very many types of I/O, and a language that has all of them built in would be large and cumbersome. A language used for professional software development suchas Java (or C or C++ or any of several others) allows the programmer to pick the rightI/O package for the job.

QUESTION 2:• Your automobile has a computer that controls the motor as it monitors data from dozens

of sensors. Is this computer doing input and output?• Is your car's computer doing input and output?

Answer:

• Yes—data is input from sensors, computations are performed, and the results are outputto devices that control the motor.

Page 195: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 195/293

 

I/O Streams• If your car's program were written in Java, it would use a specialized I/O package that

manages sensors and controllers. It would not use the I/O package that deals withkeyboards and terminals.

• In Java, a source of input data is called an input stream and the output data is called anoutput stream. Think of these streams like this:

• In this picture, each "O" represents a chunk of data waiting in line to be input or leavingas output. Data input is called reading data, and data output data is called writing data(or  printing data if the output stream is connected to a monitor or a printer.)

• Think of the input stream as a string of pearls which the program inputs one at a time, inorder. The output stream is another string of pearls (not usually the same pearls as wereread in). Often a program will read several data and then combine them somehow to produce one output value. For example, the input data might be a list of numbers, theoutput data might be their sum.

QUESTION 3:

• If the program is a text editor (like Notepad) what are the input and output data?

Answer:

A stream of characters is input (from a file) and later a stream of characters is output (often to thesame file).

Standard Streams

Some programs read in the entire input stream before they write the output stream. Other  programs read the input stream item by item and write one output item for each input item. Thereare many other patterns of input and output. In general, a program may have several inputstreams flowing into it and several output streams flowing out of it.

There are three standard I/O streams:

• System.in — the input stream.• System.out — the output stream for normal results.

Page 196: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 196/293

 

• System.err — the output stream for error messages.

 Normally System.in is connected to the keyboard and the data are characters. System.out and

System.err both are connected to the monitor, and also contain character data. These notes do

not use System.err.

QUESTION 4:

What does the keyboard send to your program when you type the following:

1234

What does the keyboard send to your program when you type the following:

1234

Answer:

The characters '1' , '2' , '3' , and '4' .

Characters In, Characters Out

The keyboard sends character data to the computer, even when the characters look like

numbers. And the program sends characters to the monitor, even when it has calculated anumerical result. (Actually, characters are not sent directly to the monitor. They are sent to thegraphics card which converts them into a video signal which is displayed on the monitor.)

If your program does arithmetic, the input characters must be converted into one of the primitivenumeric data types. This is done using a Scanner object. Then a result is calculated using

arithmetic with the numeric data. The result must then converted into character data before it issent to the monitor. This is done using a method of System.out.

Page 197: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 197/293

 

QUESTION 5:

Have you already used System.out?

Answer:

Yes,

System.out.println( "Some string" )

sends characters to the output stream.

Example I/O Program

Here is a picture of a Java program doing character input and output. In this picture, the white box represents the entire program. The program has imported Scanner for use with input, and

has imported System.out for use with output.

The nextLine() method of Scanner reads a line of character data from the keyboard. The

characters go into a String object. An assignment statment puts a reference to the object in the

reference variable inData. To output the characters to the monitor, the program uses the

println() method of System.out.

QUESTION 6:

Do you suppose that a Scanner object has more methods than the one method in this picture?

Answer:

Yes — Scanner objects have many input methods.

Page 198: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 198/293

 

Echo.java

Here is the Java program. It reads characters from the keyboard and creates a String object to

contain them. A reference to the object is put in inData. Then it sends the characters from thatString to the monitor.

import java.util.Scanner;

class Echo{public static void main (String[] args){String inData;Scanner scan = new Scanner( System.in );

System.out.println("Enter the data:");

inData = scan.nextLine();

System.out.println("You entered:" + inData );}

}

The line import java.util.Scanner; says to use the Scanner class from the package

java.util. The java.io package is imported automatically when you import Scanner. Here is

a run of the program:

Please copy the program into a source file, compile it, and run it. It is helpful to actually run a

 program, rather than just read about it.

QUESTION 7:

Could the user include digits like 123 in the input characters?

Could the user include digits like 123 in the input characters?

Page 199: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 199/293

 

Answer:

Yes. They are characters just like any other.

Digits are Characters

As far as this program is concerned, a string of digits is a string of characters and is treated likeany string of characters. The digits are not automatically converted into a numeric type. Here isanother run of the program:

In a few pages you will see a program that reads in a string of digits and converts them into anumeric data type. Then arithmetic can be done with that data.

QUESTION 8:

Is data from the keyboard always only characters?

Answer:

Yes. (Although frequently those characters are converted to a numeric type after they have beenread in.)

DetailsLater on we will do something special to convert strings of digits into primitive numeric types.This program does not do that. Here is the program again:

import java.util.Scanner;

class Echo{

Page 200: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 200/293

 

public static void main (String[] args){String inData;Scanner scan = new Scanner( System.in );

System.out.println("Enter the data:");inData = scan.nextLine();

System.out.println("You entered:" + inData );}

}

class Echo 

 The program defines a class named Echo that contains a single method, its main()

method.

public static void main ( String[] args ) 

All main() methods start this way. Every program should have a main() method.

String inData; 

 The program creates a String object referred to by the reference variable inData.

Scanner scan = new Scanner( System.in ); 

 This creates a Scanner object, referred to by the reference variable scan.

QUESTION 9:

What data stream is this Scanner connected to?

Answer:

The standard input stream — the keyboard.

(Scanner objects can be connected to other data streams.)

Details (continued)

import java.util.Scanner;

class Echo

Page 201: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 201/293

 

{public static void main (String[] args){String inData;Scanner scan = new Scanner( System.in );

System.out.println("Enter the data:");inData = scan.nextLine();

System.out.println("You entered:" + inData );}

}

System.out.println("Enter the data:"); 

 This calls the method println to print the characters "Enter the data:" to the

monitor.

inData = scan.nextLine(); 

 This uses the nextLine() method of the object referred to by scan to read a line of 

characters from the keyboard. A String object (referred to by inData) is created to

contain the characters.

System.out.println("You entered:" + inData ); 

 This first creates a String by concatenating "You entered:" to characters from

inData, then calls println() to print that String to the monitor.

QUESTION 10:

When the program runs, can the user edit the input string (using backspace and other keyboardkeys) before hitting "enter"?

(Try this, if you have a running program.)

Answer:

Yes.

Digits as Input

Page 202: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 202/293

 

Collecting characters from the keyboard is done by the operating system. While this is going on,the Java program is suspended. The user can edit the line, and then hit "enter" to signal that it iscomplete. Only then does the Java program see the characters and resume execution.

Here is another run of the program:

Enter the data:Columbus sailed in 1492.You entered:Columbus sailed in 1492.

 Notice that the characters '1', '4', '9', and '2' were read in and written out just as were the other characters. Now consider yet another run:

Enter the data:1492You entered:1492

 Nothing special here. The '1', '4', '9', and '2' are just characters. If you want the user to enter numeric data, your program must convert from character data to a numeric type.

QUESTION 11:

What primitive type should normally be used to hold integer data?

Answer:

int 

nextInt()

The nextInt() method of a Scanner object reads in a string of digits (characters) and converts

them into an int type. The Scanner object reads the characters one by one until it has collected

those that are used for one integer. Then it converts them into a 32-bit numeric value. Usuallythat value is stored in an int variable.

Page 203: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 203/293

 

The picture shows a program that reads in character data and then converts it into an integer which is stored in num. Next the program does arithmetic with num and stores the result in

square. Finally the result is sent to println which converts the numeric result into characters

and prints them out.

The nextInt() method scans through the input stream character by character, gatheringcharacters into groups that can be converted into numeric data. It ignores any spaces and end-of-lines that may separate these groups.

QUESTION 12:

Can arithmetic be done with strings of characters?

Answer:

Not without first converting them into a numeric type.

EchoSquare.java

Here is the program shown the the previous picture. It computes the square of an integer entered(as characters) by the user.

import java.util.Scanner;

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

{ Scanner scan = new Scanner( System.in );int num, square; // declare two int variables

System.out.println("Enter an integer:");num = scan.nextInt();square = num * num ; // compute the square

System.out.println("The square of " + num + " is " + square);}

Page 204: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 204/293

 

}

Here is a picture of it running:

Please run this program and play with it. Beginning programers are often confused about"character data" and "numeric data" and conversions between the two. Take the opportunity tomake sure you know what is going on to avoid future confusion.

QUESTION 13:

Do you think that the following input would work with this program?

twelve hundred

Answer:

 No. The program only works with strings of digits that can be converted into integer data.

Converting to Integers

Here is a statement from the program:

num = scan.nextInt();

Assignment statements work in two steps:

1. Evaluate the expression on the right of the equal sign,2. Put the value in the variable on the left.

Page 205: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 205/293

 

In this particular assignment statement, the expression on the right scans a group of charactersfrom the input stream and converts them into an int, if that is possible. Then the numeric result

is stored into num.

If the group of characters cannot be converted, Java throws an Exception and stops your 

 program. An Exception object contains information about what went wrong in a program.Industrial-strength programs may examine the exception and try to fix the problem. Our  programs (for now) will just stop.

QUESTION 14:

Which of the following inputs would be correct input for the program?

Enter an integer: 1492Enter an integer: Fourteen ninety two

Enter an integer: 14.92Enter an integer: -1492Enter an integer: 1 4 9 2

Answer:Enter an integer: 1492 OKEnter an integer: Fourteen ninety two WRONGEnter an integer: 14.92 WRONGEnter an integer: -1492 OKEnter an integer: 1 4 9 2 MAYBE , but only the '1' will bescanned

InputMismatchException

If the user enters one of the WRONG lines, the statement num = scan.nextInt() will not be

able to scan the characters as an integer. It with throw an exception. You will see something like:

This exception was passed out of the running program to the Java system, which stopped the program and wrote the error messages.

Page 206: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 206/293

 

QUESTION 15:

(Trick Question: ) Can Scanner.nextInt() read the following as an integer?

+84

Answer:

 No. The + is not allowed as part of an integer. This is weird, and may change with a future

release of Java.

Another Example

Here is another example. It asks the user for two integers which are then added together and thesum written out.

import java.util.Scanner;

class AddTwo{public static void main (String[] args){Scanner scan = new Scanner( System.in );int first, second, sum ; // declaration of int variables

System.out.println("Enter first integer:");first = scan.nextInt(); // read chars and convert to int

System.out.println("Enter second integer:");second = scan.nextInt(); // read chars and convert to int

sum = first + second; // add the two ints, put result in sum

System.out.println("The sum of " + first + " plus " + second +" is " +sum );}

}

Here is a sample run:

Enter first integer:12Enter second integer:-8The sum of 12 plus -8 is 4

Page 207: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 207/293

 

QUESTION 16:

( A slightly hard question: ) explain what happened in the following run of the same program:

Enter first integer:12 -8Enter second integer:The sum of 12 plus -8 is 4Enter first integer:12 -8Enter second integer:The sum of 12 plus -8 is 4

Answer:

The nextInt() method scans through the input stream character by character, grouping

characters into groups that can be converted into numeric data. It ignores any spaces and end-of-lines that may separate these groups.

In the above, the user entered two groups on one line. Each call to nextInt() scanned in one

group.

It is tempting to think of the input as separate "lines". But a Scanner sees a stream of characters.

After it has scanned a group, it stops at where ever it is and waits until it is asked to scan again.

Integer Division Tester

Here is a new program made by modifying the first program.

•  The user enters two integers, dividend and divisor.•  The program calculates and prints the quotient and the remainder.•  The program calculates and prints quotient * divisor + remainder.

import java.util.Scanner;class IntDivideTest{public static void main (String[] args){

Scanner scan = new Scanner( System.in ); 

int dividend, divisor ; // int versions of inputint quotient, remainder ; // results of "/" and "%"

System.out.println("Enter the dividend:"); // read the dividenddividend = scan.nextInt();

System.out.println("Enter the divisor:"); // read the divisor

Page 208: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 208/293

 

divisor = scan.nextInt();

quotient = dividend / divisor ; // perform int mathremainder= dividend % divisor ;

System.out.println( dividend + " / " + divisor + " is " + quotient );System.out.println( dividend + " % " + divisor + " is " + remainder );System.out.println( quotient + " * " + divisor +

" + " + remainder + " is " + (quotient*divisor+remainder) );}

}

Run the program a few times. See what happens when negative integers are input.

QUESTION 17:

Do these notes still have your undivided attention?

Answer:

Huh? What??

End of the Chapter

Perhaps it is time to quit. When you are awake, click on a subject that interests you to go towhere it was discussed.

• I/O Packages• I/O Streams• standard I/O streams• First I/O Example Program. •  The Scanner  class. •  The nextLine()  Method. •  The nextInt()  Method. • Converting a data String into an int. • InputMismatchException 

• Program to add two integers. 

The next chapter discusses input of floating point numbers.

You have reached the end of the chapter.

Page 209: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 209/293

 

CHAPTER 11 — Floating Point

Java includes the primitive types float and double, which hold floating point numbers. When

converted to characters, floating point numbers include a decimal point followed by a decimal

fraction. For example, 3.14159 and -0.718802.

Chapter Topics:

• Converting strings to double• Keyboard input of floating point numbers•  The Math class• Square root•  Trig functions• PI• Not a Number (NaN)

All of the familiar mathematical functions such as sine, log , and square root are available to your  program in the Java Math class. These functions usually use arguments of type double, and

usually return values of type double.

QUESTION 1:

Which uses more bits: a Java float or a a Java double ?

Answer:

double. As you might expect, it uses twice as many bits as a float.

Size of Floats

Floating Point Primitive

Data Types

Type Size Range

float32

bits

-3.4E+38 to

+3.4E+38

doubl

e

64

bits

-1.7E+308 to

1.7E+308

Page 210: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 210/293

 

In main storage and in disk storage, a float is represented with a 32-bit pattern and a double is

represented with a 64-bit pattern. For input from the keyboard, character data must be convertedinto floating point data. For output to the monitor or to a text file, floating point data areconverted into characters.

You almost never need to worry about the range of numbers that can be represented in a floating point variable. Ordinarily you use a double when you need a floating point type. The range and

accuracy are both much better than with a float and the extra memory used for double is not

noticible unless you are building a very large data structure.

QUESTION 2:

The data type int and the data type float both use 32 bits.

Is the pattern of the 32 bits for the int value 221 the same as the pattern for the float value221.0?

Answer:

 No. Integer and floating point types use different bit patterns to represent values.

Reading a double from the Keyboard

The scheme used to represent integers is completely different from the scheme used to representfloating point. Even though you might regard 221 and 221.0 as equivalent, the bit patterns thatthey use are completely different.

Scanner does floating point input in a way similar to integer input. Use a Scanner object to scan

through a stream of input characters and to convert them into a float or a double. The methods

that do this are nextFloat() and nextDouble().

Here is a program that converts a string of input characters into primitive type double, and then

 prints out that value and twice that value:

// This program requires Java 1.5 or higher//import java.io.*;import java.util.Scanner;

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

Page 211: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 211/293

 

double value;Scanner scan = new Scanner( System.in );

 System.out.print("Enter a double:");value = scan.nextDouble();

System.out.println("value: " + value +" twice value: " + 2.0*value );}

}

The program writes:

C:\temp>java DoubleDoubleEnter a double: 3.14value: 3.14 twice value: 6.28

It would be worth your effort to copy this program to a file and to compile and run it.

QUESTION 3:

What do you suppose happens if the user types in an integer value, like 211?

What do you suppose happens if the user types in an integer value, like 211?

Answer:

The characters are converted into a double.

Exceptions

The input characters are converted into a double, if that is possible, even if the input characters

lack a decimal point.

If the input characters can NOT be converted into a double, then Java throws an exception and

the program halts. (A later chapter will discuss how to deal with exceptions.) For example:

C:\temp>java DoubleDoubleEnter a double: ratsException in thread "main" java.util.InputMismatchException

at java.util.Scanner.throwFor(Unknown Source)at java.util.Scanner.next(Unknown Source)at java.util.Scanner.nextDouble(Unknown Source)at DoubleDouble.main(DoubleDouble.java:14)

Page 212: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 212/293

 

The input might start with characters that can be converted, followed by one or more spaces and perhaps additional characters. If that happens, nextDouble() scans in only the characters that

can be converted.

C:\temp>java DoubleDoubleEnter a double: 3.14 and more charactersvalue: 3.14 twice value: 6.28

If the program had another call to nextDouble() it would start where the previous call stopped

and would find characters that can't be converted, and would throw an exception.

QUESTION 4:

Will the following input work with the above program?

C:\temp>java DoubleDoubleEnter a double: -97.65

?????

Answer:

Yes, the minus sign is acceptable:

C:\temp>java DoubleDoubleEnter a double: -97.65value: -97.65 twice value: -195.3

Scientific Notation

Scientific notation is another way to write a number. In scientific notation, the letter E is used to

mean "10 to the power of." For example, 1.314E+1 means 1.314 * 101 which is 13.14.

Scientific notation is merely a format used for input and output. The 64-bit pattern used for adouble inside the computer are the same, no matter what character format was used for input.

Here is an example:

C:\temp>java DoubleDoubleEnter a double: 1.234E+9value: 1.234E9 twice value: 2.468E9

Here the user entered data using scientific notation, and nextDouble() converted those characte

into a double. If the user entered 1234000000, those characters would be converted into the

same double. When a double is converted into characters, scientific notation is used when

needed for very large or very small values.

Page 213: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 213/293

 

The input characters may use an upper or lower case "e":

C:\temp>java DoubleDoubleEnter a double: -7.001e-2value: -0.07001 twice value: -0.14002

In this example, the user chose scientific notation for input. On output, the values were in thenormal range and the ordinary number format was used.

QUESTION 5:

What is the meaning of 7.0E-2 ?

What is the meaning of 7.0E-2 ?

The "E-2" part means 10-2 which is 0.01, so the complete expression means 0.07

Adding Two Doubles

Here is the start on a program that asks the user for two doubles, adds them together, and writesout the result.

import java.io.*;

import java.util.Scanner;

class AddDoubles{public static void main (String[] args){double first, second, sum;Scanner scan = new Scanner( System.in );

 // Read in the first doubleSystem.out.print("Enter the first double:");first = scan.nextDouble();

// Read in the second double// Compute the sum and write it out

sum =

System.out.println()

}}

Page 214: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 214/293

 

Fill the blanks to complete the program. (Do this by clicking in a blank and typing. Nothingspecial happens when you fill the blanks They are just there to give you a place to type.)

QUESTION 6:

Fill in the blanks.

Answer:

See below

Filled BlanksThe blanks can easily be filled with a little typing aided by copy and paste from other parts of the program.

import java.io.*;import java.util.Scanner;

class AddDoubles{public static void main (String[] args){double first, second, sum;

Scanner scan = new Scanner( System.in ); 

// Read in the first doubleSystem.out.print("Enter the first double: ");first = scan.nextDouble();

// Read in the second doubleSystem.out.print("Enter the second double: ");second = scan.nextDouble();

// Compute the sum and write it outsum = first + second;System.out.print("Sum: " + sum );

}}

Here is a run of the program:

C:\temp>java AddDoublesEnter the first double: 10.59Enter the second double: 8.02Sum: 18.61

Page 215: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 215/293

 

QUESTION 7:

(Thought Question: ) Could the variable sum be eliminated from this program?

Answer:

Yes. The last line could be written

System.out.print("Sum: " + (first + second) );

 Now the declaration of sum and the statement that calculates it can be removed. The parentheses

in (first + second) are necessary to show that the addition first + second should be done

first, followed by conversion to characters and concatenation to "Sum: " 

A Story Problem

Say that you want a program that calculates the total bill for a restaurant meal. The program willinput the cost of the meal. To this is added a 20% tip and 6% sales tax. Use double for aritmetic.

Here is the program:

import java.io.*;import java.util.Scanner;

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

{double basicCost;System.out.println("basic cost: " + basicCost + " total cost: " + );}

}

Here are the missing parts, but not in order:

(basicCost + basicCost*0.06 + basicCost*0.20)

System.out.print("Enter the basic cost: ");

Scanner scan = new Scanner( System.in );

basicCost = scan.nextDouble();

Copy these missing parts and paste into the blanks to complete the program. (Copy byhighlighting a part with the mouse and hitting control-C. Paste by clicking in a box and hittingcontrol-V.)

Page 216: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 216/293

 

QUESTION 8:

Fill in the missing parts.

Answer:

The full program is below:

Full Restaurant Program

Here is the complete program. Hopefully you figured out the proper order for the lines. Youshould be able to read the program line by line, almost like a story.

import java.io.*;import java.util.Scanner;

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

{Scanner scan = new Scanner( System.in );double basicCost;

System.out.print("Enter the basic cost: ");basicCost = scan.nextDouble();

System.out.println("basic cost: " + basicCost + " total cost: " +(basicCost + basicCost*0.06 + basicCost*0.20) );

}}

As you read the story (the program) it should make sense. Actions should follow in a logicalorder. The logic is the important part, not the fussy details of syntax.

QUESTION 9:

Some big programming projects have failed badly, costing billions of dollars. What do yousuppose is true:

•  The projects failed because the programmers did not know syntax, or•  The projects failed because the logic was bad

Page 217: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 217/293

 

Answer:

•  The projects failed because their logic was bad.

Of course.

New, Improved Restaurant Program

Perhaps we should practice programming logic a little. Modify the program so the user enterscost of the meal and the percentage for the tip. (The tax rate remains the same.) Then the program calculates and prints the total cost.

import java.io.*;import java.util.Scanner;

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

{Scanner scan = new Scanner( System.in );double basicCost;

System.out.print("Enter the basic cost: ");basicCost = scan.nextDouble();

System.out.println("basic cost: " + basicCost + " total cost: " +

(basicCost + basicCost*0.06 + basicCost*0.20) );}

}

This time, there are no blanks to fill. Your job is to figure out how to change the program byinserting the following statements and parts of statements (not given in order). Do this bycopying and pasting.

basicCost*tipPercent

System.out.print("Enter the tip percentage: ");

double tipPercent;

tipPercent = scan.nextDouble();

If you want, you can copy and paste the program into a text editor and save to a file which youcan then compile and run.

Page 218: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 218/293

 

QUESTION 10:

Copy and Paste (control-C and control-V) the suggested statements into the program, and edit afew other statements.

Answer:

The new improved program follows.

New, Improved Restaurant Program

Your program should look much like the following:

import java.io.*;import java.util.Scanner;

class RestaurantBill{public static void main (String[] args){Scanner scan = new Scanner( System.in );double basicCost;double tipPercent;

System.out.print("Enter the basic cost: ");basicCost = scan.nextDouble();System.out.print("Enter the tip percentage: ");tipPercent = scan.nextDouble();

System.out.println("basic cost: " + basicCost + " total cost: " +(basicCost + basicCost*0.06 + basicCost*tipPercent) );

}}

The println statement now uses the variable tipPercent, which contains the percentage the

user wishes to tip.

QUESTION 11:

If the println statement were not changed, would the Public Health Inspector give your 

 program a passing grade?

Answer:

 No—bugs are not allowed in restaurants, nor in programs.

Page 219: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 219/293

 

Java as a Calculator

All of the familiar mathematical functions found on an electronic calculator such as  sine, log ,and square root are available in the Java Math class. Typically these functions expect data type

double as a parameter and return a double value.

Here is a program that reads a floating point number from the keyboard and prints out its squareroot:

import java.util.Scanner;

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

{Scanner scan = new Scanner( System.in );double value;

// read in a doubleSystem.out.print ("Enter a double:");value = scan.nextDouble();

 // calculate its square rootdouble result = Math.sqrt( value );

 // write out the resultSystem.out.println("square root: " + result );

}}

The assignment statement (in blue) uses the sqrt() method of the class Math. This is a static

method, which means that you ask for it using the name of a class and a dot operator, like this:

Class . method ( parameters )

This looks the same as calling a method of an object, but here a class name is used, not an objectname.

QUESTION 12:

The class Math also has a log method that returns the natural logarithm of its argument. Mentally

modify the program so that it returns the log of the input value.

Page 220: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 220/293

 

Answer:

Only two lines need to be changed:

double result = Math.log( value );

System.out.println("logarithm: " + result );

sqrt() Method

Here is sample output from the (unmodified) program:

C:\chap11>java SquareRootEnter a double: 3square root : 1.7320508075688772

It is OK to enter a number without a decimal point (as the "3" above) for floating point IO. Javaconverts it to the correct type. Here is some of the documentation for the method sqrt():

static double sqrt(double a)Returns the correctly rounded positive square root of a double value.

This was copied from the Java documentation at http://java.sun.com/javase/6/docs/api/. Searchfor "sqrt Java" with a search service (like Google) when you need it.

QUESTION 13:

Inspect the documentation. What is the type of the argument expected by sqrt()?

What is the type of value returned by sqrt()?

Is sqrt() a static method?

Answer:

Inspect the documentation. What is the type of the argument expected by sqrt()?

double 

What is the type of value returned by sqrt()?

double 

Page 221: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 221/293

 

Is sqrt() a static method?

 Yes

NaN

If you look further at the documentation for sqrt() you find some details:

Returns the correctly rounded positive square root of a double value. If the

argument is NaN or less than zero, the result is NaN.

NaN stands for "Not a Number". This is a 64-bit pattern that is returned by sqrt() when its

argument is not correct. Here is an example run of the program:

C:\chap11>java SquareRootEnter a double: -3square root : NaN

println() converts the 64-bit pattern into the characters "NaN". (The actual bit pattern is not

character data.)

QUESTION 14:

What does this fragment output:

int x = 9;System.out.println( Math.sqrt( x ) );int x = 9;System.out.println( Math.sqrt( x ) );

Answer:

3.0

Automatic Conversion

Even though sqrt() expects a double for an argument, here we gave it an int. This is OK. The

compiler knows what sqrt() expects and automatically inserts code to convert the argument to

the correct type. When sqrt() is called it has the double precision floating point argument that it

expects.

Page 222: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 222/293

 

Often programmers use a type cast to show explicitly where the type conversion takes place:

int x = 9;System.out.println( Math.sqrt( (double)x ) );

In the above code, the type case is not required, but it is used to clearly show what is intended.Sometimes a type cast is required.

QUESTION 15:

What does the following fragment write?

int x = 1;int y = 9;System.out.println( Math.sqrt( x/y ) );

Warning: this is a trick question!

int x = 1;int y = 9;System.out.println( Math.sqrt( x/y ) );

Answer:

0.0

Hidden Integer Division

The "trick" in this question is that the division of x by y is the first thing done in evaluating the

statement. Since both x and y are integers, integer division is done and the result is integer 0.

 Next, the integer 0 is converted to double precision 0.0, and it is that value that is sent to sqrt(),

which computes 0.0 as a result.

Although the question was a "trick" this situation often occurs naturally in programs and you

should watch out for it.

QUESTION 16:

Does the following correct the problem?

Page 223: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 223/293

 

int x = 1;int y = 9;System.out.println( Math.sqrt( (double)x/y ) );int x = 1;int y = 9;System.out.println( Math.sqrt( (double)x/y ) );

Answer:

Yes.

Type Casting

In the above, the integer in x is converted to double before the division is done. Now y must also

 be converted to double and double precision floating point division is performed.

 Next the result (0.111111111) is sent to sqrt() as an argument. The expected result

(0.33333333) is returned.

QUESTION 17:

Are these details a little overwhelming?

Answer:

 Yes.

PI

Don't be discouraged. Usually things work as you expect. If you can do math with an electroniccalculator then you can do it with Java. Occasionally there are annoying details, but that is trueof calculators, also.

Here is another excerpt from the Java documentation:

PI

public static final double PI

The double value that is closer than any other to pi,the ratio of the circumference of a circle to its diameter.

The reserved word final in this means that the value PI will not change.

Page 224: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 224/293

 

To use π in a program say Math.PI (the PI must be upper case). Here is an example:

double x = Math.PI;

QUESTION 18:

Java has trigonometic functions, just like a calculator. For example it has the functionMath.cos().

Do you expect that the argument to Math.cos() to be in radians or in degrees?

Answer:

radians

Radians

As is normal for most calculators (and most programming languages), the arguments for Java'strigonometric functions are in radians. Unlike most calculators, you can't push a button andswitch to degrees. Here is an example program:

import java.io.*;import java.util.*;

class CosineCalc{public static void main (String[] args){double value;Scanner scan = new Scanner( System.in );

 System.out.print("Enter radians:");value = scan.nextDouble();

 // calculate its cosinedouble result = Math.cos( value );

 

// write out the resultSystem.out.println("cosine: " + result );}

}

Here is an example run:

C:\chap11>java CosineCalcEnter radians:1.5

Page 225: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 225/293

 

cosine: 0.0707372016677029

QUESTION 19:

What do you suspect are the types of the argument and return value for Math.cos()?

Answer:

Both are double.

Cosine Documentation

Here is some of the documentation:

java.langClass Math

...

cos

public static double cos(double a)

Returns the trigonometric cosine of an angle.

cos is a static function of the class Math, which is found in the java.lang package.Classes from that package (such as String and Math) are so common that you do

not have to import the package. The angle a is a double and must be expressed inradians. The return value is a double.

QUESTION 20:

(Math Review: ) Can angles in radian mesure be converted to degrees?

Answer:

Of course! You memorized that formula in high school (and forgot five minutes later).

Fun and Simple Trig!

Actually the formula is not that bad:

radians = (Math.PI/180.0)*degrees;

Page 226: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 226/293

 

Since this is so common, the Math class has convenient methods:

public static double toRadians(double angdeg)Converts an angle measured in degrees to the equivalent in radians

 public static double toDegrees(double angrad)

Converts an angle measured in radians to the equivalent in degrees.

Here is our sample program:

import java.io.*;class CosineCalc{public static void main (String[] args){Scanner scan = new Scanner( System.in );double degrees;

// read in the degrees

System.out.print ("Enter degrees:");degrees = scan.nextDouble();

// calculate its cosinedouble result = Math.cos(

); 

// write out the resultSystem.out.println("cosine: " + result );

}}

QUESTION 21:

Fill in the blank so that the program works.

Answer:// calculate its cosine

double result = Math.cos( Math.toRadians(degrees) );

Function Results as Arguments

One function is nested inside another:

double result = Math.cos( Math.toRadians(degrees) );

This is perfectly fine, and is a reasonable way to write the code, as long as the inner functionreturns a value that is correct for the outer function. In fact, you could nest the function callswithin println():

// calculate its cosine and print the resultSystem.out.println("cosine: " + Math.cos( Math.toRadians(degrees) ) );

Page 227: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 227/293

 

It is a matter of taste, sometimes, how much put in one statement. Your goal should be to makethe logic clear, not to save typing.

QUESTION 22:

Which page in this chapter is your favorite?

Answer:

The last page.

The Last PageYou may wish to review the following.

• Sizes of floating point. • Reading in a floating point value. • Bad floating point data. • Scientific Notation•  The square root function. • Static methods. • Not an number, NaN. • PI • Cosine• Converting between degrees and radians

The next chapter shows how a program can make decisions.

You have reached the end of the chapter.

CHAPTER 12 — Decision Making

Page 228: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 228/293

 

This chapter looks at how computer programs make decisions using the if statement. This

statement is one of the fundamental building blocks of programming.

Chapter Topics:

•  Two-way Decisions•  The if statement• Outline of a two-way decision• Blocks of statements• Boolean Expressions• Relational Operators• Example Programs

QUESTION 1:

You are driving in your car and it starts to rain. The rain falls on your windshield and makes ithard to see. Should your windshield wipers be on or off?

Answer:

On.

Two-way Decisions

Page 229: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 229/293

 

The windshield wipers are controlled with an ON-OFF switch. The flowchart at right shows howthis decision is made.

Start at the top of the chart then follow the line to the question:

is it raining?

The answer is either true or  false.

• If the answer is true,o follow the line labeled True,o perform the instructions in the box "wipers on",o follow the line to "continue".

• If the answer is false,o follow the line labeled False,o perform the instructions in the box "wipers off",o follow the line to "continue".

QUESTION 2:

How many ways can you go from "start" to "continue"?

Answer:

Two.

Page 230: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 230/293

 

Decisions

The windshield wiper decision is a two-way decision (sometimes called a binary decision). Thedecision seems small, but in programming, complicated decisions are made of many small

decisions. Here is a program that implements the wiper decision:

import java.util.Scanner;class RainTester{public static void main (String[] args){Scanner scan = new Scanner( System.in );String answer;

System.out.print("Is it raining? (Y or N): ");answer = scan.nextLine();

 

if ( answer.equals("Y") ) // is answer exactly "Y" ?System.out.println("Wipers On"); // true branchelseSystem.out.println("Wipers Off"); // false branch

}}

The user is prompted to answer with a single character, Y or N :

System.out.print("Is it raining? (Y or N): ");

The Scanner reads in whatever the user enters (even if the user enters more than one character):

answer = scan.nextLine();

The if statement tests if the user entered exactly the character Y (and nothing else):

if ( answer.equals("Y") ) // is answer exactly "Y" ?

If so, then the statement labeled "true branch" is executed. Otherwise, the statement labeled"false branch" is exectued.

The "true branch" is separated from the "false branch" by the reserved word else.

QUESTION 3:

What happens if the user enters anything other than exactly the character Y ?

Answer:

If the user enters anything other than exactly the single character Y then the "false branch" isexectued.

Page 231: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 231/293

 

Checking a String

The if statement

if ( answer.equals("Y") )

 picks either the "true branch" or the "false branch" . Only one branch or the other is executed, just as in the flow chart. This part of the statement

answer.equals("Y")

evaluates to true if the string referenced by answer contains exactly the single character "Y" .

For anything else it evaluates to false. This is somewhat awkward. Dealing with user input is

often awkward. Later on you will see better ways to do this. Here are some runs of the program:

C:>javac RainTester.java

C:>java RainTesterIs it raining? (Y or N): YWipers On

C:>java RainTester

Page 232: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 232/293

 

Is it raining? (Y or N): NWipers Off

C:>java RainTesterIs it raining? (Y or N): YesWipers Off

C:>java RainTesterIs it raining? (Y or N): RatsWipers Off

QUESTION 4:

Is the integer -12 negative or not?

Answer:

-12 is negative.

Number Tester

An integer may be negative, or not. If it is not negative, then it is positive or zero. Here is thatidea expressed as a flow chart:

Page 233: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 233/293

 

The diamond box shows a two-way decision. Either the false branch or the true branch is takendepending on whether 

num < 0

is true or false.

The "two-way split" of the program is easy to see in a two dimensional chart. It is harder to seethis in a program where line follows line one after another. The flow chart shows the overalllogic of the program. Most of the details of syntax are left out. It is often helpful to sketch aflowchart when you are designing a program. You can use the flowchart to get the logic correct,then fill in the details when you write the program.

QUESTION 5:

The user runs the program and enters "12". What will the program print?

Answer:Enter an integer:12The number 12 is zero or positiveGood-bye for now

The false branch is executed because the answer to the question num < 0 was false.

The Program

Here is the number tester implemented as a program:

import java.util.Scanner;

class NumberTester{public static void main (String[] args){Scanner scan = new Scanner( System.in );int num;

System.out.println("Enter an integer:");num = scan.nextInt();

 if ( num < 0 )System.out.println("The number " + num + " is negative");

elseSystem.out.println("The number " + num + " is zero or positive");

System.out.println("Good-bye for now");}

}

Page 234: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 234/293

 

The words if and else are markers that divide the decision into two sections. The else divides

the true branch from the false branch. The if is followed by a question enclosed in parentheses.

The expression num < 0 asks if the value in num is less than zero.

•  The if statment always asks a question (often about a variable).•

If the answer is true only the true branch is executed.• If the answer is false only the false branch is executed.• No matter which branch is chosen, execution continues with the statement

after the false branch.

 Notice that a two-way decision is like picking which of two roads to take to the same destination.The fork in the road is the if statement, and the two roads come together just after the false

 branch.

QUESTION 6:

The user runs the program and enters -5. What will the program print?

Answer:Enter an integer:-5The number -5 is negativeGood-bye for now

Only the true-branch was executed because the answer to the question num < 0 was true.

Simulated Program

Here is a simulation of this program (using JavaScript and your browser). Of course, for maximum benefit copy the program to a file and run it. But, play with the following if you want.Perform the steps 1, 2, and 3 under the simulated monitor as many times as you want. (Note: if this does not work, your browser does not have JavaScript enabled. Skip this and go on to thenext page.)

import java.util.Scanner;

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

{Scanner scan = new Scanner( System.in );int num;

System.out.println("Enter an integer:");num = scan.nextInt();

 if ( num < 0 )System.out.println("The number " +

num + " is negative");

Page 235: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 235/293

 

elseSystem.out.println("The number " +

num + " is zero or positive");

System.out.println("Good-bye for now");}

}

Simulated Monitor

This is just a simulation (using JavaScript), so it is not exactly like a compiling and running areal Java program. Don't take it too seriously. Please do the real thing if you can.

QUESTION 7:

Try the program (or look at the flowchart) with the value 0 (zero). What is the output?

Answer:Enter an integer:0The number 0 is zero or positiveGood-bye for now

Zero is neither negative nor positive, (although often programs treat zero as if it were positive). Itwould be nice to treat it as a separate case. This problem will be fixed in a few pages.

More than one Statement per Branch

Here is the program again with some added statements:

import java.util.Scanner;

class NumberTester{public static void main (String[] args){Scanner scan = new Scanner( System.in );int num;

System.out.println("Enter an integer:");num = scan.nextInt();

if ( num < 0 ){System.out.println("The number " + num + " is negative."); // true-

branchSystem.out.println("Negative numbers are less than zero."); // true-

branch}else{

Page 236: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 236/293

 

System.out.println("The number " + num + // false-branch

" is zero or positive."); // false-branch

System.out.print ("Positive numbers are greater "); // false-branch

System.out.println("than zero. "); // false-branch

}

System.out.println("Good-bye for now"); // always executed}

}

To include more than one statement in a branch, enclose the statements with braces, { and }. A

group of statements grouped together like this is called a block statement, (or usually, justblock ). There can be as many statements as you want in a block. A block can go anyplace asingle statement can go. All the statements in the true block are executed when the answer to thequestion is true.

Of course, all the statements in the false block are executed when the answer to the question is false. The false block consists of the block that follows the else. Notice that the very last

statement in the program is not part of the false block.

QUESTION 8:

The user enters a 17. What will the new program print?

Answer:Enter an integer:17The number 17 is zero or positive.Positive numbers are greater than zero.Good-bye for now

The false block was executed because the answer to the question (num < 0) was false. The false

 block consists of three statements.

Outline of a Two-way Decision

Here is an outline of a two-way decision structure:

// statements that are executed before the decision

if ( condition )// true branch

else

Page 237: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 237/293

 

// false branch

// statements that are executed after the branches join together again

Here are some details:

• The condition evaluates to true or  false, often by comparing variables and values.• The else divides the true branch from the false branch.• The statements after the false branch are always executed.• A block consists of several statements inside a pair of braces, { and }.• The true branch can be a block.• The false branch can be a block.• There can be as many statements in a block as you need.• When a block is chosen for execution, the statements in it are executed one by one.

The condition can compare what is held in a variable to other values. You can use thecomparisons <, >, and so on. (More about these later.) The first statement after the false branch

will be executed no matter which branch is chosen. The if-else is like a fork in the road, butthe road always comes together again.

QUESTION 9:

Is the following section of a program correct?

if ( num < 0 )System.out.println("The number " + num + " is negative.");

elseSystem.out.println("The number " + num + " is zero or positive.");System.out.print ("Positive numbers are greater ");System.out.println("than zero. ");

System.out.println("Good-bye for now");

Answer:

 No. The programmer probably wants the three statements after the else to be part of a false

 block, but has not used braces to show this.

Only One Statement per Branch

The false block was not put inside braces:

if ( num < 0 )System.out.println("The number " + num + " is negative.");

elseSystem.out.println("The number " + num + " is zero or positive.");System.out.print ("Positive numbers are greater ");System.out.println("than zero. ");

Page 238: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 238/293

 

System.out.println("Good-bye for now");

Our human-friendly indenting shows what we want, but the compiler ignores indenting. Thecompiler groups statements according to the braces. What it sees is the same as this:

if ( num < 0 )System.out.println("The number " + num + " is negative."); //

true-branchelse

System.out.println("The number " + num + " is zero or positive"); //false-branchSystem.out.print ("Positive numbers are greater "); // alwaysexecutedSystem.out.println("or equal to zero. "); // alwaysexecutedSystem.out.println("Good-bye for now"); // alwaysexecuted

QUESTION 10:

How would you fix the problem?

Answer:if ( num < 0 )System.out.println("The number " + num + " is negative."); // true-

branchelse{System.out.println("The number " + num + " is zero or positive"); //

false-branchSystem.out.print ("Positive numbers are greater "); //

false-branchSystem.out.println("or equal to zero. "); //false-branch} System.out.println("Good-bye for now"); // alwaysexecuted

The true branch has one statement. The false branch has one statement, a block containing threestatements.

Practice

Page 239: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 239/293

 

At a movie theater box office a person less than age 13 is charged the "child rate". Otherwise a person is charged the "adult rate." Here is a partially complete program that does this:

import java.util.Scanner;class BoxOffice

{public static void main (String[] args){Scanner scan = new Scanner( System.in );int age;

 System.out.println("Enter your age:");age = scan.nextInt();

if (){System.out.println("Child rate.");

}else{System.out.println("Adult rate.");

}System.out.println("Enjoy the show."); // always executed

}}

In this program, the true branch and the false branch are both blocks. Each block contains onlyone statement, but this is OK. Often programmers do this for clarity.

QUESTION 11:

Fill in the blank so that a person under the age of 13 is charged the child rate.

Answer:if ( age < 13 )

Box Office Program

Page 240: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 240/293

 

Here is the program with the blank filled in correctly:

import java.util.Scanner;class BoxOffice{public static void main (String[] args)

{Scanner scan = new Scanner( System.in );int age;

 System.out.println("Enter your age:");age = scan.nextInt();

if ( age < 13 ){System.out.println("Child rate.");

}else{System.out.println("Adult rate.");

}System.out.println("Enjoy the show.");

}}

Here is what happens for one run of the program:

1. The program prints "Enter your age".2. The user enters an age: "21", for example.3. The string "21" is converted from characters into an int and put into the

variable age.

4. The condition age < 13 is tested.5. 21 < 13 is false.6. The false branch is executed: the program prints "adult rate".7. Execution continues with the statement after the false branch: "Enjoy the

show" is printed.

QUESTION 12:

What does the program output if the user enters 11?

Answer:Enter your age

11Child rateEnjoy the show

Boolean Expressions

Relational Operators

Page 241: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 241/293

 

Operator MeaningA == B  is A equal to B ?A < B  is A less than B ?A <= B  is A less than or equal to B ?A > B  is A Greater than B ?A >= B  is A Greater than or equal to B ?A != B  is A not equal to B ?

We need to look at the condition part of the if statement. Usually this is a boolean expression.

Recall that an expression is is a combination of literals, operators, variable names, and parentheses used to calculate a value.

A boolean expression is an expression that evaluates to true or  false.

Boolean expressions often compare numbers. A relational operator says how the numbers arecompared.

Here are some annoying details (that will be really annoying later on if you forget about them):

• The operator for "equal" is == (two equal signs in a row). In your web browser it may

 be hard to see that there are two equal signs.• The operator for "not equal" is != (exclaimation point equal sign).

It is easy to forget these two details, and easy to overlook these details in a program. You mightspend hours debugging a program because a = was used where a == belongs.

QUESTION 13:

Fill in the blanks in the following chart:

Expressi

on

Valu

e

Express

ion

Valu

e

25 ==

2525 != 25

25 <=

2525 > 25

25 >=

2525 = 25

-5 < 7-305 <=

97

Page 242: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 242/293

 

Answer:

Expressi

on

Valu

e

Express

ion

Valu

e

25 ==25 true 25 != 25 false

25 <=

25true 25 > 25 false

25 >=

25true 25 = 25 illegal

-5 < 7 true-305 <=

97true

Using Boolean Expressions

In an if statement, the true or  false of a boolean expression picks whether the true branch or the

false branch is executed. Look at another story problem:

A store wants a program that calculates the tax on an item of clothing. An item that

costs $100 or more has a 5% tax. An item that costs less than $100 is tax free.

Write a program that asks for a price, then calculates and prints the tax, then prints

the total cost.

Here is the program, not quite finished:

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

double price;double tax ;

System.out.println("Enter the price:");if ()elseSystem.out.println("Item cost: " + price + " Tax: " + tax + " Total: " +(price+tax) );}

}

Page 243: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 243/293

 

Here are some program fragments to use in completing the program. Use your mouse to copy-and-paste them into the program.

tax = price * taxRate; Scanner scan = new Scanner( System.in );price = scan.nextDouble(); final double taxRate = 0.05;price >= 100.0 import java.util.Scanner;

tax = 0.0;

(Of course, it would be nice to copy the program to a file, enter your corrections and run the program.)

QUESTION 14:

Complete the program by filling in the blanks.

Answer:

The answer is given below:

Adding in a Zero

Here is the complete program.

import java.util.Scanner;class TaxProgram{public static void main (String[] args){

final double taxRate = 0.05;Scanner scan = new Scanner( System.in );double price;double tax ;

System.out.println("Enter the price:");price = scan.nextDouble();

if ( price >= 100.0 )tax = price * taxRate;

elsetax = 0.0;

System.out.println("Item cost: " + price + " Tax: " + tax + " Total: " +(price+tax) );}

}

Is the logic of the program is correct? The expression (price+tax) in the last statement

sometimes adds zero to price. This is fine. Adding zero does not change the result.

Page 244: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 244/293

 

QUESTION 15:

The user buys a shirt for $100 What will be printed on the monitor?

Answer:

Enter the price:100Item cost: 100 Tax: 5.0 Total: 105.0

Three-way Decisions

You might wonder about the restriction that an if statement makes only a two-way decision.

Surely you must sometimes pick from more than just two branches?

We ran into this problem with a previous example program that divided integers into negativeand non-negative. It really should pick one of three choices:

• Negative: ... -3 -2 -1 • Zero: 0 • Positive: +1 +2 +3 ... 

Two-way decisions can do this. First divide the integers into two groups (using a two-waydecision):

• Negative: ... -3 -2 -1 • Zero and Positive: 0 +1 +2 +3 ... 

Then further further divide the second group (by using another two-way decision):

• Negative: ... -3 -2 -1 • Zero and Positive: 

o Zero: 0 o Positive: +1 +2 +3 ... 

By repeatedly splitting groups into subgroups, you can split a collection into any number of finedivisions.

QUESTION 16:

How could you divide a group of people into:

• children• male adults• female adults

Page 245: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 245/293

 

Answer:

You could first divide the group into:

• children•

adults

And then divide the adults into:

• male adults• female adults

Flowchart

We wish to perform two splits to divide integers into negative, zero, and positive. First zero and

 positives are split from the negatives, and then that group is further split.

Page 246: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 246/293

 

The flowchart shows how this works. One decision is nested inside the false branch of the firstdecision. A negative integer is correctly sorted out by the first decision. But a zero or positiveinteger goes through another decision to pick the correct category for it.

QUESTION 17:

Are there other ways to do this?

Answer:

Yes. There are other tests that divide the integers into these three groups. But you will alwaysneed two tests, whatever they are.

Page 247: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 247/293

 

Number Tester Program

Here is a program that implements the flowchart. The part that corresponds to the nested decisionof the flow chart is in red. This is called a nested if statement because it is nested in a branch of 

an outer if statement.

import java.util.Scanner;

class NumberTester{public static void main (String[] args){Scanner scan = new Scanner( System.in );int num;

System.out.println("Enter an integer:");num = scan.nextInt();

if ( num < 0 ){// true-branchSystem.out.println("The number " + num + " is negative");

}else{ if ( num > 0 ){// nested true-branchSystem.out.println("The number " + num + " is positive");

}

else{// nested false-branchSystem.out.println("The number " + num + " is zero");

}

}

System.out.println("Good-bye for now"); // always executed}

}

QUESTION 18:

Could an if statement be nested inside the true branch of another if statement?

Answer:

Yes. And you can have two nested if statements, one per branch.

Page 248: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 248/293

 

Last Page

This is the end of the chapter.

If you want,

review the following topics;else,go on to the next chapter.

•  Two-way decisions. • Outline of a Two-way decision. • Statement blocks. • Boolean Expressions. •  Table of Relational Operators. 

You have reached the end of the chapter.

CHAPTER 25 — Objects

Chapter Topics:

• What is an Object?• What is a Class?• Characteristics of Objects• Static Methods• Constructors• Cookie Cutters

• Dot Notation

Until now, we have not been doing much with objects. This chapter discusses objects andclasses.

Forget programming for a while. Think about the Real World and the things that are in it. Whatthings are objects? What things are not objects? This is actually a difficult problem which hasoccupied philosophers for thousands of years. Don't be too worried if it is not immediately clear to you.

QUESTION 1:

Look around you. List four objects and list four non-objects.

Objec

ts

Non-

objects

Page 249: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 249/293

 

1

2

3

4

Answer:

Objects Non-objects

1 A penThe upper 37% of the

pen

2A computer

keyboard

The air above the

keyboard

3 A shoe The color of the shoe

4 A mouseThe sound of a mouse

click

What Makes an Object?

It is easier to list things that are objects than to list things that are not objects. Just to talk about

something seems to make it an object, somehow. René Descartes (the 17th century philosopher)observed that humans view the world in object-oriented terms. The human brain wants to think about objects, and our thoughts and memories are organized into objects and their relationships.Perhaps non-human brains work differently.

One of the ideas of object-oriented software is to organize software in a way that matches thethinking style of our object-oriented brains. Instead of machine instructions that change bit patterns in main storage, we want "things" that "do something." Of course, at the machine levelnothing has changed—bit patterns are being manipulated by machine instructions. But we don'thave to think that way.

QUESTION 2:

Look at my list of objects and your own list and try to describe what all objects have in common.

What makes an object?

Page 250: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 250/293

 

Answer:

Here is my unofficial list:

• An object is made of tangible material (the pen is made of plastic, metal, ink).•

An object holds together as a single whole (the whole pen, not a fog).• An object has properties (the color of the pen, where it is, how thick it

writes...).• An object can do things and can have things done to it.

Characteristics of Objects

The first item in this list is too restrictive. For example, you can think of your bank account as an

object, but it is not made of material. (Although you and the bank may use paper and other material in keeping track of your account, your account exists independently of this material.)Although it is not material, your account has properties (a balance, an interest rate, an owner)and you can do things to it (deposit money, cancel it) and it can do things (charge for transactions, accumulate interest).

The last three items on the list seem clear enough. In fact, they have names:

• An object has identity (each object is a distinct individual).• An object has state (it has various properties, which might change).• An object has behavior (it can do things and can have things done to it).

This is a somewhat ordinary description of what an object is like. (This list comes from the book Object-oriented Analysis and Design, by Grady Booch, Addison-Wesley, 1994.) Do not besurprised if other notes and books have a different list. When you start writing object-orientedsoftware you will find that this list will help you decide what your objects should be.

QUESTION 3:

Page 251: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 251/293

 

Consider a tube of four yellow tennis balls.

• Is the tube of tennis balls an object?• Is each tennis ball an object?• Could the top two balls be considered a single object?• Is the color of the balls an object?• Is your understanding of tennis balls an object?

Answer:

• Is the tube of tennis balls an object?o  Yes. It has identity (my tube of balls is different than yours), it has

state (opened, unopened, brand name, location), and behavior(although not much).

• Is each tennis ball an object?o  Yes. It is OK for objects to be part of other objects. Although each ball

has nearly the same state and behavior as the others, each has its own

identity.• Could the top two balls be considered a single object?

o Not ordinarily. Each has its own identity independent of the other. If they were joined together with a stick you might consider them as oneobject.

• Is the color of the balls an object?o No. It is a property of each ball.

• Is your understanding of tennis balls an object?o Probably not, although it is unclear what it is. Perhaps it is a property

of the object called "your brain."

Software Objects

Many programs are written to do things that are concerned with the real world. It is convenient tohave "software objects" that are similar to "real world objects". This makes the program andwhat it does easier to think about. Software objects have identity, state, and behavior just as doreal world objects. Of course, software objects exist entirely within a computer system and don'tdirectly interact with real world objects.

QUESTION 4:

What are software objects made out of?

What are software objects made out of?

Page 252: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 252/293

 

Answer:

Computer memory.

Software Objects as Memory

It is only a slight exaggeration to say that memory (both main memory and secondary memory)is what a computer is about. The rest of the electronics—the processor chip, the buses, the power supply, the keyboard, the video card and so on—exist only to work on memory and to show whatit contains. So what else could a software object be but a chunk of memory?

(Actually, it is not quite correct to claim that a software object is a "chunk" of memory. Asoftware object is somewhat like a bank account—its existence is spread out and does not

correspond one-to-one with any particular piece of material. But for now it is convenient andreasonably accurate to think of a software object as a chunk of memory.)

Objects (real world and software) have identity, state, and behavior .

Software objects have identity. Each is a distinct chunk of memory. (Just like a yellow tennis ball, each software object is a distinct individual even though it may look nearly the same asother objects of the same type.)

Software objects have state. Some of the memory that makes up a software object is used for variables which contain values. These values are the state of the object.

Software objects have behavior. Some of the memory that makes up a software object contains programs (called methods) that enable the object to "do things". The object does something whenone of its method runs.

QUESTION 5:

(Review) What is the defining characteristic of the type of computer called a von Neumanncomputer (the type of nearly all current computers)?

Answer:

A von Neumann computer uses general purpose memory to store both programs and data.

Page 253: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 253/293

 

Picture of an Object

In terms of object-oriented programming, a von Neumann computer uses general purposememory to store both the state and behavior of objects. It is interesting that an idea from the

1940's is still important.

A software object consists of both variables (state information) and methods (recipes for  behavior). In the picture, the yellow bricks represent bytes of memory out of which the object is built. This object has some variables, location, color, and size, and has some methods that

control its behavior.

In object-oriented programming, the programmer uses a programming language (such as Java) todescribe various objects. When the program is run (after being compiled) the objects are created(out of main storage) and they start "doing things" by running their methods.

The methods must execute in the correct order. For an application, the first method to run is themethod named main(). There should be only one method named main() in an application. In a

small application, main() might do by itself all the computation that needs to be done. In a larger 

application, main() will create objects and use their methods.

Page 254: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 254/293

 

QUESTION 6:

Have you seen a main() method before?

Answer:

Every application so far in these notes starts with

public static void main ( String[] args )

This identifies the main method in the class.

Class

When a Java application is run, objects are created and their methods are invoked (are run). Tocreate an object, you need a description of it.

A class is a description of a kind of object. A programmer may define a class using

 Java, or may use predefined classes that come in class libraries.

A class is merely a plan for a possible object. It does not by itself create any objects. When a programmer wants to create an object the new operator is used with the name of the class.

Creating an object is called instantiation.

Here is a tiny application that instantiates an object by following the plan in the class String:

class StringTester{

public static void main ( String[] args ){String str1; // str1 is a variable that may refer to an object.

// The object does not exist unit the "new" is executed.int len; // len is a primitive variable of type int

str1 = new String("Random Jottings"); // create an object of type String 

len = str1.length(); // invoke the object's method length()

System.out.println("The string is " + len + " characters long");}

}

Page 255: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 255/293

 

When it is executed, the line

str1 = new String("Random Jottings");

creates an object by following the description in class String. The class String is defined in the

class library java.lang that comes with the Java system. The computer system finds a chunk of memory for the object, lays out this memory according to the plan (the definition of String),

and puts data and methods into it.

The data in this String object are the characters "Random Jottings" and the methods are themethods that all String objects have. One of these methods is length().

The variable str1 is used to refer to this object. In other words, str1 gives the object a name.

QUESTION 7:

If a program has a name for an object, does that mean that an object really exists?

Answer:

 No. Just because there is a name for an object does not mean an object exists.

Objects and Names for Objectsclass StringTester{

public static void main ( String[] args ){String str1; // str1 is a variable that may refer to an object.

// The object does not exist unit the "new" is executed.int len; // len is a primitive variable of type int

  str1 = new String("Random Jottings"); // create an object of type String 

len =str1

.length(); // invoke the object's method length()

System.out.println("The string is " + len + " characters long");}

}

A variable that can refer to an object does not always have an object to refer to. For example, inour program the variable str1 refers to an object only after the new operator has created one.

Page 256: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 256/293

 

Before the new operator does its work, str1 is a "place holder" that does not yet refer to any

object. After the new operator creates the object, str1 refers to that object.

This is similar to how names and objects work with real world things. I could speak of my dog"Rex" (a name for an object). Sadly, there is no such actual object. However, I could go to the

dog pound and bring home a new dog (instantiating an object) and now "Rex" refers to thatobject.

QUESTION 8:

What object is referred to in the statement:

len = str1.length(); // invoke the object's method length()

What object is referred to in the statement:

len = str1.length(); // invoke the object's method length()

Answer:

This statement occurs in the program after the object has been created, so str1 refers to that

object.

Using a Reference to an Object

class StringTester{

public static void main ( String[] args ){String str1; // str1 is a variable that refers to an object,

// but the object does not exist yet.int len; // len is a primitive variable of type int

str1 = new String("Random Jottings"); // create an object of type String 

len = str1.length(); // invoke the object's method length()

System.out.println("The string is " + len + " characters long");}

}

Page 257: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 257/293

 

Once the object has been created (with the new operator), the variable str1 refers to an actual

object. That object has several methods, one of them the length() method. A String object's

length() method counts the characters in the string.

QUESTION 9:

What is printed to the monitor by the above program?

Answer:The string is 15 characters long

Invoking an Object's Method

An object consists of both variables (state information) and methods (small programs). Both of these are called members of the object. Java uses dot notation for both:

referenceToAnObject.memberOfObject

For example, to invoke the length() method of the object named str1 do this:

str1.length();

To store the value computed by the length method in a variable, do this:

len = str1.length();

Method names have () at their end. Often there is additional information inside the (), but they

are required even if they contain nothing.

Page 258: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 258/293

 

QUESTION 10:

(Thought Question:) Is it possible for a program to have several objects all of the same class?

Answer:

Yes. A class is a description of a potential object. It can be used many times to make manyobjects of the same type.

Use a Class to Make Many Objects

A class is like a cookie cutter that can be used many times to make many cookies. There is onlyone cookie cutter, but can be used to make many cookies. Cookies are objects and each one hasits own individuality because each one is made out of a different section of dough. Differentcookies may have different characteristics, even though they follow the same basic pattern. For 

Page 259: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 259/293

 

example, cookies may have candy sprinkles or frosting, or may be baked for different lengths of time.

Cookies can be created. And cookies can be destroyed (just ask Cookie Monster). But destroyingcookies does not affect the cookie cutter. It can be used again if there is dough left.

A big cookie jar might require many cookies made with many different cookie patterns (stars,hearts, squares). A big cookie (such as a gingerbread house) might be built out of many smaller cookies of several different types.

QUESTION 11:

(Thought question:) Cookies in the real world are objects, of course. But real world cookiecutters are objects too. Do you think that a Java class has an object-like nature, just as does a

cookie cutter?

Answer:

Yes. In order for a plan to be followed, it has to somehow exist.

Static

Classes are mostly used to create objects, just as a cookie cutter is mostly used to create cookies.But a class has an existence, just as a cookie cutter has an existence. A class and its objects aredifferent types of things, just as a cookie cutter and its cookies are different types of things.

A cookie cutter has characteristics that are not shared with cookies. For example, a cookie cutter is made of steel and has sharp edges. It is not good to eat.

After a cookie cutter has been used for a while, there will be many cookies (soft, rounded,doughy things) but only one thing made of steel with sharp edges.

In the Java language, a characteristic of a class definition that is not shared by its objects is called

static. There is only one class definition for a given class, so when a program is running, if something is static then there is only one of it.

You can think of the word static as meaning "no matter how many objects have been made,

there is only one of these."

Page 260: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 260/293

 

QUESTION 12:

Recall the three properties of objects: identity, state, and behavior . Do you expect that a classdefinition has its own state and behavior?

Answer:

Yes. A class definition may have its own variables (state), and may have its own methods(behavior)

// The file StringTester.java//class StringTester{

public static void main ( String[] args ){String str1; // str1 is a reference to an object,int len; // len is a primitive variable of type int

str1 = new String("Random Jottings"); // create an object of type String 

len = str1.length(); // invoke the object's method length()

System.out.println("The string is " + len + " characters long");}

}

The methods that belong to a class definition are called static methods. (Sometimes they arecalled class methods, but this is confusing.) A static method is part of a class definition, but is

not part of the objects it creates.

Important:  A program can execute a static method without first creating an

object! All other methods (those that are not static) exits only when they are part of 

an object. So an object must be created before they can be executed.

The example application is similar to many you have seen so far. Now you can understand moredetails about what is going on. Assume that the source code is in a file namedStringTester.java.

•  The file defines a class called StringTester.

•  The class has a static method called main().• Since main() is a static method, it is a characteristic of the class. Objects of 

the class do not have a main() method.• Since main() is a static method, there will be only one main() method.

• After the file has been compiled, the resulting bytecodes are executed by the Java virtual machine.

o  The user executes the program by typing java StringTester.

Page 261: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 261/293

 

•  The Java virtual machine looks into the bytecode version of the classdefinition for the main() method.

o No object exists at this point.•  The main() method starts running, creates a String object using new, invokes

its length() method, and continues.

Remember the idea of object-oriented programming: an application consists of a collection of cooperating software objects whose methods are executed in a particular order to get somethinguseful done. The steps listed above is how the collection of objects gets started. (In this case onlyone object was created.)

QUESTION 13:

Say that you create a file that contains the definition of a class, but the the class contains nomain() method. Can the methods of this class ever be executed?

Answer:

 Not directly. But some other class which does have a main() method can use this class.

Constructors

class StringTester{

public static void main ( String[] args ){String str1; // str1 is a reference to an object.int len;

str1 = new String("Random Jottings"); // create an object of type String 

len = str1.length(); // invoke the object's method length()System.out.println("The string is " + len + " characters long");

}}

An object is a section of memory that contains variables and methods. A class is a description of a possible object. A class description is used when an object is created. The new operator is used

with a constructor to create an object.

A constructor has the same name as the class. The line from the above program

str1 = new String("Random Jottings");

Page 262: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 262/293

 

creates a new object of type String. The new operator says to create a new object. It is followed

 by the name of a constructor. The constructor String() is part of the definition for the class

String.

Constructors often are used with values (called parameters) that are to be stored in the data part

of the object that is created. In the above program, the characters "Random Jottings" (notincluding the quote marks) are stored in the new object.

There are usually several different constructors in a class, each with different parameters.Sometimes one is more convenient to use than another depending on how the new object's data isto be initialized. However, all the constructors of a class create the same type of object.

QUESTION 14:

(Thought question:) Could a constructor be used a second time to change the values of an objectit created?

Answer:

 No. A constructor is used once per object. Once an object has been created the constructor isfinished.

Dot NotationString str1; // str1 is a reference to an object.int len;str1 = new String("Random Jottings"); // create an object of type String len = str1.length(); // invoke the object's method length()

After an object has been constructed it can (usually) be changed by using its own methods (notits constructor). However, some objects are designed so that their data cannot be changed after the object has been constructed. The class String is one of these. String objects are immutable.

This means that after construction, they cannot be altered.

The variables and methods of an object are called the members of that object. The members of an object are accessed using dot notation.

The length() method is a member of the object created by the example. To run this method do

this:

len = str1.length();

Page 263: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 263/293

 

This assignment statement, as always, does its work in two steps:

1. The expression on the right of the = is evaluated.2. The resulting value is stored in the variable on the left of the = sign.

The right side of this particular assignment statement executes the method length() which ismember of the object referenced by str1. Executing this method returns the number of 

characters in the object.

QUESTION 15:

Do you think that the following is correct?

str1.length() = 12 ; // change the length of str1

Do you think that the following is correct?

str1.length() = 12 ; // change the length of str1

Answer:

 No. The left side of an assignment statement must be a variable.

Practice Programclass StringTester{

public static void main ( String[] args ){String str1; // a reference to a String object.String str2; // a reference to a second String object.

int len1, len2; // the length of str1 and the length of str2str1 =; // create the first Stringstr2 = ; // create the second String

len1 = str1.length(); // get the length of the first stringlen2 = . ; // get the length of the second stringSystem.out.println("The combined length of both strings is " + + "characters" );}}

It has been a long time since you have had some blanks to fill in. I'm sure that you miss them.Complete the above program so that it

Page 264: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 264/293

 

1. Creates two String objects.2. The first String holds the characters "Green eggs".3. The second String holds the characters " and ham".4. The program computes the length of each string, and then5. Writes out the the sum of the individual lengths.

QUESTION 16:

Fill in the blanks of the program. Here are some random jottings you may wish to paste into the blanks:

length()new String(" and ham.")str1str2( + )len1len2()"Green eggs"

Answer:

The completed program is given below.

Using a Constructor in a Declaration

class StringTester{

public static void main ( String[] args ){String str1; // str1 is a reference to a String object.String str2; // str2 is a reference to a second String object.

int len1, len2 ; // the length of str1 and the length of str2

str1 = new String( "Green eggs") ; // create the first String

str2 = new String( " and ham.") ; // create the second String

len1 = str1.length(); // get the length of the first string

len2 = str2 . length(); // get the length of the second string

System.out.println("The combined length of both strings is " +

Page 265: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 265/293

 

(len1 + len2) + " characters" );}

}

The above is a "wordy" version of the program. An object can be created in a variabledeclaration. For example the following creates a String object containing the designated

characters and puts a reference to the new object in the reference variable str1.

String str1 = new String("Green eggs");

Here is an even shorter way, that works only for String objects:

String str1 = "Green eggs";

This statement ensures that str1 refers to an object containing the designated characters.

However, if a "Green eggs" object already exists, no new object is created, but str1 is made to

refer to the already existing object.

This is an optimization. Often, the same sequence of characters is needed many placesthroughout a program, so it is efficient to use only one object.

QUESTION 17:

Inspect the following code. How many objects are there?

String prompt1 = "Press Enter to Continue."String prompt2 = "Press Enter to Continue."String prompt3 = "Press Enter to Continue."String prompt4 = "Press Enter to Continue."

Answer:

Just one object. All four reference variables point to the same object.

(In a sensible program, those four declarations might have been spread out over many lines.)

(The next chapter discusses this further, in case you are a little unhappy about this answer.)

End of the Chapter

You may wish to review the following. Click on a subject that interests you to go to where it wasdiscussed.

Page 266: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 266/293

 

•  Three characteristics of objects.• What software objects are made out of.• Members of an object.• von Neumann computers.• What a class is.• Cookie cutters and cookies•  The static modifier.• static methods• How the Java virtual machine starts a program up.• Constructors• Parameter• Dot notation.• Using a constructor in a variable declaration.

The next chapter discusses object references.

You have reached the end of the chapter.

CHAPTER 26 — Object References

This chapter discusses two things: object reference variables and the objects they refer to.These are crucial concepts in programming, and can be confusing. It demands careful study. Thischapter was written as my best effort to answer the questions of confused students.

Chapter Topics:

• Primitive data types, and objects• Object references and object reference variables• Copying object references•  The == operator and object references•  The equals() method for strings• String literals

You might wish to study this carefully, as a pre-emptive strike against confusion.

QUESTION 1:

(Review:) In Java, a piece of data either is of a _________________ data type or is an ________________ data type.

Answer:

(Review:) In Java, a piece of data either is of a primitive data type or is an object data type.

Page 267: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 267/293

 

Primitive Data Types and Classes

Chapter eight discusses the idea of a data type:

Computer memory stores bit patterns. A particular pattern has meaning only when

you know what type of value it represents, and what scheme is being used to

represent values with patterns. The scheme that is being used for a particular

section of memory is a data type. 

If these ideas have gotten fuzzy, you may wish to review chapter eight.

Java has many data types built into it, and you (as a programmer) can define as many more asyou need. Other than the primitive data types, all data types are classes. In other words, data iseither primitive data or object data. The only type of data a programmer can define is an objectdata type (a class). Every object in Java is an instance of a class. The class definition has to existfirst before an object can be constructed.

QUESTION 2:

(Review:) In the table decide on the classification for each data type.

Data

Type

Primiti

ve

Clas

s

int

String

long

double

Page 268: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 268/293

 

Applet

boolean

Scanner

Answer:

Data

Type

Primiti

ve

Clas

s

int X

String X

long X

double X

Applet X

boolean X

Scanner X

The correct way to do this is to recognize the primitive data types. Everything else must be aclass. Class names usually begin with a capital letter, but this is not required by syntax.

A Primitive Variable

Here is a tiny program that uses a primitive data type:

class EgLong{public static void main ( String[] args ){long value;

value = 18234;System.out.println( value );

Page 269: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 269/293

 

}}

In this program, the variable value is the name for a 64 bit section of memory that is used to

hold long integers. The statement

value = 18234;

 puts a particular bit pattern in that 64 bit section of memory.

With primitive data types, a variable is a section of memory reserved for a value that uses thatdata type. For example by saying long value, 64 bits of memory are reserved for an integer. By

saying int sum, 32 bits of memory are reserved an integer.

Object reference variables do not work this way, however. The next several pages will discussthis.

QUESTION 3:

(Thought Question:) Each primitive data type uses a fixed number of bits. For example, allvariables of type double are 64 bits long. Do you think that all objects of the same type are the

same size? Click here for a

Do you thing that all objects of the same type are the same size?

Answer:

 No. Objects are bigger and more complicated than primitive data types. It would be toorestrictive if all objects of the same type had to be the same size.

A String Object

Objects are big, complicated, and vary in size. You DO NOT automatically get an object whenyou declare an object reference variable. All you get is a place to put a future object reference.Examine the following:

class EgString{

public static void main ( String[] args ){String str;

 str = new String( "The Gingham Dog" );

System.out.println( str );}

}

Page 270: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 270/293

 

An object contains data and methods (state and behavior). You can visualize the String object

in the above program like this:

The data section of the object contains the characters. The methods section of the object containsmany methods. (Actually, this picture is a simplification. The Java system does something moreefficient, but logically equivalent.) Future diagrams sometimes will not show the methods of theobject.

QUESTION 4:

(Review:) What does the following new operator do?

str = new String( "The Gingham Dog" );str = new String( "The Gingham Dog" );

Answer:

The new operator creates an object using the constructor String(). 

Two Steps with an Assignment Operator

Review: Two steps take place when an assignment operator is executed:

1. The expression on the right of the = is evaluated.2. The result of evaluation is assigned to the variable on the left of the =.

When an object is constructed, these steps happen like this:

String str; // place to hold an object reference 

Page 271: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 271/293

 

str = new String( "The Gingham Dog" );--+-- ----------------+--------------| ||| 1. An object is created using the

constructor.| The Java system keeps track of| how to find the object (a reference to the

object).

2. A reference to the object is stored in the variable str.

There are three things involved in this statement: the object, a reference to the object, and thevariable.

QUESTION 5:

Say that you have a business card with your name on it.

Are the business card, your name, and the actual you different things?

Are a variable, a reference, and an object different things?

Answer:

Are a business card, your name, and the actual you different things? — Yes

Are a variable, a reference, and an object different things? — Yes

Object Reference

An object is constructed out a chunk of main memory and hence has a unique location. Anobject reference describes the location in memory of a particular object. In the picture, thevariable str contains a reference to the object.

Page 272: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 272/293

 

Objects are created while a program is running. When an object reference is assigned to avariable, then that variable says how to find that object in memory.

In diagrams, an object reference is shown as an arrow from the object reference variable to theobject. (An object reference is actually a complicated bit pattern.)

QUESTION 6:

What does a variable of a primitive type contain?

Answer:

A variable of a primitive type contains the actual data, not information on where the data is.

Two Kinds of Variables

An object reference does not contain the actual data, just a way to find it. There are two kinds of variables in Java:

Characteristics

primitive

variableContains the actual data.

reference

variable

Contains information on how to find the

object.

Here is the example program again:

Page 273: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 273/293

 

class EgString{

public static void main ( String[] args ){String str;

 str = new String( "The Gingham Dog" );

System.out.println( str );}

}

When the statement

System.out.println( str );

is executed, the reference in str is used to find the object and to get the data to be printed.

QUESTION 7:

Does using str in the above statement change the information it contains?

Does using str in the above statement change the information in it?

Answer:

 No. Using the information does not change it. This is the same as with a primitive variable: usingit in an arithmetic expression does not change its information.

Larger Example

Here is a slightly larger version of the example program, now with a new variable of a primitivetype:

class EgString2{

public static void main ( String[] args ){

String str;long value; 

str = new String( "The Gingham Dog" );value = 32912;

System.out.println( str );System.out.println( value );

}}

Page 274: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 274/293

 

When the statement

str = new String( "The Gingham Dog" );

is executed, a new object is created and a reference to it is placed in str.

QUESTION 8:

What happens when the statement

value = 32912;

is executed?

Answer:

When

value = 32912;

is executed nothing new is created. A bit pattern representing 32912 is stored in value.

Two Types of Assignment Statements

There is a difference between the statements:

value = 32912;

and

str = new String( "The Gingham Dog" );

In the first statement, value is a primitive type, so the assigment statement puts the data directly

into it. In the second statement, str is an object reference variable (the only other possibility) so

a reference to the object is put into that variable.

Important: A Java variable never contains an object.

There are only primitive variables and object reference variables, and each contains a specifickind of information:

Information it Contains When on the left of =

Page 275: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 275/293

 

primitive

variableContains actual data.

Previous data is replaced

with new data.

referencevariable

Contains information on how to findan object (a reference).

Old reference is replacedwith a new reference

How do you tell the two kinds of variables apart? Easy: look at how the variable is declared.Unless it was declared to be of a primitive type, it is an object reference variable. A variable willnot change its declared type.

QUESTION 9:

How are the following variables declared? Click on the button of your choice.

Declaratio

n

Primiti

ve

Object

Reference

int foo;

String st;

booleanflag;

Scanner

scan;

Answer:

Declaratio

n

Primiti

ve

Object

Reference

int foo; X

String st; X

Page 276: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 276/293

 

boolean

flag;X

Scanner

scan;

X

Two Types of Use

Look at the example program again. When the statement

System.out.println( str );

is executed, the object referred to by str is found and its data is written to the monitor. When the

statement

System.out.println( value );

is executed, the primitive value in the variable value is used directly. (It is translated into

character form and written to the monitor.)

There are two kinds of variables. When used in an expression (as above) they each behave in adifferent way:

Characteristics When used in an expression:

primitive

variable

Fixed number of bits. Contains

the actual data.Use the data in the variable.

reference

variable

Contains information on how

to find the object.

Use the reference in the variable

to find the object.

When you declare a variable, you say what type it is. For example:

String str;

says that str is a reference variable expected to (later on) contain a reference to an object of type

String. The declaration

Page 277: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 277/293

 

long value;

says that value is a variable containing the primitive data type long. When you compile a

 program, the declarations tell the compiler what style of information is kept in each variable, sothe compiler uses each variable in the appropriate way every time it is mentioned in your 

 program.

QUESTION 10:

Say that the following statement were put into the previous example program. Would it becorrect?

str = value ;

Answer:

 No. The statement

str = value ;

is (apparently) asking that the primitive data type contained in value be placed in the reference

variable str. This cannot be done.

Two Objects

Here is a further modification of the example program:

class EgString3{public static void main ( String[] args ){String str;

 str = new String("The Gingham Dog");System.out.println(str);

str = new String("The Calico Cat");System.out.println(str);

}}

The program does exactly what you would expect. It writes out:

The Gingham DogThe Calico Cat

QUESTION 11:

How many objects were created by the program?

Page 278: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 278/293

 

How many reference variables does the program contain?

Answer:

How many objects were created by the program?

TWO, one for the dog, one for the cat.

How many reference variables does the program contain?

ONE, which first refers to the dog, then refers to the cat.

Reference Variable Reused

Let us look at some of the details involved in doing this. Here is the program, again:

class EgString3{public static void main ( String[] args ){String str;

 str = new String("The Gingham Dog");System.out.println(str);

str = new String("The Calico Cat");System.out.println(str);

}

}

Here is a diagram that shows the one reference variable str and the two objects. The variable

can refer to only one object at a time. It first refers to the dog object, and then to the cat object.

Here are some details about how the reference variable and the two objects relate:

Page 279: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 279/293

 

Statement Action

str = new String("The Gingham

Dog");

Create the FIRST object.

Put a reference to this object into str 

System.out.println(str); Follow the reference in str to the FIRST object.

Get the data in it and print it.

str = new String("The Calico

Cat");

Create a SECOND object.

Put a reference to the SECOND object into str.

At this point, there is no reference to the first

object. It is now "garbage."

System.out.println(str); 

Follow the reference in str to the SECOND

object.Get the data in it and print it.

 

QUESTION 12:

(Look at the picture:) When "The Calico Cat" is constructed, what happens to the reference to"The Gingham Dog"?

Answer:

When a new reference is assigned to str it replaces the previous reference.

Garbage

Details of the action:

1. Each time the new operator is used, a new object is created.2. Each time an object is created, a reference to it is created.3. Each object that exists in a computer system has a unique reference.4. This reference is usually saved in a variable.5. The reference in the variable can be used to find the object.6. If another reference is saved in the variable, it replaces the previous

reference.7. If no variables refer to an object, there is no way to find it, and it becomes

garbage.

Page 280: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 280/293

 

The word garbage is the correct term for objects that are not refered to by any referencevariable. Since they cannot be found by the program, there is no reason for them to exist. Thissituation is common and not usually a mistake. As a program executes, objects are created. Thenwhen they are no longer needed references to them are discarded. However, a part of the Javasystem called the garbage collector reclaims the lost objects so that the memory they are made

of can be used again.

QUESTION 13:

Can several objects of the same class exist in a program at the same time?

Can several objects of the same class exist in a program at the same time?

Answer:

Yes. Of course, to locate each one, each must have a reference.

Several Objects of the same Class

Here is another version of the example program:

class EgString4{public static void main ( String[] args ){String strA; // reference to the first objectString strB; // reference to the second object

  strA = new String( "The Gingham Dog" ); // create the first objectand

// Save its reference.

System.out.println( strA ); // follow reference to first// object and print its data.

strB = new String( "The Calico Cat" ); // create the second objectand

// Save its reference.

System.out.println( strB ); // follow reference to second// object and print its

data.

System.out.println( strA ); // follow reference to first// object and print its

data. 

}}

Page 281: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 281/293

 

This program has TWO reference variables, strA and strB. It creates two objects and places

each reference in one of the variables. Since each object has its own reference variable, noreference is lost, and no objects become garbage (until the program has finished running).

QUESTION 14:

What will this program print to the monitor?

Answer:

The program will print:

The Gingham DogThe Calico CatThe Gingham Dog

Picture of Two Objects and Two ReferenceVariables

Here is a picture of the two objects and of the two reference variables. Each arrow represents areference.

QUESTION 15:

(Dumb question, but answer it anyway:) How many objects are there in this picture? How manyreference variables are there in this picture?

Page 282: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 282/293

 

Answer:

There are two objects, each with a unique reference. There are two reference variables, eachcontaining a different reference.

Equality of ReferencesThe == operator looks at the contents of two reference variables. If both reference variables

contain the same reference, then the result is true. Otherwise the result is false. Since objectreferences are unique, the == operator returns true if two reference variables refer to the same

object.

The == operator does  NOT look at objects! It only looks at references (information about where

an object is located).

Here is a section from the previous program, with an additional if statement:

String strA; // reference to the first objectString strB; // reference to the second object

 strA = new String( "The Gingham Dog" ); // create the first object

and// save its reference

System.out.println( strA );

strB = new String( "The Calico Cat" ); // create the second objectand

// save its reference

System.out.println( strB );

if ( strA == strB )System.out.println( "This will not print.")

Since the reference in strA is different than the reference in strB,

strA == strB

is false. (Look at the picture on the previous page.) The third println() statement will not

execute.

QUESTION 16:

Did the == operator look at the contents of the objects when the if statement executed?

Did the == operator look at the contents of the objects when the if statement executed?

Page 283: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 283/293

 

Answer:

 No. It only looked at the two reference variables. They held different references, so the ==

evaluated to false.

Two Reference Variables Pointing to OneObject.

Here is another example program:

class EgString5{public static void main ( String[] args ){String strA; // reference to the object

String strB; // another reference to the object 

strA = new String( "The Gingham Dog" ); // Create the only object.// Save its reference in strA.

System.out.println( strA );

strB = strA; // Copy the reference into strB.

System.out.println( strB );

if ( strA == strB )System.out.println( "Same info in each reference variable." );

}}

When this program runs, only one object is created (by the new). The unique reference to the

object is put into strA. Then the statement

strB = strA; // Copy the reference to strB.

copies the reference that is in strA into strB. It does not make a copy of the object!

Or, saying nearly the same thing: making a copy of a reference to an object does not make a copyof the object! The same information is stored in strA and strB. Both variables refer to the same

object. This is somewhat like giving your phone number to several people: each copy of your  phone number is a reference to you, but there is only one you. The program will output:

The Gingham DogThe Gingham DogSame info in each reference variable.

Page 284: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 284/293

 

QUESTION 17:

How many objects are there in this program? How many reference variables are there?

How many objects are there in this program? How many reference variables are there?

Answer:

There is one object (after the new operator has worked) and there are two reference variables.

Picture of One Objects and Two Reference

Variables

Here is a picture showing the situation in the new program:

 Now when the expression strA == strB is evaluated, it is true because the contents of strA and

of strB are the same (they both contain the same reference).

String strA; // will contain the reference to the objectString strB; // another copy of the reference to the object

 strA = new String( "The Gingham Dog" );System.out.println( strA );

strB = strA;System.out.println( strB );

if ( strA == strB )System.out.println( "Same info in each reference variable." );

When two reference variables refer to the same object, the == operator will evaluate to true. 

Page 285: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 285/293

 

QUESTION 18:

In the new program, did the == operator look at the contents of the object?

In the new program, did the == operator look at the contents of the object?

Answer:

 No. The == operator looks only at the variables.

== Looks only at Variables

For primitive types, also, the == operator looks only at the variables. For example:

int x = 32;

int y = 48;

if ( x == y ) System.out.println("They are equal.");

Only the contents of the variables x and y are examined. But with primitive types, the contents of 

a variable is the data, so with primitive types == looks at data.

With reference types, == looks at the contents of the variables, but now the variables contain

object references.

QUESTION 19:

(Thought Question: ) Could two different objects contain equivalent data?

Could two different objects contain equivalent data?

Answer:

Yes. The objects would be constructed out of different bytes in memory, but would containequivalent values.

Two Objects with Equivalent ContentsRecall that objects have identity, state, and behavior. "Identity" means that each object is aunique entity, no matter how similar it is to another. Here is a program that shows this situation:

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

Page 286: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 286/293

 

String strA; // reference to the first objectString strB; // reference to the second object

 strA = new String( "The Gingham Dog" ); // create the first object.

// Save its referenceSystem.out.println( strA );

strB = new String( "The Gingham Dog" ); // create the second object.// Save its reference

System.out.println( strB );

if ( strA == strB )System.out.println( "This will not print.");

}

}

In this program, there are two objects, each a unique entity. Each object happens to contain dataequivalent to that in the other. Each object consists of a section of main memory separate from

the memory that makes up the other object. The variable strA contains a reference to the firstobject, and the variable strB contains a reference to the second object.

Since the information in strA is different from the information in strB,

( strA == strB )

is false, just as it was in a previous program where there were two objects. Since there are twoobjects, made out of two separate sections of main memory, the reference stored in strA is

different from the reference in strB. It doesn't matter that the data inside the objects looks the

same.

QUESTION 20:

What will this example program print to the monitor?

Answer:The Gingham DogThe Gingham Dog

Picture of Equivalent Data

Here is a picture of this situation. Even though both objects have equivalent data inside of them,(strA == strB) is false.

Page 287: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 287/293

 

== reports false because there are two different objects, each with a unique reference.

QUESTION 21:

Imagine that there are three reference variables: itemA, itemB, itemC. And say that

itemA == itemB 

and that

itemB == itemC

.

How many objects are there?

Say that itemA == itemB and that itemB == itemC. How many objects are there?

Answer:

Just one object (and three reference variables, each referring to it.)

Page 288: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 288/293

 

The equals() Method

The equals( String ) method of class String tests if two Strings contain the same

characters.

The equals( String ) method looks at objects. It detects equivalence. The == operator detects

identity. For example,

String strA; // firstobjectString strB; // secondobject strA = new String( "TheGingham Dog" );

strB = new String( "TheGingham Dog" );

// check for equivalenceif( strA.equals( strB ) )System.out.println( "This

 WILL print.");

// check for identityif ( strA == strB )System.out.println( "This

will NOT print.");

In this example, there are two objects. Each object has its own identity, and its own uniquereference, so == returns false. Each object contains equivalent data, so equals() returns true.

QUESTION 22:

If you made a photocopy of a sheet of paper, you would have two sheets of paper.

Page 289: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 289/293

 

1. Are the sheets of paper separatate objects?2. Is the first sheet == the second sheet?3. Is the data on each sheet the same as on the other?4. Is the first sheet equals() to the second sheet?

If you made a photocopy of a sheet of paper, you would have two sheets of paper.

Answer:

1. Are the sheets of paper separatate objects? Yes; each object has its ownidentity.

2. Is the first sheet == the second sheet? No; they are separate objects.3. Is the data on each sheet the same as on the other?

 Yes; the data on the second sheet is a copy of the data on the first.

4. Is the first sheet equals() to the second sheet? Yes; the data on both sheets

is equivalent.

String Literals

Strings are common in programs, so Java optimizes their use. Usually if you need a string inyour program you create it as follows. Notice that new is not used:

String str = "String Literal" ;

This creates a string literal that contains the characters "String Literal". A string literal is an

object of class String. The compiler keeps track of the literals in your program and will reusethe same object when it can. (The compiler will not try to reuse other types of objects. Stringliterals are special.)

For example, say that a program contained the following statements:

String str1, str2;

str1 = "String Literal" ;str2 = "String Literal" ;

Only one object is created, containing the characters "String Literal". This is safe, because stringsare immutable, so the object str1 refers to will not change, and the object str2 refers to will not

change, so if the data is always the same, only one object is needed to contain it. There is noneed for two string objects whose content is identical.

Here is different situation:

String strA, strB;

Page 290: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 290/293

 

strA = new String("My String") ;strB = new String("My String") ;

 Now two objects are created, containing identical data. The compiler does not reuse the firstobject.

QUESTION 23:

How many objects are created by the following code:

String msg1, msg2, msg3;

msg1 = "Look Out!" ;

msg2 = "Look Out!" ;

msg3 = "Look Out!" ;String msg1, msg2, msg3;

msg1 = "Look Out!" ;msg2 = "Look Out!" ;msg3 = "Look Out!" ;

Answer:

Since these are identical string literals, only one object is created. The reference variables msg1,

msg2, and msg3 all refer to the same object.

Example Program

Here is an example program that shows this subtle difference.

class LiteralEg{public static void main ( String[] args ){String str1 = "String literal" ; // create a literalString str2 = "String literal" ; // str2 refers to the same literal

 String msgA = new String ("Look Out!"); // create an objectString msgB = new String ("Look Out!"); // create another object

 if ( str1 == str2 )

System.out.println( "This WILL print.");

if ( msgA == msgB )System.out.println( "This will NOT print.");

}

}

Page 291: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 291/293

 

Here is a picture of the program (after the first four statements have run):

As with many optimizations, you almost wish they hadn't done it. It does confuse things. Butreal-world programs often use the same message in many places (for example "yes" and "no")and it saves space and time to have only one copy. Only rarely will you need to think about thisdifference. However: I've read that the Sun Microsystems Java Certification Examinationstresses this difference.

But the difference between == and equals() is very important, and you will be sunk if you don't

know the difference.

QUESTION 24:

How would the program change if the second statement were changed to:

String str2 = "STRING LITERAL" ; // small difference

How would the program change if the second statement were changed to:

String str2 = "STRING LITERAL" ; // small difference

Answer:

 Now, since the second literal is not identical to the first, two literal string objects are created, andvariables str1 and str2 refer to different objects.

Two Strings that are == are always equal()

== determines if two variables refer to the same object. It is common in the real world (and in

 programs) for an object to have several names, for example "Mark Twain" and "Samuel

Clemens" are two names for the same author.

Page 292: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 292/293

 

Consider two strings:

String strA = new String ("The Gingham Dog");String strB = strA;

• Since there is only one object, strA == strB is true.• Since both reference variables point to an object with the same data,

strA.equals( strB ) is true.

If == is true, then so does equals().

QUESTION 25:

In the code that follows, will equals() report true or  false?

String lit1 = "String Literal" ;

String lit2 = "String Literal" ;

if ( lit1.equals( lit2 ) )System.out.println("TRUE");

elseSystem.out.println("FALSE");

String lit1 = "String Literal" ;String lit2 = "String Literal" ;if ( lit1.equals( lit2 ) )System.out.println("TRUE");elseSystem.out.println("FALSE");

Answer:

In this case there is only one object (a string literal) which both lit1 and lit2 refer to. So

equals() detects equivalent data and returns true.

Example Continued

Page 293: Introduction to Computer Systems

5/9/2018 Introduction to Computer Systems - slidepdf.com

http://slidepdf.com/reader/full/introduction-to-computer-systems-559bf56c9a02f 293/293

 

Here is the previous program with some more if statements:

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

String str1 = "String literal" ; // create a literalString str2 = "String literal" ; // str2 refers to the same literal

 String msgA = new String ("Look Out!"); // create an objectString msgB = new String ("Look Out!"); // create another object

 if ( str1 == str2 )System.out.println( "This WILL print.");

if ( str1 .equals( str2 ))System.out.println( "This WILL print.");

if ( msgA == msgB )System.out.println( "This will NOT print.");

if ( msgA .equals( msgB ))System.out.println( "This WILL print.");

}

}

QUESTION 26:

Say that you know that thing1.equals( thing2 ) is FALSE.

What can you then say about ( thing1 == thing2 ) ?


Recommended