You are on page 1of 157

Notes : CS101: Introduction to

Computer Science
by: Jessica Bone 3/23/15

CS101: Introduction to Computer Science 1


History of Computing 1.1
The first modern computer came into existence is the 1940s.
Man's quest to simplify mathematical computations has let to extensive research,
algorithm development and other innovations.
A computer is an electronic device that stores and processes data.
Hardware in a computer refers to the physical aspects of the computer and
comprises the following main components: central processing unit (CPU),
memory, storage devices (disks, Cd, and tapes). And input / output devices
(monitor, keyboards, mice and printers.)

The earliest device to keep track of calculations was an abacus. It was used
around 50 BC and was very popular in Asia.
John Napier, a Scottish Mathematician, Physicist and Astronomer definer natural
logarithms in 1614 to simplify calculations. The use of logarithms greatly
simplified the complex astronomical , navigational, mathematical and scientific
calculations that were common place at the time. He also invented Napier's bones
a mathematical tool that uses a set of numbered rods to simplified multiplication.
Charles Babbage, a British Mathematician and inventor first proposed the idea of
a programmable computer. Whiles studying complex astronomical calculations
that others had done by hand he found numerous mistakes. Which motivated him

to design a mechanical computer that could do these calculations without errors.


He designed the machine it was not built during his lifetime.
The need for programming came with the idea of making general purpose
hardware that could be used to carry our a variety of tasks.
Ada Lovelace, who was the world's first programmer, published a paper in which
she demonstrated how Babbage' s analytical engine could be programmed to
perform various computations.
A device called a punch card was used in the late 1800s to keep track of data
could be read by machines. Punch cards stored information in digital format,
which was represented at the time by specific series of holes in paper card stock.
Herman Hollerith applied the idea of representing information as holes in paper
cards to speed up the tabulation process in the 1890 US Census. Holleriths work
contributed to initial programming methods, and punch cards were used to
communicate with computers well into the 1970s.
In the late 1940s John Von Neumann introduced the idea of a computer
architecture based on stored programs. The key idea was to store both the data and
the program in memory. The idea behind storing programs in a memory was based
on the construction of these programs using a small set of generic operations.
This became know as Von Neumann Architecture in the field of computer science.
This was a major advance in computer design, because until this point computers
were programed by setting switched ans physically wiring the components;
storing programs in memory completely changed that. This was also the start of
machine language (a sequence of 0s and 1s.)
The first computer ENIAC (Electronic Numerical Integrator and Computer) was
built by the United States Army's Ballistic Research Laboratory in 1946. It was
part of the research aimes at providing better missiles to the U.S. Army during
WWII.
Dr. Presper Eckert and Dr. John Mauchly two members of the team that built
ENIAC, started their own company Universal Automatic Computer or UNIVAC
to build the first commercial computer. Their first client was the United States
Census Bureau, which needed a computer built to keep track of the growing U.S.
Population. The computer was successfully built in 1951 at the cost of about one
million dollars.

Figure 8: A layered structure showing where the operating system software and
application software are situated while running on a typical desktop computer.
During the 1950s and 1960s, several high-level programming languages were
introduced, such as FORTRAN, COBOL, Lisp, ALGOL, and PL/I. The 1970s saw
the introduction of languages such as Pascal, C, and Prolog. Most of these
languages such as Pascal, C, and FORTRAN are procedural programming
languages.
Procedural Programming is also referred to as imperative programming. The basic
idea of this programming style is to specify the steps that the program must take
to reach the desired state.
An exception to this style of programming comes from languages called Lisp and
Prolog. Lisp is a functional programming language, and Prolog is a logic
programming language.
In functional programming style, evaluation of mathematical style functions take
place and the state variables are not used.
In logical programing a program is expressed as a sequence of logical assertions
and these assertions are automatically evaluated to come up with the result. These
languages include a logic evaluation engine along with the compiler.
In the late 1970s, a new design approach called object-oriented programming
(OOP)
was developed. This programming technique has several advantages, and almost
all languages today follow this approach.
The 1980s saw the introduction of object-oriented programming language C++,
which was later followed by another OOP called Java in the 1990s.
Java has become a popular programming language for the development of mobile
and web based application.
The 1980s and 1990s also saw the introduction of scripting programming
languages such as Perl, Python and Rudy.
Prior to the introduction of personal computers, businesses utilized minicomputers
for
local computers, with users connected to the minicomputer remotely via
terminals. The

minicomputers were often connected via computer networks to enable distributed


systems software made up of components, located or distributed on the network
computers, which communicate via messages to achieve a common purpose.
The networks which began as local hard-wired networks grew rapidly by utilizing
telephone networks and eventually evolved to include wireless connections.
Computers entered American households in the 1980s. In 1975, Bill Gates and
Paul Allen co-founded Microsoft to create software for both businesses and
personal computers. As the first major project for the company, IBM asked
Microsoft to create operating system software for the personal computers that
IBM planned to build. Microsoft named this operating system MS-DOS and
released it as a product.
Although announced in 1983, the Windows operating system was not released
until 1987. It was not until the 1995 release of Windows 95 that Microsofts
software became a very popular operating system and one of the fastest-selling
pieces of software in the history of computing.
In 2001, Microsoft introduced Windows XP, with features like multi-lingual
support and a new, user-friendly interface. Released in 2006, Windows Vista
addressed security issues that many critics voiced for Windows XP and also
improved the accessibility of settings and programs. This was followed by
Windows 7, which supported mobile computing as wireless Internet access
became common. Now, with Windows 8, Microsoft has focused on touch-enabled
computing, which has become popular with devices such as smart phones and
tablets.
A web browser is a software program that allows users to easily browse the
contents of the World Wide Web. It was first created in 1989 by Tim Berners-Lee,
a British computer scientist, when he was working as a fellow at CERN. Marc
Andreessen, a student at the University of Illinois in Urbana Champaign, later
created a version of the browser in 1993, called Mosaic, which was much easier to
install and use.
The browser later formed the basis for the company Netscape, which popularized
the use of web browsers. Today, there are many browser options. The most
popular include Google Chrome, Mozilla Firefox, Microsoft Internet Explorer,
and Safari.
Founded in 1998, Google has become one of the most recognized technology
companies in the world due to its search engine, which is used to find information
on the Internet.
Googles search engine, as well as the companys other products, such as Gmail,
Google Maps, Google Books, and YouTube, are web browser-based software
applications.
There is a general trend towards using applications that do not run on your
computer but run on servers located elsewhere, also known as the cloud.

The computing resources being used are remote, and your machine mainly takes
up roles of display and communications with the remote entities. As devices
become more capable and more mobile, software development is catering to the
cloud computing paradigm more and more.
One of the enablers of cloud computing paradigm is a concept called virtual
machines.
A virtual machine is a program that creates a self-contained operating
environment on top of the underlying hardware and presents appearance of
different machines to the user. This allows the same piece of hardware to be used
as different machines at the same time.
You can create a Linux virtual machine on top of a Windows machine through the
use of virtual machine software such as Oracles VirtualBox and EMCs VMWare.
Today, mobile applications drive a lot of software development.
Released in 2007, Apples iOS, which was previously known as iPhone OS, is a
mobile operating system for the iPhone and iPod Touch devices.
the operating system functions for the iPad and the Apple TV, allowing for a
familiar interface across devices that ameliorates the users experience.
Another leading OS for smart phones and tablets is Googles Android OS, which
is Linux-based. Microsofts Windows 8 OS has also been designed to work with
phones and tablets. These operating systems have made the development of
mobile applications popular and spurred the creation of a large app-making
industry
Hardware vs Software 1.2.1
The word hardware is used for physical devices such as TV sets, DVD players
and computers. When talking about hardware mean the physical parts of a
computer. The hardware components of a computer system are the electronic and
mechanical parts, such as the processor, main memory, secondary memory, input
and output devices.
The word software is used for the information used with such devises: music,
movies, novels, web-pages, computer programs and data. Software means the
programs and data used with the physical computer. The software components of
a computer system are the data and the computer programs.
Main Components of a Computer System

The terms input and output say if data flow into or out of the computer.
A bus is a group of wires on the main circuit board of the computer. It is apathway
for data flowing between components. Most devices are connected to the bus
through a controller which coordinates the activities of the device with the bus.
The processor is an electronic device about a one inch square, covered in plastic,
Inside the square is an even smaller square of silicon containing millions of tiny
electrical parts. The processor is sometimes called the Central Processing Unit
(CPU).
A modern processor chip (in 2014) may have up to 2.5 billion transistors. The first
commercial chip 2.5 thousand transistors is 1971.
The processor performs all the fundamental computation of the computer system.
Other components contribute to the computation by doing such thins a storing
data or moving data into ans out the processor. The processor is where the
fundamental action takes place.
The processor chip has relatively little memory . If has only enough memory to
hold a few instructions of a program and the data they process. Complete
programs and data sets are held in memory external to the processor.
There is two fundamental types of memory, main and secondary.
Main memory is sometimes called volatile because it looses its information when
power is removed. Main memory is sometimes called main storage. Main memory
is closest connected to the processor, stored data are quickly and easily changed;
holds the programs and data that the processor is actively working with; interacts
with the processor millions of times per second; needs constant electrical power to
keep its information. Main memory is sometimes called RAM (Random Access
Memory) which mean the memory cells can be accessed in any order. Properly
speaking RAM means the type of silicon chip used to implement main memory.
One megabyte of memory is enough to hole approximately one million (106)
characters of a word processing document. Primary memory is fast, ecpensice,
low capacity, works directly with the processor.

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.) Secondary memory is sometimes called secondary
storage or mass storage. Secondary memory is connected to main memory
through the bus and a controller; stored data are easily changed but changes are
slow compared to main memory; used for long tern storage of programs and data.;
before data and programs can be used, they must me copied form the secondary
memory into main memory; doe not need electric power to keep its information.
Secondary memory is where programs and data are kept on a long-tern basis.
Secondary storage devices are the hard disk and optical disks. Hard disk has a
enormous storage capacity compared to main memory; usually contained inside
the case of the computer; is used for long-tern storage of programs and data; data
and programs o the hard disk are organized into files; a file collection of data on
the disk that has a name; hard disk storage capacity of 500 gigabytes (room for
about 500 x 109 characters) is about 100 times the capacity of main memory.
Secondary memory is slow, cheap, arge capacity, not connected directly to the
processor.
The reason for having to types of storage is this difference in speed and capacity.
It the disk were the only type of memory the computer system would slow down
to a crawl.
Large blacks of data are copied form disk into main memory. The operation is
slow but slow, but lots of data is copied, the the processor can quickly read and
wirte small sections of the data in main memory.
Input and output devices allow the computer system to interact with the outside
world byt moving data into and out of the system.
An input device is used to bring data into the system. Some input devices include
keyboard, mouse, microphone, bar code reader, graphics tablet.
Out put devices is used to send data out of the system. Some output devices
include the monitor, printer and speaker.
A network interface acts as both input and output; data flows from the network
into the computer and out of the computer into the network.
Input/output devices are usually called I/O devices. The are directly connected to
electronic module attached to the motherboard called a device controller. Example
of this the speakers of a multimedia computer system are directly connected to a
device controller card an audio card, which in turn is plugged into a bus on the
motherboard. Some motherboards have audio, graphics and network controllers
built in. What counts as a I/O device depends on the context.
A computer that is part of a larger machine and which controls how that machine
operates is an embedded system. Usually the processor constantly runs a single
control program which is permanently kept in ROM (Read Only Memory).
Rom is used to make a section of main memory read only. Main memory looks

the same as before to the processor, except a section of it permanently contains the
program the processor is running. This section of memory retains its data even
when power is off. A typically embedded system includes cellphone, car, digital
camera, DVD player, meical equipment and home appliances. Majority of
processor chips are used in embedded systems, less than 1% of processor chips
are used in the familiar desktop computer.
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.
Both programs and data are saved in computer memory in the same way. The
electronics of computer memory and secondary memory make no distinction
between programs and data. Both programs and data can be saved using the same
electronic methods is an important concept in computer science. Computer
systems use memory for wither programs or data as needed.
There are two categories of programs applications and system programs.
Application programs are programs that people use to get their work done.
Examples of application programs word processor, game programs, spreadsheets,
data base systems, graphics programs, and web browsers.
System programs keep the hardware and software running together smoothly. An
important system program is the operating system. Examples of system programs,
operating system, networking systems, programming language software, website
server, and data backup.
Operating System coordinates the operation of the other hardware and software
components of the computer system. The operating system is responsible for
stating up application programs, running them and managing the resources that
they need. Examples of operating systems are Unix, Linus, Android, Mac OS and
Windows. An operating system is a complex program that keeps the hardware and
software components of a computer system coordinated and functioning. Most
computer systems can potentially run any of several operating systems. For
example, most Pentium-based computers can run either Linux or a Windows
operating systems.
When a computer is first started, the hardware automatically loads the operating
system and starts it running. This process is called booting.
Here is a simplified list of what happens when the user starts up a application: 1.
the user asks to run a application ( 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 ans its
data are stored. 4. The OS finds an unused section of main memeory 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. ( the software on the hard disk is unchanged.

Main memory hols a copy 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 and output for the application, and keeping everything else running.
A computer network consists of two or more computers connected so that they
can exchange data and programs. When a computer is a member of a network, the
programs it runs and the data it uses can be on the hard disk of some other
computer on the network. The operating system that runs on a networked
computer must manage its share of the network (along with managing all its other
responsibilities).
In a local-area network only a few dozen computers are connected together,
usually all located within the same building. Each computer has a network address
that the other computers use to access 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 are expected to
need.
Each computer in a network has a network interface card. This is an input/output
device that sends and receives data over cables. The network interface cards of
computers on a network are connected together with cables.
A wide-area network can connect thousands of computers together over great
distances. 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.
An agreement about how to represent and transmit data over a network use a
protocol called TCP/IP ( fr transmission control protocol / internet protocol).
The internet consists of many networks that have been connected together to form
one huge worldwide network. Even on this huge network, each computer must
have a unique network address, called an ip address, much like each telephone in
the world has a unique telephone number I including the country code and area
code.)
IP addresses actually are 32-bit binary numbers.
Networking equipment uses these addressed to route information over the
network. But even when written in decimal the address is not clear to humans.
One of the features of the World Wide Web is that it allows humans to use
computer names rather than numbers.
This computer name corresponds to the above IP address. When you use it in a
web browser it is converted into the 32 binary digits of the computer's IP address.
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.

Communications equipment makes no distinction between programs and data,


either. It is all information as far as it is concerned, and all information is
transmitted the same way.
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. What makes Web data special is that it is intended for Web
browsers (such as the one you are probably looking at). A browser is a program
that can read Web pages and display them in a nicely formatted way. This
information is given using a language called Hypertext Markup Language
(HTML). If you want to see the HTML that describes this page, look at the menu
at the top of your Web browser, and select Tools/Web Developer/Page Source. For
older browsers, select View in the menu 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 its upper right corner (the
button marked with X).
One web page is connected to another with a hyperlink. A web browser usually
displays a hyperlink in a distinguishing color ( usually blue) . When you click 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 the exact computer (among all the interent computers in the world) an
the exact web oage on theat computer.
The Quiz On Computer Systems 1.2.1
1. What is the difference between hardware and software? Hardware is tangible, but
software is intangible.
2. What hardware components(of a typical desktop computer) are usually found
inside of the case? The processor, main memory and secondary memory
3. Which component does the actual computation of a computer system? The
processor chip
4. Which type of memory is most closely connected to the processor? Main memory
5. Where are programs and data kept while the processor is using them? Main
memory
6. What is an embedded system? A computer and software system that controls a
machine or appliance.
7. How is it possible that both programs and data can be store on the same floppy
disk? Programs and data are both software, and both can be stored on any
memory device.
8. What are the two general types of programs? System software and Application
software
9. What is an operating system?Systems software that coordinates the hardware and
software components of a computer system.

10.What is a computer network? Two or more computers connected together to


exchange data and programs.
Programs and Processes 1.2.2
Binary Numbers 1.2.2
decimal binary
(base 10) (base 2)
0 ones
0
0
1 one
1
1
1 two and zero ones
2
10
1 two and 1 one
3
11
1 four, 0 twos, and 0 ones
4
100
1 four, 0 twos, and 1 one
5
101
1 four, 1 two, and 0 ones
6
110
1 four, 1 two, and 1 one
7
111
1 eight, 0 fours, 0 twos, and 0 ones
8
1000
1 eight, 0 fours, 0 twos, and 1 one
9
1001
1 eight, 0 fours, 1 two, and 0 ones
10
1010
1 eight, 0 fours,1 two, and 1 one
11
1011
1 eight, 1 four, 0 twos, and 0 ones
12
1100
1 eight, 1 four, 0 twos, and 1 one
13
1101
1 eight, 1 four, 1 two, and 0 ones
14
1110
1 eight, 1 four, 1 two, and 1 one
15
1111
1 sixteen, 0 eights,0 fours, 0 twos, and 0
16
10000
ones
Binary / Decimal Conversion Quiz 1.2.2
1. Convert decimal 6 to a binary? 110
2. Convert decimal 14 to a binary? 1110
3. Convert decimal 239 to a binary? 11101111
4. Convert decimal 256 to a binary? 100000000
5. Convert decimal 1010 to a binary? 1111110010
6. Convert Binary 100 to a decimal? 4
7. Convert Binary 1011 to a decimal? 11
8. Convert Binary 101010 to a decimal? 42
9. Convert binary 10001000 to a decimal? 136
10.Convert binary 11001011 to a decimal? 203
The Processor 1.2.2
When a program is running on a computer the processor is constantly performing
very many tiny electronic operations. For example, one such operation reads one

byte of data from main memory into 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 thousand types of tiny operations like these, and can perform billions of
them per second.
The purpose of a high-level language like Java is to organize the tiny electronic
operations into large, useful units represented by program statements.
Users and programmers of computers usually don't think about the billions of tiny
electronic operations that go on each second. The situation is (very roughly)
similar to when you are driving your car. You think about the "big operations" it
can perform, such as "accelerate", "turn left", "brake", and so on. You don't think
about tiny operations, such as the valves in your engine opening 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 then in a second.
A machine instruction consists of several bytes in memory that tell the processor
to perfom one machine operation. The processor looks at machine instructions in
main memory one after another, and performs one machine operation for each
machine instructions. The collection of machine instructions in main memory is
called a machine language program or (more commonly) an executable program.
A typical processor has a thousand or more different machine instructions.
A machine language program is a sequence of machine language instructions in
main memory. A machine instruction consists of one or more bytes. The processor
runs a program one machine instruction at a time. All the little machine operations
ass up to something useful.
The word execute is often to mean perform the machine operation that an
instruction asks for. Execute is also used for an entire program or part of a
program: to execute the program turn the switch to on.
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 instructions per second. A program without loops would execute for only a
few seconds even if it had billions of instructions.
A typical processor is made up of millions of transistors on a small wafer of
silicon called an integrated circuit ( also called a chip). Integrated circuits are used
for other electronic parts of a computer. For example main memory is
implementer with memory chips.
Most modern processor ships have two or more processor on them. Each of the
processors on the ship is called a processor core of often just called a core.
Each core has the same set of tiny electronic operations and runs programs
independently of the other cores. When a program is running it runs on a single

core, which performs the tiny electronic operations of the program one at a time.
There are many types of processors used in computer systems. 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 one type of processor would make no sense to a different
processor type. All processor types have enough power in their little machine
operations to create the 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.
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 they
interacts with main memory and other components. Architecture is concerned
with the general plan and functions of a processor; it is not much concerned with
electronic details.
It is rare for programmers to write programs in machine language . The executable
files ( the directly runnable machine language programs) for most applications
contain hundreds of thousand of machine language instruction. Most programs
are created using a high level programming language such as Java, C, C++ or
Basic. With a high level language a programer creates a program using powerful,
bit operations which will later be converted into many little machine operations.
The machine operations that correspond to this big operation set up a part of main
memory to hold a number store the numbers zero there and arrange things so
other parts of the program can use it.
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 programs is also called a source file, source code or
sometimes just source. Source program is translated into a machine language
program. An application program called a translator 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
to sometimes just executable.
The word compile means the same thins as translate. So one can say that a source
program is compiled into a executable program.

The source program is created using a text editor. It contains instructions in a high
level language. It contains bytes that represent characters. The Source program is
kept on the hard disk. The source program can not be run by the processor.
The translator program translates the source program into an executable program.
The source program remains unchanged; a new executable program is created.
The executable program contains machine instructions. A translator translate from
a specific high level language (like C) into machine instructions for a specific
processor type. The executable program is also kept on hard disk.
The program is run by copying machine language from the executable program on
disk into main memory. The processor directly executes these machine language
instructions.
Once the source program has been translated into machine code ( the executable
program) the machine code can be directly executed by the processor. The source
program is only a means to create the machine code.
Ideally only one program needs to be written in the high level language. That
source field can then be translated into several executable files. Each containing
the correct machine instructions for its intended processor.
The idea of using one source file for executable programs that run on different
processors is called the software portability. You would like to write a program
just once ( in a high level language) and then run it on any computer system by
translating it into that systems machine language. Unfortunately thins do not
work out that nicely.
Programs written in a high level language are never directly executed by the
processor. You have already 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 use an interpreter for the language. An interpreter is an


executable program that runs directly on the processor. An interpreter reads
through a source program written in a high level language and performs the
actions that the source program asks for. 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 by one. Each time it reads in a command, the interpreter does what
the command asks. A BASIC command might ask to add two numbers together.
The BASIC interpreter is a program and programs can easily ass together two
numbers. The BASIC program might then ask to write the sum to the monitor.
The BASIC interpreter can easily do that. The BASIC interpreter works by
reading in commands of the BASIC source program one by one. Each time it
reads in a command the interpreter does what the command asks. A BASIC
command might ask to add two numbers together. The BASIC interpreter is a
program and programs can easily ass together two numbers. The BASIC program
might then ask to write the sum to the monitor. The BASIC interpreter uses the
fundamental machine operations of the processor to perform the actions requested
in the BASIC source program. But the source program itself is not translated into
machine language.
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 hardware can execute directly. The BASIC source program
consists of commands that the interpreter can perform. BASIC program, it looks
like the commands in BASIC are being directly executed by some sort of
machine. The combination looks like a machine that can directly execute BASIC
commands. It is as if BASIC commands are the machine language for
combination of processor and interpreter.
Virtual is used in situations where software has been used to make something look
like the real thing. In this case it looks like we have a machine that can directly
execute BASIC, so we can say that we have a BASIC virtual machine.
Translator: takes a complete document in one language and translates it into a
complete document in a second language, which can then be used by a reader of
the second language.
Interpreter:acts as an intermediate between a speaker of one language and a
speaker of another language. Usually an interpreter works one sentence at a time.
Immediately after a sentence is spoken in the first language, the translator
converts it into the second language.
The Quiz on Processor 1.2.2
1. What part of a computer system is most directly concerned with performing the
actions called for by a program? The processor

2. About how many different fundamental operations can most processors perform?
A few hundred
3. What is a machine operation? One of the tiny electronic operations that a
processor can perform.
4. What is a machine instruction? Several bytes in main memory that tells the
processor to perform one machine operation.
5. Which one of the following statements is False? Each machine instruction can be
used only once.
6. How many machine instructions can execute per second on a modern processor?
Millions of instructions per second
7. What is the architecture of a computer ? The choice of machine operstaions and
how they are implemented.
8. What is a source program?A text file created by a programmer containing
instructions written in a high level
9. What does a computer language compiler do? It takes a source file as input ans
produces an executable program as output
10. What is an interpreter? An interpreter is a program that acts like a processor that
can directly execute a high level language
The Software Development Cycle 1.2.3
Software goes through various stages from its conception to its end.
Through each takes a different approach, the various phases of the software
development process can be broadly summarized as follows: Planning and
Analysis; Designing ; Implementation; Testing and Debugging; Deployment and
Maintenance.
The first stage of software development is planning and analysis. In this stage a
requirement analysis is done, which includes finding out what the clients needs
are.
Once the requirements are gathered, the second and third phase of the software
development process begins. In these phases, a simple version of the program is
implemented using a programming language chosen by the team lead. As the
software
is written, it is tested and debugged to eliminate as many bugs as possible.
Once the software is tested and works according to specification, it is deployed
and
given to the client. In the maintenance stage, the software is enhanced and any
new found bugs are fixed. If there are new requirements at this stage they can be
added.
One can add additional features and repeat the steps of implementation, testing,
and

deployment as often as required.


There are several software development models that are used in the industry.
In the maintenance stage, the development process can return to any of the
previous stages if s drawback is encountered, so a bug or flaw in a stage can be
fixed in the maintenance stage of the SDLC.

The Programming Process 1.2.4


A program is a set of step-by-step instructions that directs the computer to do the
tasks you want it to do and produce the results you want.
Programming helps you understand computers. The computer is only a tool. If
you learn how to write simple programs, you will gain more knowledge about
how a computer works.
Writing a few simple programs increases your confidence level. Many people find
great personal satisfaction in creating a set of instructions that solve a problem.
Learning programming lets you find out quickly whether you like programming
and whether you have the analytically turn of mind programmers need. Even if
you decide that programming is not for you, understanding the process certainly
will increase your appreciation of what programmers and computers can do.
A set of rules that provides a way of telling a computer what operations to
perform is called a programming language.
Developing a program involves steps similar to any problem-solving task. There
are ingredients in the programming process: defining the problem; planning the

solutions; coding the program; testing the program and documenting the program.
Defining the problem: consists of identifying what it is you know (input -given
data) and what it is you want to obtain.

Two common ways planning the solution to a problem are to draw a flowchart and
to write a pseudo-code, or possibly both. Essentially a flowchart is a pictorial
representation of a step-by-step solutions. I t consists of arrow representing the
direction the program takes and boxes and other symbols representing actions. It
is a map of what your program is going to do and how it is going to do it.
ANSI( American Nations Standards Institute) has developed a standard set of
flowchart symbols.
Pseudo-code is an English-like nonstandard language that lets you state your
solution with more precision than you can in plain English but with less precision
than is required when using a formal programming language. Pseudo-code
permits you to focus on the program logic without having to be concerned just yet
about the precise syntax of a particular programming language. However, pseudocode is not executable on the computer.
As we have already noted, a programming language is a set of rules that provides
a way of instructing the computer what operations to perform. There are many
programming languages: BASIC, COBOL, Pascal, FORTRAN, and C are some
examples. You may find yourself working with one or more of these.
To get your program to work, you have to follow exactly the rules-the syntax-of
the language you are using. Of course, using the language correctly is no

guarantee that your program will work, any more than speaking grammatically
correct English means you know what you are talking about. The point is that
correct use of the language is the required first step. Then your coded program
must be keyed, probably using a terminal or personal computer, in a form the
computer can understand.
Programmers usually use a text editor, which is somewhat like a word processing
program, to create a file that contains the program.
Eventually, after coding the program, you must prepare to test it on the computer.
This step involves these phases: Desk-checking. This phase, similar to
proofreading, is sometimes avoided by the programmer who is looking for a
shortcut and is eager to run the program on the computer once it is written.
However, with careful desk-checking you may discover several errors and
possibly save yourself time in the long run. In desk-checking you simply sit down
and mentally trace, or check, the logic of the program to attempt to ensure that it
is error-free and workable. Many organizations take this phase a step further with
a walk through, a process in which a group of programmers-your peers-review
your program and offer suggestions in a collegial way. Translating. A translator is
a program that (1) checks the syntax of your program to make sure the
programming language was used correctly, giving you all the syntax-error
messages, called diagnostics, and (2) then translates your program into a form the
computer can understand. A by-product of the process is that the translator tells
you if you have improperly used the programming language in some way. These
types of mistakes are called syntax errors. The translator produces descriptive
error messages. For instance, if in FORTRAN you mistakenly write N=2 *(I+J))which has two closing parentheses instead of one-you will get a message that
says, "UNMATCHED PARENTHESES." (Different translators may provide
different wording for error messages.) Programs are most commonly translated by
a compiler. A compiler translates your entire program at one time. The translation
involves your original program, called a source module, which is transformed by
a compiler into an object module. Prewritten programs from a system library may
be added during the link/load phase, which results in a load module. The load
module can then be executed by the computer. Debugging. A term used
extensively in programming, debugging means detecting, locating, and correcting
bugs (mistakes), usually by running the program. These bugs are logic errors,
such as telling a computer to repeat an operation but not telling it how to stop
repeating. In this phase you run the program using test data that you devise. You
must plan the test data carefully to make sure you test every part of the program.
Documenting is an ongoing, necessary process, although, as many programmers
are, you may be eager to pursue more exciting computer-centered activities.
Documentation is a written detailed description of the programming cycle and

specific facts about the program. Typical program documentation materials


include the origin and nature of the problem, a brief narrative description of the
program, logic tools such as flowcharts and pseudo-code, data-record
descriptions, program listings, and testing results. The wise programmer continues
to document the program throughout its design, development and testing.
Documentation is needed to supplement human memory and to help organize
program planning. Documentation is critical to communicate with others who
have an interest in the program, especially other programmers who may be part of
a programming team.
Java 1.3
Java is an object-oriented programming language developed by James Gosling
and colleagues at Sun Micro systems in the early 1990s. Unlike conventional
languages which are generally designed either to be to be compiled to native
(machine ) code, to be interpreted from source code at runtime. Java is intended to
be compiled to a bytecode, which is then run ( generally using JIT compilation)
by a Java Virtual Machine.
Java was started as a project called "Oak" by James Gosling in June 1991.
Gosling's goals were to implement a virtual machine and a language that had a
familiar C-like notation but with greater uniformity and simplicity than C/C++.
The first public implementation was Java 1.0 in 1995. It made the promise of
"Write Once, Run Anywhere", with free run-times on popular platforms. It was
fairly secure and its security was configurable, allowing for network and file
access to be limited. In 1997, Sun approached the ISO/IEC JTC1 standards body
and later the Ecma International to formalize Java, but it soon withdrew from the
process. Java remains a proprietary de facto standard that is controlled through the
Java Community Process. Sun makes most of its Java implementations available
without charge, with revenue being generated by specialized products such as the
Java Enterprise System. Sun distinguishes between its Software Development Kit
(SDK) and Run time Environment (JRE) which is a subset of the SDK, the
primary distinction being that in the JRE the compiler is not present.
There were five primary goals in the creation of the Java Language; It should use
the object-oriented programming methodology ; It should allow the same program
to be executed on multiple operating systems ; It should contain built-in support
for using computer networks ; It should be designed to execute code from remote
sources securely ; It should be easy to use by selecting what was considered the
good parts of other object-oriented languages.
The first characteristic, object orientation ("OO"), refers to a method of
programming and language design. Although there are many interpretations of
OO, one primary distinguishing idea is to design software so that the various

types of data it manipulates are combined together with their relevant operations.
Thus, data and code are combined into entities called objects. An object can be
thought of as a self-contained bundle of behavior (code) and state (data).
The principle is to separate the things that change from the things that stay the
same; often, a change to some data structure requires a corresponding change to
the code that operates on that data, or vice versa.
This separation into coherent objects provides a more stable foundation for a
software system's design. The intent is to make large software projects easier to
manage, thus improving quality and reducing the number of failed projects.
Another primary goal of OO programming is to develop more generic objects so
that software can become more reusable between projects. A generic "customer"
object, for example, should have roughly the same basic set of behaviors between
different software projects, especially when these projects overlap on some
fundamental level as they often do in large organizations. In this sense, software
objects can hopefully be seen more as pluggable components, helping the
software industry build projects largely from existing and well-tested pieces, thus
leading to a massive reduction in development times. Software reusability has met
with mixed practical results, with two main difficulties: the design of truly generic
objects is poorly understood, and a methodology for broad communication of
reuse opportunities is lacking. Some open source communities want to help ease
the reuse problem, by providing authors with ways to disseminate information
about generally reusable objects and object libraries.
The second characteristic, platform independence, means that programs written in
the Java language must run similarly on diverse hardware. One should be able to
write a program once and run it anywhere. This is achieved by most Java
compilers by compiling the Java language code "halfway" to bytecode
(specifically Java bytecode)simplified machine instructions specific to the Java
platform. The code is then run on a virtual machine (VM), a program written in
native code on the host hardware that interprets and executes generic Java
bytecode. Further, standardized libraries are provided to allow access to features
of the host machines (such as graphics, threading and networking) in unified
ways.
Although there's compiling stage at some point the Java bytecode is interpreted or
converted to native machine instructions by the JIT compiler. The first
implementations of the language used an interpreted virtual machine to achieve
portability. These implementations produced programs that ran more slowly than
programs compiled to native executable s, for instance written in C or C++, so the
language suffered a reputation for poor performance. More recent JVM
implementations produce programs that run significantly faster than before, using

multiple techniques. The first technique is to simply compile directly into native
code like a more traditional compiler, skipping bytecodes entirely. This achieves
good performance, but at the expense of portability. Another technique, known as
just-in-time compilation (JIT), translates the Java bytecodes into native code at
the time that the program is run which results in a program that executes faster
than interpreted code but also incurs compilation overhead during execution.
More sophisticated VMs use dynamic recompilation, in which the VM can
analyze the behavior of the running program and selectively recompile and
optimize critical parts of the program. Dynamic recompilation can achieve
optimizations superior to static compilation because the dynamic compiler can
base optimizations on knowledge about the runtime environment and the set of
loaded classes. JIT compilation and dynamic recompilation allow Java programs
to take advantage of the speed of native code without losing portability.
One idea behind Java's automatic memory management model is that
programmers should be spared the burden of having to perform manual memory
management. In some languages the programmer allocates memory to create any
object stored on the heap and is responsible for later manually deallocating that
memory to delete any such objects. If a programmer forgets to deallocate memory
or writes code that fails to do so in a timely fashion, a memory leak can occur: the
program will consume a potentially arbitrarily large amount of memory. In
addition, if a region of memory is deallocated twice, the program can become
unstable and may crash. Finally, in non garbage collected environments, there is a
certain degree of overhead and complexity of user-code to track and finalize
allocations. Comparing Java and C++, it is possible in C++ to implement similar
functionality (for example, a memory management model for specific classes can
be designed in C++ to improve speed and lower memory fragmentation
considerably), with the possible cost of extra development time and some
application complexity. In Java, garbage collection is built-in and virtually
invisible to the developer. That is, developers may have no notion of when
garbage collection will take place as it may not necessarily correlate with any
actions being explicitly performed by the code they write. Depending on intended
application, this can be beneficial or disadvantageous: the programmer is freed
from performing low-level tasks, but at the same time loses the option of writing
lower level code.
The syntax of Java is largely derived from C++. However unlike C++ which
combines the syntax for structured generic and OOP; Java was built for the
ground u to be virtually fully OOP; everything in Java is an object with the
exception of atomic dataypes.
Java applets are programs that are embedded in other applications typically in a
web page displayed in a web browser. An applet is placed in an HTML document

using the applet HTML element. The applet tag has three attributes set: Code
specifies the name of the applet class and width and height sets the pixel width
and height of the applet.
The import statements direct the Java compiler to include all of the public classes
and interfaces from the java.io and javax.servlet packages in the compilation. The
Hello class extends the GenericServlet class; the GenericServlet class provides the
interface for the server to forward requests to the servlet and control the servlet's
life-cycle. The service() method is passed a ServletRequest object that contains
the request from the client and a ServletResponse object used to create the
response returned to the client. The service() method declares that it throws the
exceptions ServletException and IOException if a problem prevents it from
responding to the request. Java servlets are server-side Java EE components that
generate responses to requests from clients.
Swing is the advanced graphical user interface library for the Java SE platform.
The import statement directs the Java compiler to include all of the public classes
and interfaces from the javax.swing package in the compilation. Note that once
the frame is displayed, exiting the main method does not cause the program to
terminate because the AWT event dispatching thread remains active until all of the
Swing top-level windows have been disposed.
The default look and feel of GUI application written in Java using the swing
toolkit is very different from native applications. It is possible to specify a
different look and feel through the pluggable look and feel system of Swing.
Java primitive types are not objects. Primitive types hold their values in the stack
rather than being references to value. This was a conscious decision by Java's
designers for performance reasons. Java is not considered to be a pure OOP
language. However as of Java 5.0 auto-boxing enables programmers to write as if
primitive types are their wrapper classes and freely interchange between them for
improved flexibility. Java designers decided not to implement certain features
present in other OO languages to include multiple inheritance; operator
overloading; class properties and tuples.
High-Level vs. Low-Level Programming Languages 1.3.2
Languages are used to communicate between different entities. Computer
language makes it possible to talk to the computers and ask the computer to
perform specific work. Computer languages produces programs which are
executed by CPU and then only understand programs in their own machine
language. Machine language is their language of 0s and 1s, It is difficult to write
program in machine language so what is the solution to this dilemma? The answer
is in high-level languages.
HLLs are programming languages that look like natural language text. Their

advantages are they make programming easier and more abstract IE. the
programmer does not need to come up with the detailed machine instructions.
HLL programs are machine independent . They can run on different hardware
platforms( different computers with different instruction sets).
To run a HLL program on a specific machine, it has to be translated to it's
machine language. This is done through the use of a compiler. A compiler is a
program that translates a HLL program produced by the compiler is usually
referred to as the executable program.
Translating HLL programs to machine language programs is not a one to one
mapping. A HLL instruction (usually called a statement) will be translated to one
of more machine language instructions. The number of mapped machine
instructions depends on the efficiency of the compiler in producing optimized
machine language programs from the HLL programs. A machine language
program produced by a compiler or an assembler. Usually machine language
programs produced by compilers are not efficient contain many unnecessary
instructions that increase processing and slow down execution.
Assembly language is the most basic programming language available for any
processor. A programmer works only with operations implemented directly on the
physical CPU. Assembly language lacks high-level conveniences such as
variables and functions and it is not portable between various families of
processors. Assembly language is the most powerful computer programming
language available and it gives programmers the insight required to write effective
code in high-level languages.
Advantages to learning assembly language: very useful for making efficient and
fast running programs; very useful for making small programs for embedded
system applications; writing compact code.
Compiler is a program that translates the high level programs to machine code
either directly or via assembler. It allows the programmer to specify the memory
locations for his data and programs and symbolically refer to them in his assembly
code. It will translate there symbolic addresses to actual addresses in the produced
machine code.
This is the program that is used to link together separately assembled/ compiled
programs into a single executable code which finally runs on the CPU.
Assembly programmers use debugger and monitor to alter the contents of memory
and registers while running their code. To perform disassemble of their machine
code. Permit them to run their programs, stop them , run them step-by-step or
insert break points. Break pints are positions in the program that if are
encountered during run time, the program will be halted so the programmer can

examine the memory and registers contents ans determine what went wrong.
Interpreter vs. Complied Languages 1.3.3
A compiler is a computer program that implements a programming language
specification to translate programs usually as a set of files which constitute the
source code written in source language into their equivalent machine readable
instructions.
The source language is always a higher-level language in comparison to machine
code, written using some mixture of English words and mathematical notation,
assembly language being the lowest compilable language (an assembler being a
special case of a compiler that translates assembly language into machine code).
Higher-level languages are the most complex to support in a compiler/interpreter,
not only because they increase the level of abstraction between the source code
and the resulting machine code, but because increased complexity is required to
formalize those abstract structures.
The target language is normally a low-level language such as assembly, written
with somewhat cryptic abbreviations for machine instructions, in this cases it will
also run an assembler to generate the final machine code. But some compilers can
directly generate machine code for some actual or virtual computer e.g. byte-code
for the Java Virtual Machine. Another common approach to the resulting
compilation effort is to target a virtual machine. That will do just-in-time
compilation and byte-code interpretation and blur the traditional categorizations
of compilers and interpreters.
An interpreter is a computer program which executes the translation of the source
program at run-time. It will not generate independent executable programs nor
object libraries ready to be included in other programs. A program which does a
lot of calculation or internal data manipulation will generally run faster in
compiled form than when interpreted. But a program which does a lot of
input/output and very little calculation or data manipulation may well run at about
the same speed in either case.
Being themselves computer programs, both compilers and interpreters must be
written in some implementation language. Up until the early 1970's, most
compilers were written in assembly language for some particular type of
computer. The advent of C and Pascal compilers, each written in their own source
language, led to the more general use of high-level languages for writing
compilers. Today, operating systems will provide at least a free C compiler to the
user and some will even include it as part of the OS distribution.
At the highest level compilation is broken into a number of parts 1. lexical
analysis (tokenizing) 2. syntax analysis (parsings) 3. type checking 4. code
generation

any compiler has some essential requirements, which are perhaps more stringent
that for most programs: any valid program must be translated correctly, i.e. no
incorrect translation is allowed; Any valid program must be rejected and not
translated. There will inevitably be some valid programs which can't be translated
due to their size or complexity in relation to the hardware available, for example
problems due to memory size. The compiler may also have some fixed-size tables
which place limits on what can be compiled (some language definitions place
explicit lower bounds on the sizes of certain tables, to ensure that programs of
reasonable size/complexity can be compiled).
There are also some desirable requirements, some of which may be mutually
exclusive: Errors should be reported in terms of the source language or program.
The position at which an error was detected should be indicated; if the actual error
probably occurred somewhat earlier then some indication of possible cause(s)
should also be provided. Compilation should be fast. The translated program
should be fast. The translated program should be small. If the source language has
some national or international standard: Ideally the entire standard should be
implemented. Any restrictions or limits should be well and clearly documented. If
extensions to the standard have been implemented: These extensions to the
standard have been implemented: these extensions.
There are also possibly controversial requirements to consider: Eros detected
when the translated program is running should still be reported in relation to the
original source program e.g. line number. Error detected when the translated
program is running should include division by 0, running out of memory, use of
an array subscript / index which is too big or too small, attempted use of
undefined variable' incorrect use of pointers, etc.
For ease of exposition we will divide the compiler into a front end and a back end.
These need not even be written in the same implementation language, providing
they can communicate effectively via some intermediate representation. The
following list itemizes the task carried out by the front end and the back end. Note
that the tasks are not carried out in any particular order, as outlined below, and
discussed in more detail in subsequent chapters. Front end: lexical analysisconvert character to tokens; syntax analysis check for valid sequence of tokens;
semantic analysis check for meaning; some global/ high level optimization.
Back end: some local optimization; register allocation; peep=hole optimization;
code generation; instruction scheduling. Almost all the source-language aspects
are handled by the front end. Almost all the machine dependent aspects are
handled by the back end. It is possible to have different back ends for different
computers so that the compiler can produce code for different computers.
The front end is normally controlled by the syntax analysis processing. As

necessary the syntax analysis code will call a routine which performs some lexical
analysis and returns the next token. At selected points during syntax analysis,
appropriate semantic routines the next token. At selected points during syntax
analysis, appropriate routines are called which preform any relevant semantic
checked and or add information to internal representation.
A computer is an integrated collection of hardware components, which are
capable of executing instructions called object code stored in a computer's
memory component.
The computer's control component takes the object code stored as a string of
binary bits
(i.e. 0's and 1's), converts the bits to voltage levels, and transmits the voltage
levels to
its hardware components which carry out, or execute, operations as directed by
the
voltages, as specified in the object code. The steps of conversion, transmission,
and
execution by hardware components are called interpretation.
Writing instructions in object code (also called the target language, machine
language,
or a low level language for some computer hardware) is not easy for humans to
do. A low level target language is a language appropriate for computer hardware,
not for humans. Languages that are appropriate for the problems that humans
work on are called higher level or source languages. Many higher level source
languages have been defined over the years, including Java and C++.
Analysis of the source program to check that its grammar or syntax has no errors;
parse the source program to identify its syntactic elements, e.g. operations and
operands and organize the elements into an overall structure and modify this
syntax structure to optimize it.
Java Application Programming Interface (API) 1.3.4.3
Java application programming interface (API) is a list of all classes that are part of
the Java development kit (JDK). It includes all Java packages, classes, and
interfaces,along with their methods, fields, and constructors. These prewritten
classes provide a tremendous amount of functionality to a programmer. A
programmer should be aware of these classes and should know how to use them.
A complete listing of all classes in Java API can be found at Oracles website:
If you browse through the list of packages in the API, you will observe that there
are packages written for GUI programming, networking programming, managing
input and output, database programming, and many more.
Byte Code vs. Machine Code 1.3.5

A source program is a text file that contains a program (such as above) written in
a programming language.

Java combines these ideas in a way that will take some explaining. To run Java
program the source file is first translated into a file of bytecodes.
Java bytecode is a machine instruction for a Java processor. A file of bytecodes
is a machine language program for a Java processor. Conceptually a Java
processor is a silicon processor chip that directly executes a machine language
called Java bytecodes.
The javac program is a compiler that translates the source program into a
bytecode file. The bytecode file will contain exactly the same bytecodes no
matter what computer the javac compiler runs on. 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 same bytecodes as
the Java compiler on an Intel system.
Any computer system can execute a Java bytecode program by using a Java
interpreter. The Java interpreter has to be specifically written for that particular
computer system but once that is done, the computer system can become a Java
virtual machine. Any computer system can execute a Java bytecode program by
using a Java interpreter. The Java interpreter 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 the same no matter what computer
system is used. A java source program can be written and compiled on one
computer to produce bytecode. Now that bytecode can run on any computer that
has a Java interpreter.
Java programs are portable, which means that the same bytecode program can
run on any computer system that has a Java Interpreter. 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 a particular

computer system. No matter what computer you have, you ca write the same
Java programs.
An applet is a Java bytecode program that runs on a Web browser. Most up-todate 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 sends Java bytecodes to a client computer
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.
Introduction to Computer Science Using JAVA 1.3.5
1. Complete the program so that it writes "Good-by" on the computer monitor.
class Bye
{
public static void main ( String[] args )
{
System.out.println("Good-by");
}
}
2. The source file that this program is saved in should be call Bye.java (Be sure you
use correct upper and lower case characters
3. To compile the program, enter this command into the DOS window:
C:\SomeDir>javac Bye.java
4. The compiler will create a file containing bytecodes. This file will be named
Bye.class.
5. To run the bytecodes, enter this command into the DOS window: C:\SomeDir>
java Bye
6. The program that interprets the byte codes on your hardware is called the Java
Virtual Machine.
7. Although the underlying hardware may be different, the Java Virtual Machine on
your computer is the same as that on any other computer, and so can run the same
byte codes.
8. An applet is a Java bytecode program that runs on a Web browser.

9. To create a Java source file, use a program called a text editor such as Notepad.
10. The Dir command of DOS is used to examine the files in a directory.
Programming Language Design 2.1
A class is a set of functions that work together to accomplish a task. It can contain
or manipulate data, but it usually does so according to a pattern rather that a
specific implementation. An instance of a class is considered an object.
An object receives all of the characteristics of a class, including all of its default
data and any actions that can be performed by its functions. The object is for use
with specific data or to accomplish particular task. To make a distinction between
classes and objects, it might help to think of a class as the ability to do something
and the object as the execution of that ability in a distinct setting.
A method simply refers to a function that encased in a class.
A parameter is a variable that is passed into a function that instructs it how to act
or gives it information to process. Parameter are also sometimes called arguments.
A property is a default set of data stored in a class. A class can have multiple
properties and the properties can be changed dynamically through the methods of
the class.
classes can inherit methods and properties from other classes by extending them
and each class can be extended by multiple classes. This means that you can start
with a base (or parent) class that contains shared characteristics among several
classes. That base class can then be extended by other classes (children) that are
similar but are meant for slightly different purposes. Any changes in the parent
class will automatically cascade to its children.
DRY stands for Don't Repeat Yourself and it means just that. If you write some
code, you shouldn't have to repeat that particular code ever again. In practical
terms, it means thinking more abstractly and planning a little better at the outset.
I'll give an example shortly.
KISS stands for Keep It Simple, Stupid and means that you should try to write
code that accomplishes its goal in the simplest manner possible. Simpler means
fewer possibilities for errors and easier maintenance. In the context of OOP, this
usually means making sure that each method has only one task. If you find that a
method does more than one thing, it usually means that it can be re-factored into

several smaller methods, each dedicated to a specific task.


Improved software-development productivity: Object-oriented programming is
modular, as it provides separation of duties in object-based program development.
It is also extensible, as objects can be extended to include new attributes and
behaviors. Objects can also be reused within an across applications. Because of
these three factors modularity, extensibility, and re-usability object-oriented
programming provides improved software-development productivity over
traditional procedure-based programming techniques.
Improved software maintainability: For the reasons mentioned above,
objectoriented software is also easier to maintain. Since the design is modular,
part of the system can be updated in case of issues without a need to make largescale changes.
Faster development: Reuse enables faster development. Object-oriented
programming languages come with rich libraries of objects, and code developed
during projects is also reusable in future projects.
Lower cost of development: The reuse of software also lowers the cost of
development. Typically, more effort is put into the object-oriented analysis and
design, which lowers the overall cost of development.
Higher-quality software: Faster development of software and lower cost of
development allows more time and resources to be used in the verification of the
software. Although quality is dependent upon the experience of the teams, object
oriented programming tends to result in higher-quality software.
Steep learning curve: The thought process involved in object-oriented
programming may not be natural for some people, and it can take time to get used
to it. It is complex to create programs based on interaction of objects. Some of the
key programming techniques, such as inheritance and polymorphism, can be
challenging to comprehend initially.
Larger program size: Object-oriented programs typically involve more lines of
code than procedural programs.
Slower programs: Object-oriented programs are typically slower than procedure
based programs, as they typically require more instructions to be executed.
Not suitable for all types of problems: There are problems that lend themselves
well to functional-programming style, logic-programming style, or procedure-

based programming style, and applying object-oriented programming in those


situations will not result in efficient programs.
Fundamental Concepts of OO Programming 2.2
Real-world objects share two characteristics: they all have state and behavior. Dos
have state( name color breed, hungry) and behavior ( barking, fetching, wagging
tail.)Identifying that state and behavior for real-world objects is a great way to
being thinking in terms of object-oriented programming.

a software object.
A object stores its state in fields ( variables in some programming languages) and
exposes its behavior through methods ( functions in some programming
languages). Methods operate on an object's internal state and serve as the primary
mechanism for object to object communication.
Hiding internal state and requiring all interaction to be performed through an
object's methods is known as data encapsulation.
Bundling code into individual software objects provides a number of benefits,
including: modularity: the source code for an object can be written and
maintained independently of the source code for other objects. One created, an
object can be easily passed around inside the system. Information hiding: By
interacting only with an objects methods, the details of its internal implementation
remain hidden from the outside world. Code re-use: If an object already exists
( perhaps written by another software developer). You can use that object in your
program. This allows specialist to implement/ test/debug complex, task specific
objects, which you can then trust to run in your own code. Pluggability and
debugging ease: If a particular object turns out to be problematic, you can simply
remove it from your application and plug in a different object as its replacement.
This analogous to fixing mechanical problems in the real world. It a bolt breaks

you replace it, not the entire machine.


A class is the blue print from which individual object are created.
Software engineering is concerned with the construction of correct, working, well
written programs.
The structured programming approach to program design was based on the
following advice: to solve a large problem, break the problem into several pieces
and work on each piece separately; to solve each piece, treat it as a new problem
which can itself be broken down into smaller problems; eventually you will work
your way down to problems that can be solved directly, without further
decomposition. The approach is called top-down programming. It is a valuable
and often-used approach to problem solving. However it is incomplete. It deals
almost entirely with producing the instructions necessary to solve a problem yet
as time when on people realized that the design of the data structures for the
program as a least as important as the design of subroutines and control structures.
With strict top down programming is that is makes it difficult to reuse work sone
for other projects. By starting with a particular problem and subdividing it into
convenient pieces top down programming tends to produce a design that is unique
to that problem. It is unlikely that you will be able to take a large chunk of
programming from another program and fit it into your project, at least not
without extensive modification. Producing high quality programs is difficult and
expensive so programmers and the people who employ them are always eager to
reuse past work.
In practice top down design is often combined with botton-up designing. In
bottom up design the approach is to start at the bottom with problems that you
already know how to solve ( and for which you might already reusable software
component at hand. From there you can work upwards towards a solution to the
overall problem. The reusable components should be modular as possible.
The reusable components should be a modular as possible. A module is a
component of a larger system that interacts with the rest of the system in a simple
well-defined, straightforward manner. The idea is that a module can be plugged
into a system. The details of what goes on inside the module as not important to
the system as a whole as long as the module fulfills its assigned role correctly.
This is called information hiding, ans it is one of the most important principles of
software engineering.
One common format for software modules is to contain some data along with
some subroutine for manipulation that data. This protects the data, since it can
only be manipulated in know well defined ways. And it makes it easier for
programs to use the module. Since they don't have to worry about the details of
how the data is represented. Information about the representation of the data is
hidden.
OOP is the central concept of object oriented programming is the object which is

a kind of module containing data and subroutines. The point of view in OOP is
that an object is a kind of self-sufficient entity that has an integrable state and that
can respond to messages. The OOP approach to software engineering is to start
by identifying the objects involved in a problem and the messages that those
objects should responding to. The program that results is a collection of objects
each with its own data and its own set of responsibilities. The objects interact by
sending messages to each other. There is not much top down in such a program .
You should think of objects as knowing how to respond to certain messages.
Different objects might respond to the same message in different ways. This
property of objects that different objects can respond to the same message in
different ways is called polymorphism.
It is common for objects to bear a kind of family relationship to one another.
Objects that contain the same type of data and that respond to the same message
in the same way belong to the same class. ( In actual programming the class is
primary that is a class created and then one or more objects are created using that
class a template.) But objects can be similar without being in exactly the same
class.
Consider a drawing program that lets the user draw lines , rectangles, ovals ,
polygons, and curves on the screen. In the program each visible object on the
screen could be represented by a software object in the program. There would be
five classes of objects in the program, on for each type of visible object that can
be drawn. All the lines would belong to one class, all the rectangles to another
class and so on. These classes are obviously related ; all of them represent
drawable objects. They would for example all presumable be able to respond to a
draw yourself message. Another level of grouping , based on the data needed to
represent each type of object, is less obvious, but would be very useful in a
program: we can group polygons and curves together as multiple point objects
while lines rectangles and ovals are two point objects. ( A line is determined by its
endpoints, a rectangle by two of its corners, and an oval by two corners of the
rectangle that contains it.) We could diagram these relationships as follows:
DrawableObject, MultipointObject, and TwoPointObject would be classes in the
program. MultipointObject and TwoPointObject would be subclasses of
DrawableObject. The class Line would be a subclass of TwoPointObject and
(indirectly) of DrawableObject. A subclass of a class is said to inherit the
properties of that class. The subclass can add to its inheritance and it can even
"override" part of that inheritance (by defining a different response to some
method). Nevertheless, lines, rectangles, and so on are drawable objects, and the
class DrawableObject expresses this relationship.

Inheritance is a powerful means of organizing a program. It is also related to the


problem of reusing software components. A class is the ultimate reusable
component. Not only can it be reused directly if it fits exactly into a program you
are trying to write, but if it just almost fits, you can it be reused directly if it fits
exactly into a program you are trying to write, but it just almost fits, you can still
reuse it by defining a subclass and making only the small changes necessary to
adapt it exactly to your needs.
OOP is meant to be both a superior program-development tool and a partial
solution to the software reuse problem.

Encapsulation is to put both data, and operations that can be performed on this
data, in a single class. The advantages of encapsulation include information
hiding, which means the user does not need to know the implementation details of
the internal design, but is still be able to access and modify the data through
public operations provided.

Inheritance is to reuse the existing classes when creating a new class. The derived
class will inherit public operations defined in the base class.

OOP allows classes to inherit commonly used state and behavior from other
classes. In the Java programming language each class is allowed to have one
direct super-class and each super-class has the potential for unlimited number of
subclasses.

The syntax for creating a subclass is simple . At the beginning of your class
deceleration use the extends keyword followed by the name of the class to inherit
from.

This gives all the same fields and methods of the super-class yet allows its code to
focus exclusively on the features that make it unique. The makes code for your
subclasses easy to read. However, you must take care to properly document the
state and behavior that each super-class defines, since that code will not appear in
the source file of each subclass.

Inheritance is the capability of a class to use the properties and methods of


another class while its own functionality. The concept of inheritance greatly
enhances the ability to reuse code as well as making design a simpler and cleaner

process. Java uses the extends keyword to set the relationship between a parent
class and child class.

The class assumes or inherit all the properties of the box class and can now add its
own properties and methods as well as override existing methods. Overriding
means creating a new set of method statements for the same method signature.

Overriding means creating a new set of method statements for the same method
signature ( name, number of parameters and parameter types. When extending a
class constructor, the super-class constructor and overridden super-class methods
can be reused by using the reserved word super. Note that this reference must
come first in the subclass constructor. The reserved word this is used to
distinguish between the object's property and the passed in parameter. The
reserved word this can also be used to reference private constructors which are
useful in initializing properties.

The super-class contains properties and methods common to all of the sub-classes.
Often the super-class will be set up as an abstract class which does not allow
objects of its prototype to be created. In this case only objects of the subclass are
used. To do this the reserved word abstract is included in the class definition.

Abstract method are methods with no body specification. Sub-classes must


provide the method statements for their specific meaning. If the method was
provided by the super-class, it would require overriding in each subclass. And if
one forgot to override, the applied method statements may be inappropriate.

Abstract classes and methods force prototype standards to be followed.

Interfaces are similar to abstract classes but all methods are abstract and all
properties are static final. Interfaces can be inherited. As with classes the extends
keyword is used for inheritance. Java does not allow multiple inheritance for
classes (ie. A subclass being the extension of more than one super-class. An
interface is used to tie elements of several classes together. Interfaces are also
used to compilation and parameter consistency testing prior to the coding phases.
Interfaces are also used to set up unit testing frameworks. Since this interface has
the method called work(), that method must be defined in any class using the
working interface. When a class that uses an interface is created, reference the
interface with the phrase implements Interface_list. Interface_list is one or more
interfaces as multiple interfaces are allowed. Any class that implements an
interface must include code for all methods in the interface. This ensures
commonality between interfaced objects.

Polymorphism is the ability of an object to take on many forms. In programming


languages polymorphism is the capability of an action of method to do different
things based on the object that it is acting upon. This is the third basic principle of
OOP. The three types of polymorphism are: ad-hoc (overloading and overriding)

parametric (ie generic typing) and dynamic method binding.

Overloaded methods are methods with the same name signature but either a
different number os parameters of different types in the parameter list. By
defining a method for handling each type of parameter one controls the desired
effect.

Over ridden methods are methods that are redefined within an inherited or
subclass. They have the same signature and the subclass definition is used.

Dynamic or late method binding is the ability of a program to resolve references


to subclass methods at runtime. For example assume that three sub-classes have
been crested based on the abstract class each having their one speak() method.
Although each method reference is to an super-class the program will resole the
correct method reference at runtime.

Once a class has been specified a data-type exists with the same name. Specific
instances of discrete copies of a class can be created by the assignment operator
and the new memory allocation operator.

To reference object variables and methods use dot notation. Use


class_name.variable to class_name.method_name(args) for static variables or
methods. Use instance_name.variable or instance_name.method_name(args) for
instance objects declared with new.

An object does not need to be destroyed or removed when it is no longer neede.


Java automatically flags unused objects and applies garbage collection when
appropriate. However the finalize() method can be used to insure that a non-Java
resource such as a file handle to a window font character is released first.

As with arrays of primitive types. Arrays of objects allow much more efficient
methods of access. By making the method speak() abstract, it can be defined for
each subclass and any usage will be polymorphic (ie. Adapted to the appropriate
object type at runtime). It now becomes very easy to rehearse the speak (method)
for each object by object indexing.

One of the difficulties of using a super-class array to hold many instances of


subclass objects is that one can only access properties and methods that are in the
super-class (ie. Common to all). By casting an individual instance to its subclass
form, one can refer to any property or method. But first take care to make sure the
cast is valid by using the instance of operator. Then perform the cast. Casts to
subclass ca be done implicitly but explicit casts are recommended. Cast to superclass must be done explicitly. Casts cannot be made between sibling classes.

A major principle of OOP is keeping the implementation of an object separate


from manipulation. Instance variables are also called attributes and they contain
information that an object of this class will hold. All instances variables are

private, meaning that they can only be directly accesses by an abject of type
customer.

Methods are the behaviors associated with a class. All methods are public
meaning that any other object methods inside of an object of this class. Setter are
used to change the values of the instance variable. Within each of the setters and
getters a programmer could convert from one type to another. The setter could
accept a string as a parameter and then convert this to an array of characters which
would be stored in the instance variable.

A programmer who does not have access to the customer source code only needs
to know how to get access to the instance variables and to change these through
the getters and setters. If a change to a data type of an instance variable was
needed, this could be very easily done. And the getter and setter for that variable
would be modified. A programmer responsible for maintaining objects that use the
customer object would not need to rewrite any code for these objects, since the
getters and setters would still behave the same way. This is the concept of
decoupling: separating implementation from manipulation.

Fundamental Concepts of Object Oriented Programming 2.2


1. In an object-oriented terms, an abject usually has which of the following two
properties? State
and Behavior
2. Which of the following is not a behavior of a car? Going uphill
3. Complete the following sentence. An object stores its state in a ? Field
4. Complete the following sentence. Hiding internal information and requiring all
operations to be
done through an object's methods is known as? Data encapsulation
5. Which of the following is not a benefit of bundling both data and operations into
individual
objects? Loose coupling
6. Fill in the blanks. A(n) class is like a blueprint from which individual objects can be
created.
7. Fill in the blank. In object-oriented terms, my car is a(n) instance of the class of
objects known
as cars.
8. Fill in the blanks. Given a car class, the field (such as speed) represents the object's
state, and
the method (such as changing gears) defines its interaction with the outside world.
9. Fill in the blank. Object-oriented programming allows classes to inherit commonly
used data
and operations from other classes.
10.Fill in the blanks. Car can be a super class of sedan, SUV and a truck, which are

sub class.
HelloWorld.java 3.1
Source code file is a text file created b a programmer that contains a Java
program. Bytecode is a file created by a Java compiler that contains machine
language for the Java virtual machine file name must be named to match the class
name. On all computers, upper and lower case inside a Java program are
important. A programming language where upper and lower case make a
difference is called case sensitive. Java is case sensitive. Not all programming
languages are. A class is a section of a program. Small programs ofter consist of
just one class. When the program is compiled, the compiler will make a file of
bytecodes.
Most classes contain many lines. 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 programing, the name for
something like a class is called an identifier. An identifier consists of alphabetical
characters and digits. The first character must be alphabetical the remaining
characters can be mixed alphabetic characters and digits (plus the two characters
'_' and '$' underscore and dollar sing). No spaces are allowed inside the name.
Usually a class name starts with a capital letter, but it is not required. A source file
should always end with .java in lower case. A reserved world is a word like class
that has a special meaning to the system. You must use reserved words only for
their intended purpose.
Everything that a program does is described between the first brace and the final
brace of a class. The line public static void main(string [ ] args) shows where the
program starts running. The word main means that the main method where the
Java virtual machine starts running the program. The main method starts running
the program. The main method must start with this line ans all of its parts must be
present. Wherever there is one space it is OK to have any number of spaces. The
spaces surrounding the parentheses are not required.
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 the rules by example. The main method of this
program consists of a single statement. System.out.println(hello world!); This
statement writes the characters inside the quotation marks on one line of the
monitor ans then over on to the next line. A statement in a programming language
is a command for the computer to do something . It is like 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 { }.
Programs usually contain many methods. A string is a sequence of characters. A
string literal consists of characters between quote marks , but does not include

the quote marks. It can contain any valid character including white space and
punctuation. This program writes a string to the monitor and then stops. In a
source file a string literal must be on just one line.
A syntax error is a grammatical error in using the programming language. The
error message is not very clear. They never are. Bust at least it shows where the
compiler got confused. The compiler did not create a new bytecode file because it
stopped translating when it do to the error.
Until your program runs correctly 1. Edit the program ( the source code). 2. Save
the program to the hard disk with the Save ot Save As command of the editor. 3.
Compile the program with the javac command. 4. If there are syntax errors, go
back to step one. 5. Run the program with the java command. 6. If there are bugs,
go back to step 1. 7. when it runs correctly quite. This is called the edit-compileand 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
go through the same fundamental cycle.
Just because a program compiles and runs does not mean that it is correct. When a
program compiles without any syntax errors but does not perform as expected
when it runs, the program is said to have a bug. Usually bugs are much more
difficult to find than the one in the previous program. The longer a program is the
more bugs it is likely to have and the more difficult it is to find them. The
compiler does not see the two dimensional layout of the program. It regards the
program as a stream of characters, on following the other.
A comment is a note written to a human reader of a program. A comment starts
with the two characters //. 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. Most program editor are smart enough to recognize
comments and will display them in color. Comments can be placed after a
program statement to explain what it does. The ?? and everything after on that line
are ignored by the compiler. The program statement in the start of the line is not
affected by the comment.
Often you want to write a comment that spans several lines. With this style of
comment , everything between the two characters /* and the two characters */ are
ignored by the compiler. The / and * must not have any character between them.
There can be many lines of comments between the /* 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. Comments are useful for debugging. One way
to narrow down the problem is to remove some of the code from consideration by
turning it into a comment. Compile and run the program. 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.
Examine the program. For every left brace { there is a right} brace the 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). 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 by another two spaces. Line up the braces vertically. Some people
prefer to indent by four spaces for each level. If you use a clever programming
editor, you can set it up to indent as your prefer. It is important to be consistent.
The purpose of the indenting is to visually show the logic of the program. If your
indenting is inconsistent you have defeater the purpose. They are many styles of
laying out a program.
Notice that in addition to pairs of braces that match there are pairs of parentheses (
) , and pair of brackets [ ] that match. Large programs will have many of there
matching pairs, which are used 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 a
tremendous help in programming.
Java. Applet: The applet package provides the classes necessary to create an
applet and the classes an applet uses to communicate with its applet context.
Java.awt: The awt package contains all of the classes for creating user interfaces
and for painting graphics and images.
Java.lang : the lang package provides classes that are fundamental to the design of
the Java programming language.
In order to use a Java class declared in there packages you need to include an
import statement before class declaration to your program. The import statement
starts with the keyword import followed by the name of the java package.
The two kinds of import statements. 1) specific import: this statement imports
only a single class into the program. For example, to import the JoptionPane class
from the javax.swing package we can use the following import statement: import
javax.swing.JOption Pane; this will only import only one class, ie. The
JOptionPane class. 2) wild card import: the wild card import statement imports all
the classes in a package. Import javax.swing*; This statement imports all the
classes from the javax.swing package into your program.
Unless there are comments the first statement in a Java file should be a package
declaration. Following this package declaration, you can ass the import statements
as listed above. The import statements allow you to use classes from other
packages. You can then continue on to define your classes in the file that may use
classes from imported packages.
The import only tells the compiler where to look for symbols and as a result
doesn't make the program mush larger. The wild card * makes the classes in the
associated package visible, but not any of the classes in the sub-packages. All

classes in the java.lang package are automatically visible and do not require an
import. The order of imports is not important and they can be grouped for
readability purposes.
Declaring a Class 3.1.3
1. A source code file is a text file in the JAVA language crested by a programmer with a
text editor.
A bytecode file is a file of machine language for the JAVA virtual machine crested by a
Java
compiler.
2. Pick the correct braces, left brace {or right brace} in the following program.
Class Bye
{
public static void main ( String [] args)
{
System.out.printlin(Hello);
}
}
3. The main method is where a program starts running.
4. A syntax error is a grammatical error in using the programming language.
5. In creating a program you need to frequently revise the source file, compile new
bytecodes, and
run the program to see the result. This process is called the edit , compile and run cycle.
6. Say that your program was compiled without problems, but when your run it
something goes
wrong. This is called a bug.
7. Your assignment is to create a program that writes the following lines on the computer
monitor:
Oh many a peer of England brews
Livelier liquor than the Muse,
And malt does more than Milton can
To justify God's ways to man.
Complete the program so that it performs as required.
class Thomas
{
public static void main ( String[] args )
{
System.out.println(" Oh many a peer of England brews ");
System.out.println(" Livelier liquor than the Muse, ");
System.out.println(" And malt does more than Milton can ");
System.out.println(" To justify God's ways to man ");
}

}
8. Application is a Java bytecode program that runs by itself, without the need of a web
browser.
9. Here is a poorly indented program. Suggest a better way to intent the program by
clicking of the
button where further indenting is needed.
class Percy
{
public static void main (String[ ] args )
{
System.out.println(I arise from dreams of thee);
System.out.println(In the first sweet sleep of night);
System.out.println(When the winds are breathing low,);
System.out.println(And the stars are shining bright);
}
}
10.A comment is a note written to a human reader of a program.
Compiling and Executing a Java Program 3.1.4
This exercise reviews the steps of the method used to run programs from these notes.
Step 1. Start up a DOS command prompt window and the Notepad text editor.
Step 2. Use the CD command in the command prompt window to get to the subdirectory you wish to use.
Step 3. In the browser window, highlight the program with the mouse, then copy it into
the clipboard using the "copy" command from the edit menu.
Step 4.Copy the program into Notepad using the paste command from Notepad's edit
menu.
Step 5. From Notepad save the program to a file using the Save As command from
Notepad's File menu.
Step 6. In the DOS window, use the DIR command to check if the file is there. Then
compile the program using javac and run it using the command java
Variables, Literals and Primitive Data Types 3.2
In programs, names are used to refer to many different sorts of things. In order to
use those things a programmer must understand the rules for giving names to
them and the rules for using the names to work with them, in this a programmer
must understand the syntax and the semantics of names.
According to the syntax rules of Java, the most basic names are identifiers.
Identifiers can be used to name classes, variables and subroutines. An identifier is
a sequence of one or more characters. It must begin with a letter or underscore
and must consist entirely of letter , digits and underscores. In order to be a legal

identifiers. ( examples are N, N, rate, x15, quite_a_long_name, HelloWorld)


No spaces are allowed in identifiers; HelloWorld is a legal identifier, but Hello
World is not. Upper case and lower case letters are considered to be different, so
that HelloWorld, hellowworld, HELLOWORLD, and hELLoWorld are all distinct
names.
Certain words are reserved for special uses in Java and cannot be used as
identifier. These reserved words include:,class,public,static,if,else,while ans
several dozen other words. ( Remember that reserved words are not identifiers,
since they can't be used as names for things.)
Java is actually pretty liberal about what counts as a litter or a digit. Java uses the
Unicode character set, which includes thousands of characters from many
different languages ans different alphabets, ans many of these characters counts as
letters or digits.
http://unicode-table.com/en/#control-character
the pragmatics of naming includes style guidelines about how to choose names for
things. It is customary for names of classes to begin with uppers case letter, while
names of variables and subroutines begin with lower case letters; you can avoid a
lot of confusion by following this standard convention in tour own programs.
Most Java programmers do not use underscores in names , although some do use
them at the beginning of the names of certain kinds of variables. When a names is
made up of several words, such as HelloWorld or interestRate, it is customary to
capitalize each word, except possibly the first; this is sometimes referred to as
camel case, since the uppercase letters in the middle of a name are suppose to
look something like the humps on a camels back.
I'll note that in addition to simple identifiers, things in Java can have compound
names which consist of several simple names separated by periods. (Compound
names are also called qualified names.) System.out.println. The ides here is that
things I s Java can contain other things. A compound names is a kind of path to an
item through one or more levels of containment. The name system.out.println
indicates that something called system contains something called out which in
turn contains something called println.
Programs manipulate data that are stored in memory. In machine language data
can only be referred to by giving the numerical address of the location in memory
where the data is stored. In a high-level language such as Java, names are used
instead of numbers to refer to data. It is the job of the computer to keep track of
where in memory the data is actually stored; the programer only has to remember
the name. A name used in this way to refer to data stored in memory is called a
variable.
Variables are actually rather subtle. Properly speaking a variable is not a name for
the data itself but for a location in memory that can hold data. You should think of
a variable as a container or box where you can store data that you will need to use

later. The variable refers directly to the box and only indirectly to the data in the
box. Since the data in the box can change, a variable can refer to different data
values at different times during during the execution of the program, but is
always refers to the same box. Confusion can arise especially for the beginning
programmers because when a variable is used in a program in certain ways it
refers to the container, but when it is used in other ways it refers to the data in the
container.
In Java the only way to get data into a variable-that is into the box that the
variable names is with an assignment statement. An assignment statement takes
the form: variable=expression; where expression represents anything that refers to
or computes a data value. When the computer comes to an assignment statement
in the course of executing a program, it evaluates the expression and puts the
resulting data value into the variable. For example consider the simple assignment
statement rate=0.07; . The variable in this assignment statement is rate, and the
expression is the number 0.07. The computer executes this assignment statement
by putting the number 0.07 in the variable rate, replacing whatever was there
before. Now consider the following more complicated assignment statement,
which might come late in the same program: interest+rate*principal; The the
value of the expression rate * principal is being assigned to the variable interest.
In the expression the * is a multiplication operator that tells the computer to
multiply rate times principal. The names rate and principal are themselves
variables and it is really the values stored in the variable that matters; in this care
the variable seems to refer to the data in the box rather that to the box itself.
When the computer executes this assignment statement, it takes the value of the
rate , multiplies it by the value of principle and stores the answer in the box
referred to by interest. When a variable is used on the left-hand side of an
assignment statement, it refers to the box that is named by the variable. (Note, by
the way, that an assignment is a command that is executed by the computer at a
certain time. It is not a statement of fact. Fro example, suppose a program
includes the statementrate=0.07; If the statement interest=rate * principal; is
executed late in the program , can we say that the principal is multiplied by 0.07?
No. The value of rate might have been changed in the meantime by another
statement. The meaning of an assignment statement is completely different from
the meaning of an equation in mathematics, even though both use the symbol =.)
A variable in Java is designed to hold only one particular type of data; it can
legally hold the type of data and no other. The compiler will consider it to be a
syntax error if you try to violate this rule by assigning a variable of the wrong
type to a variable. We say that Java is strongly typed language because it enforces
this rule.
There are eight so called primitive types built into Java. The primitive types are
named byte, short, int, long, float, double, char, and boolean. The first four types
can hold integers (whole numbers such as 17, -38477, and 0) The four integer

types are distinguished by the ranges of integers that can hold. The float and
double types hold real numbers (such as 3.6 and -145.99). Again the two real
types are distinguished by their range ans accuracy. A variable of type char holds a
single character from the Uni code character set. And a variable of type boolean
holds one of two logical values true or false.
Any data value stored in the computer's memory must be represented as a binary
number, that is as a string of zeros and ones. A single zero or one is called a bit. A
string of eight bits is called a byte. Memory is usually measured in terms of bytes.
Not surprisingly, the byte data type refers to a single byte of memory. A variable
of type of byte holds a string of eight bits , which can represent any of the integers
between -128 and 127, inclusive.(There are 256 integers in that range; eight bits
can represent 256 two raised to the power of eight-- different values.) As for the
other integer types, short corresponds to two bytes (16 bits). Variables of type
show have values in the range -32768 to 32767. Int corresponds to four bytes (32
bits). Variables of type int have values in the range -2147483648 to 2147483647.
long corresponds to eight bytes (64 bits). Variables of type long have values in the
range -9223372036854775808 to 9223372036854775807.
For representing integer data you should just stick to the int data type, which is
good enough for most purposes.
The float data type is represented in four bytes of memory using a standard
method for encoding real numbers. The maximum value for a float is about 10
raised to the power of 38. A float can have about 7 significant digits. ( so that
32.3989231134 and 32.3989234399 would both have to be rounded off to about
32.398923 in order to be stored in a variable of type of float.) A double takes up 8
bytes can range up to about 10 to the power 308, and has about 15 significant
digits. Ordinarily you should to double type for real values.
A variable of type char occupies two bytes in memory. The value of a char
variable is single character such as A, *, x, or a space character. The value can
also be a special character such a tab to a carriage return or one of the many
Unicode characters that come from different languages. Values of type char are
closely related to integer values, since a character is actually stored as a 16-bit
integer code number. In fact, we will see that chars in Java can actually be used
like integers in certain situations.
It is important to remember that a primitive type value is represented using only
certain, finite number of bits. So, an int can't be an arbitrary integer; it can only be
integer in a certain finite range of values. Similarly , float and double variables
can only take on certain values. They are not true real numbers in the
mathematical sense. For example , the mathematical constant can only be
approximated by a value of type float or double, since it would require an infinite
number of decimal places to represent it exactly. For that matter, simple numbers
like 1/3 can only be approximated by floats and doubles.

A data values is stored in the computer as a sequence of bits. In the computer's


memory, it doesn't look anything like a value written on their page. You need a
way to include constant values in the programs that you write. In a program you
represent constant values as literals. A literal is something that you can type in a
program to represent a value . It is a kind of name for a constant value.
To type a value of type of char in a program, you must surround it with a pair of
single quote marks, such as 'A', *, or x. The character and the quote makes
make up a literal of type of char. Without the quotes, A would be an identifier and
* would be a multiplication operator. The quotes are not part of the value and are
not stored in the variable; they are just a convention for naming a particular
character constant in a program. If you want to store the character a in a variable
ch of type char, you could do so with the assignment statement ch='A'; Certain
special characters have special literals that use a backslash,\ as an escape
character. In particular tab is represented as '\t', a carriage return as 'r\', a linefeed
as 'n\', the single quote character a '\' ', and the backslash itself as '\\'. Note that
even though you type two characters between the quotes in 't\' the value
represented by this literal is a single tab charter.
Numerical literals are a little more complicated that you might expect. Of course
there are the obvious literals such as 317 and 17.42. But there are other
possibilities for expressing numbers in a Java program. First of all, real numbers
can be represented in an exponential form such as 1.3e12 or 12.3737e-108. The
e12 and e-108 represent powers of 10, so that 1.3e12 means 1.3 times 1012 and
12.3737 e-108 means 12.3737 times 10 -108. This format can be used to express
very large and very small numbers . Any numeric literal that contains a decimal
point or exponential is a literal of type double. To make a literal of type of float,
you have to append an F or f to the end of the number. For example, 1.2F
stands for 1.2 considered as a valueof type float. (Occasionally, you need to know
this because the rules of Java say that you can't assign a value of type double to a
variable of type float, so you might be confronted with a ridiculous-seeming error
message if you try to do something like x-1.2; if x is a variable of type float.
You have to say x=1.2F; This is one reason why I advise sticking to type double
for real numbers.)
Even for integer literals, there are some complications. Ordinary integers such as
177777 and -32 are literals of type byte , short, or int, depending on their size. You
can make a literal of type long by adding L as a suffix. For example : 17L or
728476874368L. As another complication, Java allows binary octal (base-8), and
hexadecimal (base-16) literals Octal numbers use only the digits 0 through 7. The
Java, a numeric literal that begins with a 0 interpreted as an octal number; for
example, the octal literals 045 represents the number 37 not the number 45. Octal
numbers are rarely used. But you need to be aware of what happens when you
start a number with a zero. Hexadecimal numbers use 16 digits, the usual digits 0

and 9 and the letters A, B, C, D, E and F. Upper case and lower letters letters can
be used interchangeably in their context. The letters represent the numbers 10
through15. In Java a hexadecimal literal begins with 0x or X as in 0x45 or
0xff7A. Finally binary literals start with 0b or 0B and contain the digits 0 and 1;
for example 0b10110.
As a final complication numeric literals in Java 7 can include the underscore
character(_), which can be used to separate f=groups of digits. For example, the
integer constant for seven billion could be written 7_000_000_000; which is a
good deal easier to decipher than 7000000000. There is no rule about how many
digits have to be in each group. Underscores can be especially useful in long
binary numbers; or example, 0b1010_1100_1011.
Hexadecimal numbers can also be used in character literals to represent arbitrary
Unicode characters. A Unicode literal consists of \u followed by four hexadecimal
digits. For example , the character literal '\u00E9' represents the Unicode
character that is can e with an acute accent.
For the type boolean, there are precisely two literals: true and false. These literals
are typed just as I've written them here, without quotes, but they represent values,
not variables. Boolean values occur most often are the values of conditional
expressions. For example, rate > 0.5. is an Boolean-valued expression the
evaluates to true if the value of the variable rate is greater than 0.05, and to false if
the value of rate is not greater than 0.05. Boolean-value expressions are used
extensively in control structures. Of course , boolean values can also be assigned
to variables of type boolean. For example, if test is a variable of type boolean,
then both of the following assignment statements are legal: test=true;
test=rate>0.05;
Java has other types in addition to the primitive types, but all the other types
represent objects rather than primitive data values. For the most part we are not
concerned with objects for the time being. However there is one predefined object
type that is very important: the type String.
A value of type Sting is a sequence of character. The double quotes are part of the
literal; they have to be typed in the program. However they are not part of the
actual String value, which consists of just the characters between the quotes. A
string can contain any number of characters, even zero. A string with no
characters is called the empty string and is represented by the literal, a pair of
double quote marks with nothing between them. Remember the difference
between single quotes and double quotes! Single quotes are used for char literals
and double quotes for string literals. This is a big difference between the String
A and the char 'A'.
Within a string literal, special characters can be represented using the backslash
notation. Within this context, the double quote is itself a special character. For
example, to represent the string value I said, Are you listening! with a line feed

at the end, you would have to type the string literal: I said,\Are you
listening!\\n You can also use \t,\r,\\, and Unicode sequences such as \u00e9 to
represent other special characters in string literals.
A variable can be used in a program only if it has first been declared. A variable
declaration statement is used to declare one or more variables and to give them
names. When the computer executes a variable declaration, it sets aside memory
for the variable and associates the variable's name with that memory. A simple
variable declaration take the form: type-name variable-name or names; The
variable-name-or-names a single variable name or list of variable names separated
by commas. Good programming style is to declare only one variable in a
declaration statement, unless the variable are closely related in some way. For
example: int numberofStudent; String name; double x,y; boolean is Finished; char
firstInitial, middleInitial, lastInitial; It is also good style to include a comment
with each variable declaration to explain its purpose in the program, or to give
other information that might be useful to a human reader. For example: double
principal; // Amount of money invested. Double intrestRate;// Rate as a decimal,
not percentage. We will only use variables declared inside the main ( ) subroutine
of a program. Variables declared inside a subroutine are called local variables for
that subroutine. They exist only inside the subroutine, while it is running and are
completely inaccessible from outside. Variable declarations can occur anywhere
inside the variables at the beginning of the subroutine. Others like to wait to
declare a variable unit it is needed. Declare important variables at the beginning
of the subroutine and use a comment to explain the purpose of each variable.
Declare utility variable which are not important to the overall logic of the
subroutine at the point in the subroutine where they are first used.
This value is called a parameter to the subroutine. A parameter provides a
subroutine with information it needs to perform it tasks. In a subroutine call
statement, any parameters are listed in parenthesis after the subroutine name. Not
all subroutines have parameters. If there are no parameters in a subroutine call
statement, the subroutine name must be followed by an empty pair of parentheses.
The Java programming language defines the following kinds of variables:
Instance Variables ( Non-Static Fields) technically speaking , objects store their
individual states in non-static fields, that is fields declared without the static
keyword. Non-static fields are also known as instance variables because their
values are unique to each instance of class ( to each object, in other words); the
currentSpeed of one bicycle is independent from the currentSpeed of another.
Class Variables (static Fields) A class variable is any field declared with the static
modifier; this tells the compiler that there is exactly one copy of this variable in
existence, regardless of how many times the class has been instantiated. A field
defining the number of gears for s particular kind of bicycle could be marked as
static since conceptually the same number of gears will apply to all instance. The

code static int numGears=6; would create such a static fields. Additionally the
keyword final could be added to indicate that the number of gears will never
change.
Local Variable similar to how an object stores its state in fields, a method will
often store its temporary state in local variables. The syntax for declaring a local
variable is similar to declaring a field (for example, int count = 0;) There is no
special keyword designation a variable as local; that determination comes entirely
from the location in which the variable is declared which is between the opening
and closing braces of a method. As such, local variables are only visible to the
methods in which they are declared, they are not accessible from the rest of the
class.
Parameters You've already seen examples of parameters, both in the Bicycle class
and in the main method of the Hello World! application. Recall that the
signature for the main method is public static void main (String [ ] args). Here the
args variable is the parameter to this method. The important thing to remember is
that parameters are always classified as variables not fields. This applies to other
parameter-accepting constructs as well ( such as constructors ans exception
handlers) that you'll learn about later in the tutorial.
A type's fields, methods, and nested types are collectively called its members.
Variable names are case sensitive. A variable's name can be any legal identifier
an unlimited sequence of Unicode letters and digits beginning with a letter the
dollar sign $ of the underscore character _. The convention however is to
always begin your variable names with a letter, not $ or _. Additionally the
dollar sign character by convention, is never used at all. You may find some
situations where auto-generated names will contain the dollar sign, but your
variable names should always avoid using it. A similar convention exists for the
underscore character; while it's technically legal to begin your variable's name
with _, this practice is discouraged. White space is not permitted.
Subsequent character may be letters, digits, dollar signs, or underscore characters.
Conventions apply to this rule as well. When choosing a name for variables, use
full worlds of cryptic abbreviations. Doing so will make your code easier to read
and understand. In many cases it will also make your code self-documenting;
fields named cadence, speed, and gear for example are much more intuitive that
abbreviated versions such as s,c, and g. Also keep in mind that the name you
choose must not a keyword or reserved word.
If the name you choose consists of one word spell that word in all lower case
letters, If it consists of only one word, spell that word in all lowercase letters. If it
consists of more that one word, capitalize the first letter of each subsequent word.
The names gearRation and currentGear are prime examples of this convention. If
your variable stores a constant value, such as static final in Num_GEARS=6, the
convention changes slightly, capitalizing every letter and separating subsequent

words with the underscore character. By convention, the underscore character is


never used elsewhere.
Type Size Range
byte 8 bits -128 to +127
short 16 bits -32,768 to +32,767
int 32 bits -2 billion to +2 billion (approximately)
long 64 bits -9E18 to +9E18 (approximately)
boolean 1 bit True or False
char 16 bits Unicode (All the World's Lang.)
Type Size Range
float 32 bits -3.4E38 to +3.4E38
double 64 bits -1.7E308 to 1.7E308
E means ten to the power of
Primitive Characters 3.2.3
5. The following are All legitimate data types in Java. Which ones are primitive,
and which ones
are classes?
a. int - primitive
b. String - class
c. double primitive
d. Scanner - class
e. short - primitive
A character literal is a single character with an apostrophe on each side:
'm' 'y' 'A'
A control character is represented with a special sequence of characters:
'\n' '\t'
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. There are unaccountably
many types of data that can be represented in the memory of a computer. If
specific patterns always had specific meaning, then only a few types of data could
be represented. Programs can use this memory with whatever data types they
need. There are types of data that are so fundamental that ways to represent them
are built into Java. There are the primitive data types. The eight primitive data
types are: byte, short, int, long, float, double, char, and boolean. Computer
languages where case is important are called case sensitive. In the phrase
primitive data type the word primitive means a fundamental compnent that is used
to create other , larger parts. All data in Java 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 many others as you need. Any data

type you invent will be a type of object. 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. Integer types have no fractional part; floating point types have a
fractional part. There is a fundamental difference between the method used to
represent integers and the method used to represent floating point numbers. This
means that if you are using a particular data type then the same number of bits
will be used no matter what value is represented. Values that are large in
magnitude (negative or positive ) need more bits to be represented. Usually you
should pick a data type that has a range much greater than the range of numbers
you expect to deal with. Usually you should use int or double for your numeric
data. This called a literal. The word literal means that a value is explicitly shown
in the program. A 64 bit long literal has upper case 'L' or lower case 'l' at the end.
If you use the literal 197.0 in a program, the decimal point tells the compiler to
represent the value using a floating point primitive data type. Data type float is
sometimes called single precision floating point. Data type double has twice as
many bits and is something called double precision floating point. Literals written
like the above will automatically be of type double. Sometimes you need to
explicitly ask for a single-precision float literal. Sometimes you need to explicitly
ask for a double literal. Do this by putting a lower case 'd' or upper case 'D' at the
end. You will sometimes see scientific notation. The big E means times 10 to
the power of in which direction and for how many places to shift the decimal
point. 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
primitive data type for characters in Java is named char. 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. The method is called Unicode. Knowing that data
type of a pattern is necessary to make sense of it. Upper and lower case characters
are represented by different patterns. 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 that are rarely used there
days. Primitive type char represents a single character. It does not include any font
information. A character literal is a single character with an apostrophe on each
side. A control character is represented with a special sequence of characters.
Each of there represents a single control character. String is not a primitive data
type and is surrounded by double quote marks not by apostrophes. Another of the
primitive data types is the type boolean. It is used to represent a single tue/false
value. The data type boolen is named after George Boole, a nineteenth century
mathematician, who discovered that a great many things can be done with

true/false values.
Integer type is a commonly used primitive data type. It represents integers using
8, 16, 32, or 64 bits. The number of bits decides the range of an integer. Floats and
doubles are data types that have a fractional part. They can represent a number
with decimal point. Booleans is a data type that only stores a value true or
false. Booleans type is fundamental to implement Boolean logic expression.
Chars is a data type that stores a single character. The char type provides a basic
unit corresponding to a symbol on the keyboard as well as a special character
defined in a character set.
Flash Cards on Primitive Data Types 3.2.3
1. What is the type of this literal 401.23 ? Double
2. What is the literal B ? String (not char , because of the double quote)
3. A language where upper and lower case letters make a difference in names is
called? Case sensitive
4. What is the type of this literal 32D? Double
5. What is the type of this literal 401.23F? Float
6. What is the type of this literal 12.6E13 ? Double
7. How many bytes are in data type short? 2
8. What range of values can be represents in a byte? -128 to +127
9. What range of values can be represented in an int? About -2 billion to about +2
billion
10. What is the type of this literal 'A'? char (from the single quotation mark)
Basic Operations in Java 3.3
Little sections of main memory called variables. The billions of bytes of main
storage in your home computer are used to store both machine instructions and
data. The electronic circuits of main memory make no distinction between the
two. Suing the same memory for both instructions and data was the idea of John
Von Neumann, a computer pioneer. Variable a named location in main memory
which uses a particular data type which uses a particular data type to hold a value.
Think of a variable as 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 each variable. A declaration of a variable is where
a program says that it needs a variable. The declaration gives a name and a data
type for the variable. A variable cannot be used in a program unless it has been
declared.( http://ideone.com/ Java Online Simulation) The word syntax means the
grammar of a programming language. There are several ways to declare variables
dataType variableName; This declares a variable, declares its data type and
reserves memory for it . It says nothing about the value is put in memory.
DataType variableName = initialValue; This declares a variable, declares its data

type reserves memory for it and puts an initial value into that memory. The initial
value must be of correct data type. dataType variableNameOne,
variableNameTwo; This declares two variable, both of the same data type,
reserves memory for each, but puts nothing in any variable. You can do this with
more than two variables. dataType variableNameOne=initialValueOne,
variableNameTwo=intitialValueTwo; This declares two variables, both of the
same data types, reserves memory, and puts an initial value in each variable. You
can so this all on one line if there is room, You can do this for more than two
variables as long as you follow the pattern. A name chosen by a programmer is
called a identifier. Use only the characters 'a' through 'z', 'A' through 'Z', '0'
through '9', character '_', and character '$'. 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. An identifier can not be a reserved word.
An identifier must not already be in use in this part of the program. A reserved
word is a word which has a predefined meaning in Java. A name for a variable
usually starts with a lower care letter. The character * means multiply. 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 an value to be calculated. When it
follows a character sting + means to add characters to the end of the character
string. Integers do not have fractional parts. Floating point type which does have a
fractional part. The parentheses around force the multiplication to be done first.
When you have a calculation as part of a statement it is a good idea to surround
the calculation with parentheses. Anywhere a space character is OK you can split
a statement. Although correct the division of statements is confusing to humans.
It is a good idea to indent the second half of a split a statement. An assignment
statement changes the value that is held in a variable. The assignment statement
puts the value into the variable. The word execute is often used to mean run.
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 to be
calculated. The syntax of a programming language says what programs look like.
The semantics of a programming language says what the program does as it
executes. An assignments statement does its work in tow steps: Fist do the
calculation on the right of the equal sign. Replace the contents of the variable on
the left of the equal sign with the result of the calculation. Step two will replace
whatever is already in total. The two statements executes one after the other and
each statement perform two steps. The first statement: get the number on the right
of the equal sign. Step two look on the left of the equal sign to see where to put
the result. A variable can be used on both the Left and the Right of the + in the
same assignment statement. When is is used on the right it provides a number
used to calculate a value. When is is used on the left, it says where in memory to
save that value. Increment the number in count. Sometimes programmers call this

incrementing a variable although it is really the number in the variable that is


incremented. An expression is a combination of literals, operators, variable names
and parenthese used to calculate a value. Literal characters that directly give you
a value. Operator a symbol like plus or times that asks for an arithmetic operation.
Variable a section of memory containing a value. Parentheses. / means division.
Multiplication must always be shown by using a * operator. An expression can be
written with using any spaces. Use spaces wisely to make it clear what the
expression means. Spaces can't be placed in the middle of identifiers. It is possible
to be deceptive with spaces.
Operator
Meaning precedence
-

unary minus

highest

unary plus

highest

multiplication middle

division

middle

remainder

middle

addition

low

subtraction
low
An arithmetic operator is a symbol that asks for two numbers to be combined by
arithmetic. Operators of highest precedence are done first. Addition and
subtraction have the same precedence. Unuary minus and unary plus operators
are used as part of negative or positive number. When both operands are integers,
these operators do integer arithmetic. If one operand or both operands are floating
point then these operators do floating point the these operators do floating point
arithmetic. The unary minus is used to show a negative number. The subtraction
operator is used to show a subtraction. The unary minus operator has precedence.
To show exactly what numbers go with each operator, us parentheses. The ( )
groups together what you want done first. It does not hurt to use parentheses that
are not needed. Look out for division. The operator is a constant source of bugs.
Parentheses will help. Sometimes in a complicated expression one set of
parentheses in not enough. The innermost set of parentheses is evaluated first.
Start evaluating at the most deeply nested set of parentheses and the work outward
unit there are no parentheses left.
Variables and Assignment 3.3
1. Which one of the following is a reserved word? Boolean
2. Which one of the following is not a correct variable name? 2Bad
3. Which one of the following declarations in not correct ? Boolean value = 12;
4. What does the following program output?
Class question4

{
public static void main (String [ ] args)
{
int unitCost = 8;
int items = 5;
System.out.printlin ( total cost: + (unitCost * items) );
}
}
5. Which of the following shows the syntax of an assignment statement? VariableName
=
expression;
6. What are the two steps that take place when an assignment statement is executed? (I)
Evaluate
the Expression, and (ii) Store the value in the variable.
7. What is an expression? An expression is a combination of literals, operators,
variables, and
parenthesis use to calculate a value.
8. Which one of the following expressions is not correct? -12 + ( 13+ 7 ) / 2 ) * 4
9. Which of the following expressions is not correct? 34 86 ) / ( 23 3 )
10.What is the value of the following expression : (2-6) / 2+9 ? 7
An expression is a combination of literals, operators, variable names, and
parentheses used to calculate a value. Expression contain operators and operands.
An operands is a value that is acted upon by an operator. Each operator must have
be arranged correctly. The syntax of Java describes the correct arrangements.
Each operator must have the correct number of operands. Multiplication *,
Division / , Addition +, Subtraction should have two operands, one on each side.
Negative and unary plus + should be followed by one operand. Parentheses ( )
can surround a legal expression to make it an operand. In Java expressions,
operators and operands must be explicit. In a correct expression, parentheses will
always be balanced. Parentheses are balanced with they from matching pairs.
These operators for arithmetic . These operators can be used on floating point
numbers and on integer numbers. For instance, / means integer division is both
operands are integers and means floating point division if one or both operands
are floating point. An interfere operation is always done with 32 bits or more. If
one or both operand is done with 64 bits. Otherwise the operation is done with 32
bits even if both operands are smaller than 32 bits. The division operator / means
integer division is 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 integer
division is always an integer. Integer division determines how many times one
integer goes into another. Integer arithmetic might be used in some parts an
expression and not in others, even though the final value expression is floating
point. The normal rules of arithmetic are used to determine the sign of result of

division. Most of the operators we are interested in take two operands. In each of
the following examples the operator has two operands. Unary operators take just
one operand. A binary operator will always have exactly two operands. However,
sometimes one or both operands of a binary operator is a subexpression. A
subexpression is a part of an expression that is by itself a correct expression. Any
expression can be a subexpression of a larger expression. If both operands are
integers, then the operation is an integer operation. If any operand is floating point
then the operation is floating point. In more complicated expressions an operand
of an particular operator might be a subexpression. The rule still applies if one or
both operand is a floating point type then the operation is floating point. 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 symbol for finding the
remainder is % ( percent sign). This symbol is also called the modulo operator.
Operators you will see that it has the same precedence as / and *. The integer
division operator / and the remainder operator % take an integer apart. The
original integer can be put back together again. The remainder operator can be
used with negative integers. The rule is performed the operation as if both
operands were positive. If the left operand is negative then make the result
negative. If the left operand is positive then make the result positive. Ignore the
sign of the right operand in all cases. Often in a program you want to give a name
to constant value. . The reserved word final tells the compiler that the value will
not change. Constants make your program easier to read and check for
correctness. If a constant needs to be changes all you need to do is change the
declaration of the constant . You don't have to search through your program for
every occurrence of a specific number. In your programs used a named constant
like durable rather then using a literal.
Quiz on Expressions 3.3
1. Which one of the following is not a correct arithmetic expression? alpha ( /
momentum - 12.4 )
2. What is an operand? A value that is acted upon by an operator.
3. Assume the following declarations:
short a=12 ;
int b=33 ;
float x = 2.3;
double y = 3.14;
Which one of the following expressions will NOT be evaluated using double
precision floating point? a+b
4. What does the following program output?
class question4
{
public static void main ( String[] args )
{

int totalCost = 6;
int items = 12;
System.out.println("cost per item: " + totalCost/items );
}
} cost per item :
0
5. What is the result of evaluating the following expression?
( 1/2 + 3.5) * 2.0 7.0
6. What is the result of evaluating the following expression?
-32 / 6 -5
7. What is an expression? An expression is a combination of literals, operators,
variables, and
parentheses used to calculate a value.
8. Given the following expression:
(a - x)/(13 - z)
Which of the following is NOT a subexpression? x ) / (13
9. What is the value of
-32 % 6 -2
10. Which of the following declarations works for the constant pi (assume that the
numerical value
is correct)? final double pi = 3.14159265358979 ;

Besides basic arithmetic operations such as addition, subtraction, multiplication,


division, arithmetic operators also include reminder operator, unary plus, and
unary minus. Together with operands, arithmetic operators are used to build
arithmetic expressions.
The assignment statement is one of the central constructs in programming
languages. Using an assignment statement, the programmer can change the
binding of values to the variables in the program. The variables are of type integer
in their case. Int x = 0; int y = 1; The assignment operator can be combined with
various arithmetic and logic operators to provide compound assignments where
arithmetic and logic operations are part of the assignment operations. The
assignment can be combined with the following arithmetic and logic operations.
+
addition
+= x
+= 5; or x = x + 5;
subtraction
-= x
-= 5; or x = x - 5;
*
multiplication
*= x
*= 5; or x = x * 5;
/
division
/= x
/= 5; or x = x / 5;
%
remainder
%= x
%= 5; or x = x % 5;
<< shift left
<<= z
<<= 5; or z = z << 5;
>> shift right
>>= z
>>= 5; or z = z >> 5;
&
and
&= y
&= 5; or y = y & 5;

^
xor
^= y
^= 5; or y = y ^ 5;
|
or
|= y
|= 5; or y = y | 5;
Java has two special unary arithmetic operations, which are special cases of
compound assignment operators. These are the increment and the decrement
operators. The combine increment and decrement operations (++ and ) with the
assignment operation.
X=++count;
is equivalent to
count = count+1;
x=count;
In OOP classes provide a blueprint or a factory for creating objects. An object is
an instance of a class. An object is an instance of a class.
Rectangle R1= new Rectangle(5,10);
creates a new rectangle object named R1 with length 5 and width 10.
rectangle R2= new Rectangle (7,8);
creates another new rectangle object named r2 with length 7 and width 8.
Typecasting is to convert one data type to another data type, for example, integers
to doubles, which can be done either implicitly or explicitly

String Class 3.4


Strings which are widely used in Java programming, are a sequence of characters.
In the Java programming language, strings are objects. The Java platform
provides the String class to create and manipulate strings.
The most direct way to create a string is to write: String greeting = Hello world!';
In this case, Hello worlds! is a string literal= a series of characters in your code
that is enclosed in double quotes. Whenever it encounters a string literal in your
code, the compiler creates a String object with its value- in this case, Hello world!
As with any other object you can create String objects by using the new keywords
and a constructor. The String class has thirteen constructors that allow you to
provide the initial value of the string using different sources, such as an array of
characters. The string class immutable, so that once it is created a string object
cannot be changed. The string class has a number of methods, some which will be
discussed below, that appear to modify strings. Since are immutable, what these
methods really do is create and return a new string that contains the result of the
operation. Methods used to obtain information about an object are known as
accessor methods. One accessor method that you can use with string is the length
( ) method, which returns the number of characters contained in the string object.
After the following two lines of code have been executed, len equals 17; String
palindrome = Dot saw I was Tod; int len = palindrome.length( ) ; A palindrome
is a word or sentence that is symmetric it is spelled the same forward and
backward, ignoring case and punctuation. Here is a short and inefficient program

to reverse a palindrome string. It invokes the String method charAt (i), which
returns the ith character in the string, counting from 0.
public class StringDemo {
public static void main (String [ ] args) {
String palindrome = dot saw I was Tod;
int len = palindrome.length ( ) ;
char [ ] tempCharArray = new char[len];
char [ ] charArray = new char [ len];
// put original string in an
// array of chars
for (int i=0; i< len; i++) {
tempCharArray [i] =
palindrome.charAt(i);
}
// reverse array of chars
for (int j = 0; j < len; j++) {
charArray [j] =
tempCharArray [ len -1 j ];
}
String reversePalindrome =
new String (charArray);
System.out.println (reversePalindrome);
}
}
Running the program produces this output: doT saw I was toD
To accomplish the string reversal, the program had to convert the string to an
array of characters (first for loop), reverse the array into a second array (second
for loop), and then convert back to a string. The string class includes a method,
getChars ( ), to convert a string , or portion of a string, into an array of characters
so we could replace the first loop in the program above with
palindrome.getChars(0 , len, rempCharArray, 0);
The string class includes a method for concatenating two strings:
string1.concat(string2); This returns a new string that is string1 with string2 added
to it at the end. You can also use the concat 9) method with string literals, as in:
My name is .concat(Rumpelstiltskin); Strings are commonly concatenated
with the + operator, as in Hello, + world + ! which results in Hello,
world! The operator + is widely used in print statements. Such a concatenation
can be a mixture of any objects. For each object that is not a String, its toString ( )
method is called to convert it to a String. The Java programming in languages
does not permit literal strings to span lines in source files, so you must use the +
concatenation operator at the end of each line in a multi-line string. Breaking
strings between lines using the + concatenation operator is once again very

common in print statements.


You have seen the use of the printf( ) and format( ) methods to print output with
formatted numbers. The string class has an equivalent class method, format ( ) ,
that returns a String object rather than a PrintStream object. Using String's static
format ( ) method allows you create a formatted string that you can reuse, as
opposed to a open-time print statement.
String objects are very useful and are frequently used. To make life easier for
programmers Java has a short-cut way for creating String object: String zeta - the
last rose of summer. This creates a String object containing the characters
between quote marks. A string created in theis short cut way is called String
literal. The previous paragraph is correctly stated, but awkward. People often say
"String" when they really mean "reference to a String". This is fine, but remember
that a reference variable like stringA does not contain an object, but only a
reference to an object. This may seem picky, but there is nothing quite as picky as
a computer.
The Code
stringA.equals
( stringB )

What is usually said


The equals method of
stringA is called with
stringB.

Careful meaning
The equals method of the String
referenced by stringA is called with
the reference in stringB.

A reference variable holds information about the location of an object. It does not
hold the object itself. Null is a special value that means no object. Set a
reference variable to null when it is not referring to any object. Variables are often
set to null when they are declared. The value null works for this and can be
assigned to any reference variable. In most programs , objects come and objects
go, depending on the data and on what is being computed. A reference variable
sometimes does and sometimes does not refer to an object, and can refer to
different objects at different times. You need a way to say that a variable does not
now refer to an object. You do this by assigning null to the variable.

A string object that contains no character is still an object. Such an object is called
an empty string. It is similar to having a blank sheet of paper. Overlooking this
difference is one of the classic confusions of computer programming. That each
variable contains a String reference before calling println( ) with it. The first
statement does two things: (1) a String object is created, containing the characters.
Then (2) a reference to that object is saved in the reference variable alpha. The
second statement assigns the value null to alpha. When this happens, the reference
to the object is lost. Since there is no reference to the object elsewhere it is now
garbage. The object still exists in memory. The memory it consists of will
eventually be recycled by the garbage collector and will be made available for
new objects. This time the object does not become garbage. This is because in the

second statement a reference to the object is saved in a second variable, beta. Now
when in the third statement, aloha is set to null, there is still a reference to the
object. There can be many copies of the reference to an object. Only when there is
no reference to an object anywhere does the object become garbage.
public String concat(String str);
--+--- --+--- --+-- ----+---|
|
|
|
|
|
|
|
|
|
|
+---- says that the method requires a
|
|
|
String reference parameter
|
|
|
|
|
+----- the name of the method
|
|
|
+----- the method returns a reference
|
to a new String object
|
+----- anywhere you have a String object,
you can use this method
The concat method performs String concatenation. A new String is constructed
using the data from two other Strings. In the example, the first two Strings supply
the data that concat ( ) uses to construct a third string. The first two Strings are
not changes by the action of concat ( ). A new String is constructed that contains
the characters. The picture shows the operation of the concat ( ) method before the
reference to the new object has been assigned to name. String concatenation, done
by contact ( ) or by +, always constructs a new object based on data in other
objects. Those objects are not altered at all. When the operands on either side of +
are numbers, then + means addition. If one or both of the operands is a String
reference, then String concatenation is performed. When an operator such as +
changes meaning depending on its arguments, it is said to be overloaded.
Objects of some Java classes cannot be altered after construction. The class String
is one of these. Sometimes immutable objects are called write-once objects. Once
a String object has been constructed, the characters it contains will always be the
same. Non if its methods will change those characters, there is no other way to
change them. The characters can be used for various purposes and can be
inspected. But never altered. String objects are immutable. This means that after
construction, a String object cannot be altered. The length of a string is the
number of characters it contains, including space characters and punctuation. A
empty string has length zero. The length ( ) method of a String returns its length.
The method takes no parameters, but the ( ) is needed when it is used.

lengt
h

String
"element"

"x"

""

"Look Homeward" 13
" Look Out "

13

The trim ( ) method of a string object creates a new String object creates a new
String that is the same as the original except that any leading or trailing space is
trimmed off. The new String contains the same characters as the old one but has
whitespace characters removes from both ends. The new String referenced by
fixed will contain the characters without any surrounding spaces. This method is
often useful. Extraneous spaces on either end of user input is a common problem.
The charAt ( int index) method returns a single character at the specified index. If
the index is negative, or greater than length ( ) -1, an
indexOutOfBoundsException is thrown. The value returned by charAt ( int index)
is an char, not a String containing a single character. A char is a primitive data
type, consisting of two bytes that encode a single character.

Expression

Result

String source = "Subscription";

"Subscription"

source.charAt(0)

'S'

source.charAt(1)

'u'

source.charAt(5)

'r'

source.charAt(source.length()-1)

'n'

IndexOutOfBoundsExce
ption
Here is a program that checks that every line of a text file has a space character in
column 10. This might be used to verify the correct formatting of columnar data
or of assembly language source programs. The program is used with redirection
c:\ javac ColumnCheck.java ; c:\ java ColumnCheck < datafile.txt . When the
program is running the nextLine ( ) method reads one line from the file. An

source.charAt(12)

improved program might ask the user for several column numbers to check.
A substring of a string is a sequence of characters from the original string. The
characters from the original string and no characters are skipped. The method
creates a new substring that consists of the characters from character number
begin Index to the end of the string. Remember character numbering starts with
zero. The leftmost character of a string is character zero. The method public
String substring (int beginIndex) creates a new string. The original string is not
changed. There are two tricky rules : 1. If the beginIndex is exactly equal to the
length of the original string, a substring is created, but it contains no characters ( it
is an empty string) 2. If beginIndex is greater than the length of the original string,
or a negative value , an IndexOutOfBoundsException is thrown ( and for now,
your program crashes).
substring(int beginIndex, int endIndex) This method creates a new String
containing characters from the original string starting at beginIndex and ending at
endIndex-1. The Character at endIndex is not included. The length of the resulting
substring is endIndex-beginIndex.
As with the other substring method; this one public String substring (int
beginIndex, int endIndex) creates a new string. Here are some more rules.
Essentially the rules say that if the indexes make no sense, a
IndexOutOfBoundsException is thrown. 1. If beginIndex is negative value, an
IndexOutOfBoundsException is thrown. 2. If beginIndex is larger than endIndex
an IndexOutOfBoundsException is thrown. 3. IF endIndex is larger than the
length, an IndexOutOfBoundsException is thrown. 4. if beginIndex equals
endIndex, and both are within range, then an empty string is returned. Usually
when an exception is thrown your program halts.
Recall that control characters are bit patterns that indicate such things as the end
of a line or page separations. Other control characters represent the mechanical
activities of old communications equipment. The characters that a String object
contains can include control characters. Control character is embedded in the data
of the String. Although you do not see them in the output, the control characters
are part of the data in the String.
The temporary object is unused to construct a second object. A String is
constructed. Then a second String is constructed. A reference to the second String
is used a parameter for println( ). Both String objects are temporary. After println
( ) finishes, both Strings are garbage. There is nothing special about temporary
objects. What makes the temporary is how the program uses them . The objects in
the above statement are temporary because the program saves no reference to
them. The garbage collector will soon recycle them.
The starts With ( ) method tests if one String is the prefix of another. This is

frequently needed in programs. Sometimes a method of a String creates another


String, and then a method of that second String is invoked to create a third String.
This is sometimes called a cascade. Usually a cascade involves intermediate
temporary objects.
Programmers often forget that String objects are immutable. Once a Sting object
has been constructed it cannot be changed. This line code: str.substring (16);
creates a new object, containing a substring of the characters of the original
object. However m the original object is not changed. Since the reference variable
str continues to point to the original object, the new object immediately becomes
garbage. The next statement System.out.println (str); writes out the characters in
the original object.
A common mistake is to think change a string, but to them attempt to change an
immutable object. When you think change a string' you need to do two things: 1.
Computer a new String object. 2. Assign the reference to the new String to a
reference variable. The diagram shows how the second how the second version of
the program works. The reference variable str is first assigned a reference to the
original object. Then a new object is constructed by substring ( ). The new
reference is assigned to str. Then the println ( ) method is called with a new
reference so the new string it written.
The beginning character of a string corresponds to index 0 and the last character
corresponds to the index (length of string) -1. The length of a string is the number
of characters it contains, including spaces, punctuation and control characters. The
sequence \t stands for a single character, a tab character. Each tab character counts
as one character. Be careful about the difference between an empty string, and a
null reference. Any empty string is an object the contains no characters and has
length 0. A null reference means there is no object present.

There are two versions of substring. substring(int from) create a new object that
contains the characters of the method's string from index from to the end of the
string. Throws an IndexOutOfBoundsException if from is negative or larger that
the length of the string. Substring ( int from, int to) Create a new object that
contains the characters of the method's string from index from to index to -1.
Throws an IndexOutOfBoundsException if from is negative or if from is larger
than to. There are some tricky rules about the first version of the method: 1. If
from is exactly equal to the length of the original string, a substring is created, but
it contains no characters. 2. If from is greater than the length of the original string,
or a negative value, a IndexOutOfBoundsException is thrown. The parameter for
substring ( ) must be an integer literal like 0 or 12. substring ( int from, int to)
Create a new object that contains the characters of the method's string from index

from to index to -1. Throws an IndexOutOfBoundsException if from is negative


or if from is larger than to. There is a second version of substring ( ). 1. If from is
negative, an IndexOutOfBoundsException is thrown. If from is larger than to, an
IndexOutOfBoundsException is thrown. If to is larger than the length, an
IndexOutOfBoundsException is thrown. If from equals to, and both are intin
range then an empty string is returned. The rules make sense. If something can't
be done, Java throwns an exception.

There are four varieties of indexof () in the Java library. Indexof (string str)
returns the index of the first occurrence of str or -1 if str is not found.

Indexof ( ) and substring ( ) can be used to chop a string into useful pieces. Here is
a fragment that chops an assignment statement into the part to the left of the
assignment operator. The statement String newLine = line.substring ( spot + 1);
computes the tail of the original line, starting with the character after the first =
sign. The clause newLine.indexOf(=) >0 detects = anywhere but at the
beginning of this new line.

String Class 3.4


1. Which of the following is the correct code to create a string in Java? String greeting =
Hello!;
2. Given
String name Jerry;
Which of the following is the correct code to obtain the length (that is, number of
characters
in the string)? int len = name.length();
3. Given
String name Str1 = Jerry;
String name Str2 = Tom;
which of the following is the correct code to compare two strings?
NameStr1.equals(nameStr2)
4. A string that contains no characters is called an empty string. Which of the following
creates a
string referring to no object? String c=null;
5. What does the following code display?
String strA = Mary;
System.out.println(Hello + strA !);
Hello Mary !
Operator Notations 4.1
Operators are special symbols that allow us to perform certain actions on the
operands. By using these operators we can write expressions that can act on , two
or threes operands to perform a specific task. We have three Different styles of

operator notations based on where the operator is placed relative to its operands.
Infix Notation: In this type of notation, the operator is written in between the two
operands. The addition of two numbers, and 3 and 4 can be written as follows in
the infix notation 3 +4 The infix notation is most commonly used notation in
mathematics. A more complex example. Of parenthesized notation, is shown:
((1*2) + (3*4)) (95-6) + 7/8)). Here the operators are evaluated from left to right
with the operations within parentheses being evaluated first, followed by
multiplication, division, addition and subtraction. Prefix Notation: This is also
known as Polish notation. In this type of notation, the operators are written before
their operands. The operators are evaluated from let to right and they operate
upon their nearest two right operands. For example the addition of two numbers 3
and 4 can be written as follows in the prefix notation: + 3 4. Here the operator +
is written before 3 and 4 and acts on its immediate two operands on the right
(i.e, 3 and 4). A more complex example in prefix notation: - + 2 12 + - 5 6 / 8 8.
Next the - operator acts on 5 and 6 to result in a -1 and this followed by /
acting on 8 and 8 to result in a 1. At this point the expression looks as follows: - +
2 12 + -1 1. We have gone through a round of left to right evaluation, and now the
second round starts, as we still have operators to be resolved. Now the +
operator will act on 2 and 12 resulting in 14, and the other + will act on -1 and
1 results in 0. At this point the expression looks as follows: - 14 0. Finally, the last
round results in 14 as the answer for the evaluated expression. Postfix Notation:
This is also known as reversed Polish notation. In this notation, the operators are
written after their operands. As with prefix notation, the operands are evaluated
from left to right. An operator acts on its immediate two preceding operands. For
example the addition of the numbers 3 and 4 can be written as follows in postfix
notation: 3 4 +, Here the operator + is written after numbers ( 3 and 4) that
need to be added. A more complex example of postfix notation is shown below: 1
2 * 3 4 * + 5 6 8 8 / + - . As you are going from left to right, the * operator
will work on the numbers 1 and numbers 2, with a result of 2 replacing * 1 2.
Then the * operator will work on the numbers 3 and 4, with a result of 12
replacing * 3 4 . At this point the expression looks as follows: 2 12 + 5 6 8
8 / + - . Next the - operator acts on 5 and 6, resulting in a -1, and this is
followed by / acting on 8 and 8, resulting in a 1. At this point the expression
looks as follows: 2 12 + -1 1 + -. Now the + operator will act on 2 and 12,
resulting in 14, and the other + operator will act on -1 and 1, resulting in 0. At
this point the expression looks as follows: 14 0 - . Finally the last round results in
14 as the answer for the evaluated expression. As the infix notation is commonly
used in mathematics and is practices from very early on this style is most intuitive
and easy to understand. Most modern programming languages, including Java,
use infix notation for writing mathematical expressions. However, prefix is often
used for operators that take a single operand, such as logical negation (1) and
function calls. The postfix notation is similar to the infix, with operators following

the operands rather than preceding them. The use of postfix notation is not
common in any of the programming languages.
Relational Operators 4.2
The first step in learning to use a new programming language is usually to learn
the foundation concepts such as variable, operators, types, expressions, flow of
control, etc. Both Java and C== provide a set of operators that can be used to
perform an action on one or two operands. An operator that operates on one
operand is called a unary operator, and an operator that operates on two operands
is is called a binary operator. Some operators can behave either as a unary or as a
binary operator, the best known of which is probably the minus sign. As a binary
operator, the minus sign causes its right operand to be subtracted from its left
operand. As a unary operator, the minus sign causes the algebraic sign of the right
operand to be changed. As a unary operator, the minus causes the algebraic sign of
the right operand to be changed. In addition to the normal use of operators, C +
+ makes it possible to overland operators. This means that the programmer can
redefined the behavior of an operator with respect to objects of a new type defined
by that program. Java does not support operator overloading. In Java the plus sign
can be used to perform arithmetic addition. It can also be used to concatenate
strings. The operand on the right is automatically converted to a character string
before being concatenated on the left. The cast operator is used in this case to
purposely convert the integer value contained in the int variable ch2 to a character
type suitable for concatenating with the string on the left of the plus sign.
Otherwise, Java would attempt to convert the value of the int variable to a series
of digits representing the numeric value of the character since the character is
stored in a variable of type int. There are some other operators, such as the c++
scope resolution operator and the c++ and extraction operators, which do not
overlap the two languages. The plus sign is not automatically overloaded to
perform string concatenation in C++ ( but you can overload it if you want to). As
you might imagine many Java operators are also used in Pascal with the same
symbol to perform essentially the same operation. An extremely important unary
operator that is used in both Java and C== ( but does not exist in Pascal ) is the
increment operator ( ++) This operator is used in both prefix and postfix notation.
The increment operator causes the value of its operand to be increased by one.
The increment operator behaves differently when applied to pointer variables in C
++. Java does not support pointer variables. With the prefix version, the operand
appears to the right of the operator ( ++ X ) while with the postifx version, the
operand appears to the left of the operator ( X++). The difference in the prefix and
postfix has to do with the point in time that the increment actually occurs if the
operator and its operand appears as part of a larger overall expression. With the
prefix version the variable is incremented before it is used to evaluate the larger
overall expression. With the postfix version the variable is used to evaluate the

larger overall expression and then it is incremented. There is essentially not


difference in the behavior of the Java increment operator and the C ++ increment
operator, so a C ++ program is not shown for comparison. Binary operators use
infix notation which means that the operator appears between its operands. To
evaluate to a value means that after the action is performed the operator and its
operands are effectively replaced in the expression by the value that is returned.
The act of returning a value becomes much more obvious in C ++ where it is
possible to overload operators to specify their behavior relative to specific types
of operands. In this case the programmer actually writes a method or function
with a special name and argument list. When the program encounters the operator
and the specified types of operands, the function is called. The overloaded
operator function actually returns a value just like any other function or method.
Author divide Java's operators into the following categories: arithmetic, relational
and conditional, bitwise and logical, assignment. Both Java and C ++ support
various arithmetic operators on all floating point and integer numbers. C++ also
support arithmetic operators on objects of newly defined types through operaotr
overloading, but this capability is not supported by Java.
The following table lists the binary arithmetic operators supported by both Java and C+
+.
Operator Description
+
*
/
%

Adds its operands


Subtracts the right operand from the left
operand
Multiplies the operands
Divides the left operand by the right operand
Remainder of dividing the left operand by
the right operand

The plus operator is also used to concatenate strings as in the following code
fragment: MyVariable has a value of + MyVariable + in this program. This
operation also coerced the value of MyVariable to a string representation for use
in the expression only. The value stored in the variable is not modified in any
lasting way. String concatenation using the plus operator is not supported by C +
+. Rather a function named strcat ( ) can be used to concatenate two string. The
use of this function can be dangerous because there is no protection against
overwriting the bounds of the array that is used as the destination of the
concatenated string.

Both Java and C++ support the following unary arithmetic operators.
Operator Description
+
++
--

Indicates a positive value


Negates, or changes algebraic sign
Adds one to the operand,
both prefix and postfix
Subtracts one from operand,
both prefix and postfix

Java and C== support the same set of binary relational operators. Relational
operators in Java return wither true or false as a boolean type. Relational operators
in C ++ return an integer where the integer value of zero may be interpreted as
false and any one-zero value may be interpreted as true.

These Operators are also used in Pascal to perform similar operations.


Operator Returns true if
>
Left operand is greater than right operand
>=
Left operand is greater than or equal to
right operand
<
Left operand is less than right operand
<=
Left operand is less than or equal to
right operand
==
Left operand is equal to right operand
!=
Left operand is not equal to right operand

Relational operators are frequently used in the conditional expressions of control


statement such as if (LeftVariable <= RightVariable) The relational operators

are often combined with another set of operators ( referred to as conditional


operators in Java and referred to as logical operators in C ++) to construct more
complex expressions.
Both Java and C++ support three such operators as shown in the following table.
Operator Typical Use
Returns true if
&& Left && Right Left and Right are both true
|| Left || Right Either Left or Right is true
!
! Right
Right is false

With the exception of the manner in which true and false is maintained, the
operators behave the same in Java and C ++. However because of the difference,
the variety of ways that the operators are used in C ++ may be much greater than
in Java. In Java, the operands must be boolean types or must have been created
by evaluation of an expression that returns a boolean type. In C++ the operands
can be integer types, can be convertible to integer types, or can be created by any
expression that returns an integer type. In C++ a zero is typically placed in a
pointer variable to indicate that the pointer doesnt point to anything in particular.
This is often referred to as a null pointer. An important characteristic of the
behavior of the && and || operators in both Java and C ++ is that the expressions
are evaluated from left to right, and the evaluation of the expression is
terminated as soon as the result of evaluating the expression can be determined. If
the variable a is less that the variable b, there is not need to evaluate the right
operand of the || to determine the value of the entire expression. Evaluation will
terminate as soon as the answer can be determined. The & operator in Java is a
bitwise and while the | operator is a bitwise or. The & operator can be used as a
synonym for && and the | can be used as a synonym for || if both of the operands
are boolean. The evaluation of the expression is terminated until all operands
have been evaluated, thus eliminating the possible advantage of the left-to-right
evaluation. A common programming error in C++ is to use the & operator when
the logic requires the use of the && operator or to use the | operator when the
logic requires the use of the || operator . One of the operations supportive by Java
( >>>) is not supported by C++ and the behavior of some of the operations is not
always exactly the same between Java and C++.

These Java operators are summarized in the following table.

Operator Typical Use


>>

Operation

OpLeft >>

Dist
Shift bits of OpLeft right
by Dist bits (signed)
<<
OpLeft <<
Dist
Shift bits of OpLeft left
by Dist bits
>>>
OpLeft >>>
Dist Shift bits of OpLeft right
by Dist bits (unsigned)
&
OpLeft & OpRight
Bitwise and of the
two operands
|
OpLeft | OpRight
Bitwise inclusive or of the
two operands
^
OpLeft ^ OpRight
Bitwise exclusive or (xor) of
the two operands
~
~ OpRight
Bitwise complement of the right
operand (unary)
The signed right shift operation populates the vacated bits with the sign bit, while
the left shift and the unsigned right shift populated the vacated bits with zeros. C+
+ does not support the >>> operator is the concept of a signed right shift. In C ++
if the type of the value being shifted to the right is an unsigned type, the vacated
bits are populated by zeros. If the type is a signed type the vacated bits in a right
shift operations may be populated by either zeros or ones on a platform-dependent
basis. In a left shift operation vacated bits are populated by zeros. In all cases for
both Java and C ++, bits shifted off the end are lost. The bitwise and operation
operates according to the rule that the bitwise and operation of two 1 bits is a 1
bit. Any other combination results in a 0 bit. For the inclusive or if either bit is a
1, the result is a 1. Otherwise the result is a 0. For the exclusive or if either but not
both bits is a 1 the result is a 1. Otherwise the result is a 0. Another way to state
this is is the bits are different the result is a 1. If the two bits are the same the
result is a 0. The complement operator changes each 1 to a 0 and changes 0 to a
1. Just as in C== the (=) is a value assigning binary operator in Java. The value
stroed in memory and represented by the right operand is copied into the memory
represented by the left operand. Unlike C++, you cannot overload the assignment
operator ( or any other operator for that matter) in Java. You need to be careful
and think about what are doing when the assignment operator with reference
variables in Java. If you assign one reference variable to another you simply end
up with two reference variables the refer to the same object. You do not end up
with two different objects. If what you need is another copy of the object you can
use the clone () method to accomplish that. Also similar to C++, Java supports the
following list of shortcuts assignment operators. These operators allow you to
perform an assignment and another operation with a single operator. += -= *= /=

%= &= |= ^= <<= >>= >>>= The two statements that follow perform the same
operation x +=y; x= x+ y; the behavior of all the shortcut assignment operators
follow the same pattern. Note that C== does not support the >>>= operator,
because it doesnt support the >>> operator.
Logical Operators 4.3
Each part is a relational expression. A relational expression is a type of boolean
expression that uses a relational operator to compute a true or false value. The
symbol && means and . A boolean expression is often composed of smaller
boolean expressions. The role of the && ( and operator) between the two
relational expressions the && requires that both are true for the entire expression
to be true. The entire question must be true in order for the branch to execute. The
and operator && is a logical operator. A logical operator examines two true / false
values and outputs a single true / false value. The and operator requires that both
sides are true. If both sides are true the entire expression is true. If either side or
both are false the entire expression is false. Use and when every requirement must
be met. As soon as the first false is detected you know that the entire expression
must be false because false and anything is false. Java only evaluates an
expression as far as needed to determine the value of the entire expression. This
type of optimization is called short-circuit evaluation. The characters that follow
&& do not form a complete relational expression. The compiler would not accept
it. IF a boolean expression includes an assignment operator or method calls, then
the order does matter. The reason for this involves the short-circuit optimization.
Sometimes a program has if one or the other of the conditions has been met. The
symbol || means or. The OR operator evaluates to true when either qualification is
met or when both are met. The if statement asks a question with two parts: if
either part is true or both parts are true then the entire boolean expression is true.
The OR operator is used in a boolean expression to check that there is at least one
true. If both sides are true then entire expression is true. If just one side is true, the
entire expression is true. If both sides are false, the entire expression is false. The
OR operator is a logical operator because it combines two true/false values into a
single true/false value. This type of OR is called an inclusive OR because its
value is true for one or two values. This is called an exclusive or. Because true or
anything is true. Java only evaluates an expression only as far as needed to
determine its value. This type of optimization is called short-circuit evaluation.
AND is different for OR. All the values AND combines bust be true to get a true.
At lease one of the true OR combines must be true to get a true.

B A && B

A || B

F F

F T

T F

T T
T
T
Each row of the truth table shows how logical operators combine the true/ false
values of operands. All possible truth values of the operands A and B are listed in
the left columns. The NOT operator in Java is this : !. The Not operator changes
true to false and false to true, as seen in the truth table. The Not operator has high
precedence so it is done before arithmetic and relational operators unless you use
parentheses.
Boolean Expressions 4.3.1
1. Select a True or False for each set of radio buttons, then click on the "?" button to see
what the
AND of the two boolean values is. False + False = False ; True + True = True ; False
+ True
= True
2. In Java, the AND operation is requested using the operator &&
3. In Java, the OR operation is requested using the operator ll
4. Arithmetic operators (like *, +, -, /) have higher precedence that other operators (like
<,>,>=,&&, II), so arithmetic is done first.
5. Relational operators (like<, >, >= ,) have higher precedence that logical operators
(like &&, ll ),
so comparing numbers is done next. Since they have the lowest precedence the logical
operators act last.
6. 1+2 > 4-2 && 12 < 23 evaluates to true.
7. 1+2 > 4-2 ll 12 < 23 evaluates to true.
8. 1+2 > 4-2 && 12 > 23 evaluates to false.
9. 1+2 > 4-2 ll 12>23 evaluates to true.
Truth Tables 4.3.2

Truth tables are used to analyze boolean expressions, De Morgan's rules can
transform confusing boolean expressions in easier ones. Both of these techniques
are used in programming and in computer hardware design. A truth tables is
another way to show the evaluation of a boolean expression. Each row of a truth
table starts with a selection of truth values for the operands. These is one row for
each possible selection of truth values. The columns show the truth of expressions
and subexpressions containing the operands. Truth tables are usually organized by
putting the operands in a conventional order. This order helps prevent mistakes.
The convention order is easy to remember if you think of F as 0 and T as 1. A

truth table is another way to analyze the expression. The first two columns are
filled with the possible truths values of the relational expressions. Generally
people find statements the involve NOT to be confusing . Avoid using NOT is you
can. If Nots are need try to apply them to small expressions only. Usually if you
have an expression that uses a NOT operator, replace it with an equivalent
comparison that does not use a NOT. If this is not possible , rewrite the
expression so that the NOT applies to the smallest subexpression possible. August
DE Morgan was a nineteenth century British Mathematician who showed the
importance of several rules of logic. Two of these De Morgans Rules show how
the NOT operator can be moved to the inside of an expression. ( Although these
rules are named after De Morgan they were in fact known to Aristotle.)
De Morgan Rule: !(A || B) is equivalent to ! A && !B.
A

(A ||
B)

!(A || B)

!A

!B

!A && !B

De Morgan's rules can be extends to three operands: !(a && BB && CC) is = to !
A || !B || !C ; ! ( A || B || C ) is equivalent to ! A && !B && !C Expressions with
moe than three operands behave similarly.

Truth Tables and De Morgan's Rules 4.3.2


1. Complete the following truth table:
Operan
d

Operan
d

Expression

x <= y

y > 100

x <= y || y >
100

Decide from the table what the value of the expression is is when x == 150 and y ==
125.

2. Complete the following truth table:


Operan
d

Operan
d

Expression

ch >=
'a'

ch <=
'z'

ch >= 'a' && ch <=


'z'

Decide from the table what the value of the expression is is when ch == 'A'.

3. Complete the following truth table:


Operan
d

Operan
d

Operan
d

Subexpression

Expression

ch >=
'a'

ch <=
'z'

ch ==
'?'

ch >= 'a' && ch


<= 'z'

(ch >= 'a' && ch <= 'z') || ch


== '?'

Decide from the table what the value of the expression is is when ch == 'x'.

4. Is !A && B equivalent to A || !B ? Complete the table to find out.


Operan
d

Operan
d

Subexpressi
on

Subexpressi
on

Expressio
n

Expressio
n

!A

!B

!A && B

A || !B

The two expressions are equivalent if the T / F values in the last two columns are the
same.
Are the two columns the same?

No... they are opposites

Now use De Morgan's Rule:


!(A && B) is equivalent to !A || !B
to rewrite !( !A && B ).

A || !B

5. You wish to purchase a certificate of deposit, but only if the interest rate is greater
than three percent and the minimum deposit is less than 10000. Fill in the blanks.
>

&&

<

if ( interest
3
minimum
System.out.println("Buy this CD");
else
System.out.println("Reject this CD");

10000)

Rewrite the above fragment so that it fits the following.


<=

||

if ( interest
3
minimum
System.out.println("Reject this CD");
else
System.out.println("Buy this CD");

>

10000)

(The first program fragment is probably the best way to write this.)
6. A program is searching for books with a call number that starts "QA" published
between 1990 and 1995 (inclusive) with the word "web" in the title. Assume that the
attributes of a book are accessed by book.getTitle(), book.getDate(), and book.getCall().
Recall that indexOf( String sub ) returns the integer index of the substring, or -1 if the
substring is not found.
>=

if ( book.getCall().indexOf("QA")
book.getDate()

>=

1990

&&

&&

book.getDate()

<=

1995

&&

book.getTitle().indexOf("Web")

>=

0)

System.out.println( book.getCall(), book.getTitle() );


Introduction to Control Structures 5.1

When you compile and run a Java program, the HVM executes whatever is within
the main method. These instruction are carried out sequentially unless dictated
otherwise by the code itself, for example by using control structures, calling
methods or creating Objects. When you start programming in any language, it
can seem intuitive to think of a program as a series of instructions that are
executed in a linear fashion. When building applications, you will structure your
code in a number of different ways. IF your application allows user interaction
whatever code is executed will depend on what the user does at any point.
Whenever your programs use external input whether from user interaction or
where content comes from a database you need to tailor the behavior of your code
to suit the particular input that it receives. Imagine you have an application in
which series of products are being displayed the product details being pulled from
a database. Control structures dictate what the behavior of a program will be
under what circumstances. Control structures belong to one of two families: those
that test values and determine what code will be executed based on those values,
and those that loop, performing identical operations multiple times. Control
structures like if-then-else and switch the program to behave differently based on
the data that they are fed. The while and for loops allow you to repeat a block of
code as often as it is needed. As you can see, that functionality can be very useful
when designing complex programs. This unit will introduce you to control
structures and the ways in which they are used before moving on to discuss if,
switch, while/do-while, and for loops. We will also discuss some advanced topics,
such as nesting and scope. Another basic way to introduce a control structure to
your code is by using loops. You will often find when programing that you need to
carry out repetitive processing you can reduce of code you actually need to write
by using while or for loops. The code within this loop will execute as many times
as there are elements in the array. What happens when the instructions reach the
loop: The first time the loop is carried out, the value 0 is assigned to the i variable.
The test I <products.length is carried out returning a true or false value. If the test
returns true: the contained of the loop ( printing out the value at position I in the
array) is carried out; i++ is executed (I is incremented to keep track of how many

times the loop has executed); the is the re-entered the test carried out again to
see if I is still less than the length of the array. If the test returns false, the loop is
abandoned and whatever code lies after it is executed. A while loop can be used to
the same effect. intj=0; while(j); you will often find that you are carrying out the
same processing in more than one place within your program. When creating your
own methods like this, you have to decide what the type and number of
parameters are, what the return type is (int in this case, void if there is non), as
well as the content and name of the method ( try to make this meaningful but
concise if possible). You can then call the method passing it any other String array
and it will perform the same action with it.
Up to this point everything that we've covered involved simple linear execution of
every line of code. In most programming languages and if statement contains thre
parts. The first part is a keyword that tells the computer that it's an if statement
( some languages may have an equivalent structure that uses a different key
word0. The second part is a boolean expression. The third part is a statement or
group of statements. The wat that the computer executes an if statement is that,
first it evaluates the boolean expression. If the expression evaluates to false, it
skips the third part the statements completely as if they weren't even there. On the
other hand if the expression evaluates to true, then the statement are executed.
This is the style of while loop used in Java, C and C++. The code of the block is
delineated in this example by a matched pair of curly braces. The condition is
inside the parenthesis that follows immediately after the keyword while. The
sample while loop given above will execute nine times with the value of th
variable counter starting at one. With each iteration through the loop the value of
counter is incremented by one. When the value of counter reaches ten the
condition will evaluate to false and the loop will not be executed. With each
iteration, the program will print out the sum of the first N integers with N equal to
counter.
int fN = 0;
int fNplus1 = 1;
int counter = 0;
while (counter < 11)
{
fNplus2 = fN + fNplus1;
print fN;
fN = fNplus1;
fNplus1 = fNplus2;
counter += 1;
}

The while loop shown above is an example of a loop structure where the
condition is checked before the code is executed. This know as a precondition.
The block is not executed at all if the precondition is false when reaching the
loop. In java, C and C++ there is a structure that is called a do-while loop that is
nearly identical to a while loop, except that it uses a post-condition. Because the
condition is checked at the end of the loop, post condition loops are guaranteed to
execute at least once.
The if Statement 5.2
The words if and else are markers that divide the decision into two sections. The
else divides the true branch form the false branch. The if is followed by a question
enclosed in parentheses. The expression num<o asks if the value in num is less
than zero. The if statement always asks a question ( often about a variable). If the
answer is true only the truth 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. 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, just block).
There can be as many statements as you want in a block. A block can go any place
a single statement can go. All the statements in the true block are executed when
the answer to the question is true. All the statements in the flase block are
executed when the answer to the question is flase. The flase block consists of the
block that follows the else.
// statements that are executed before the decision
if(condition)
// true branch
else
//false branch
// statements that are executed after the branches join together again
The condition evaluates to true or false, often by comparing variable 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 block. The false branch can be
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 the
comparisons <,>, and so on. 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,
by the road always comes together again.
Relational Operators

Operator

Meaning

A == 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 ?
Expression 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 are compared. The operator for equal is == (two equal
signs in a row). The operator for not equal is != (exclamation point equal sign).
In an if statement, the true or false a boolean expression picks whether the true
branch or the false branch is executed. These is sometimes a nested if statement
because it is nested in a branch of an outer if statement.
Quiz on the If Statement 5.2
1. How many choices are possible when using a single if-else statement? 2
2. What does the following code fragment write to the monitor?
int sum = 14;
if ( sum < 20 )
System.out.print("Under ");
else
{
System.out.print("Over ");
System.out.println("the limit.");
}
Under
3. What does the following code fragment write to the monitor?
int sum = 7;
if ( sum > 20 )
{
System.out.print("You win ");
} else
{
System.out.print("You lose ");
}
System.out.println("the prize."); You lose the prize.
4. What does the following code fragment write to the monitor?

int sum = 21;


if ( sum != 20 )
System.out.print("You win ");
else
System.out.print("You lose ");
System.out.println("the prize."); You win the prize
5. Evaluate (to true or false ) each of the following expressions: 14<=14 true 14<14
false -9>-25
true -25>-9 false
Sometimes it is important to evaluate the value of an expression and perform a
task if the value comes out to be true and another task if it false. The if-else
structure can evaluate a Boolean expression and execute the statements in the if
block when the value is true, or the statements in the else block when the
value is false.
The 'Switch' Statement 5.3
Nested if and else statements can be used to choose between several options. An if
statement can be used to compute absolute values. This statement uses a
conditional operator. The right side of the = is a conditional expression. The
expression is evaluated to produce a value which is then assigned to the variable,
abs. The conditional operator is used in an expression. It asks for a value to be
computed but does not by itself change any variable. In the above example, the
variable value is not changed. Usually, an assignment operator is used to make a
change.
True-or-false-condition ? Value-if-true : value-is-false
The true-or-false-condition is true, the evaluate the expression between ? And: If
the true-or-false-condition is false, the evaluate the expression between: and the
end. The result of evaluation is the value of the entire conditional expression. The
expression evaluated to the maximum of two values. The condition a > b is false,
so. The part after the colon (:) is evaluated. The entire expression evaluates to that
value. Usually an expression is part of a longer statement that does something
with the value. The value of the conditional expression can be used with the
concatenation operator + in the println() statement. The subexpressions that make
up a conditional expression can be as complicated as you want. If you need to do
something more complicated do it with if-else statements. Often a program needs
to make a choice among several options based on the value of a single expression.
A choice is made between four potions based on the value is code. To execute the
switch statement, look down the list of cases to match the value in code.
Only one case is selected per execution of the switch statement. The value of
integerExpression determines which case is selected. IntegerExpression must

evaluate to an integer type(including char). Each label must be an integer literal,


but not an expression or variable. There can be any number of statements in a
statementList. The statementList is usually followed with a break; Each time the
switch statement is executed, the following happens: 1. The integerExpression is
evaluated. 2. The labels after each case are inspected one by one, starting with the
first. 3. The first label that matched has its statementList execute. 4. The
statements execute until the break statement is encountered. 5. Not the entire
switch statement is complete. If no case label matches the value of
integerExpression, then the default case is picked, and its statements execute.
There is one label per case statement , and there must be an exact match with the
expression in the switch for the case to be chosen. The break at the end of each
case is not always needed. If it is omitted then after the statements in the selected
case have executed, execution will continue with the following case. Often what
you really want it for several characters to select a single case. This can be done
using several case statements, followed by just one list of statements. The
program uses the charAt(int index) method of the String class. This method
returns a single character from a string. The charAt() method must be used here to
get a char that can be used in the switch. If you need to select among several
options based on complicated requirements, used nested if statements or if else if
statements.
Quiz of the Conditional Operator and the Switch Statement 5.3
1. What value is placed in var?
Var = 12 > 9 ? 0 : 1; 0
2. What value is placed in awk?
int x = 5, y = 19;
awk = y-x > x-y ? y-x : x-y ; 14
3. What value is placed in choice?
int a=5, b=10, c=15 ;
choice = a>b && a>c ? a : (b > c ? b : c) ; 15
4. What value is placed in sum?
double sum = 10.0, price=100;

sum += price>=100 ? price*1.1 : price; 120


5. Which statement makes sure that x is an even number? x += x%2 == 0 ? 0 : 1 ;
6. What value is assigned to discount ? 0.2
double discount;
char code = 'C' ;
switch ( code )
{
case 'A':
discount = 0.0;
break;
case 'B':
discount = 0.1;
break;
case 'C':
discount = 0.2;
break;
default:
discount = 0.3;
}
7. What value is assigned to discount ? 0.3
double discount;
char code = 'C' ;
switch ( code )
{
case 'A':
discount = 0.0;
case 'B':
discount = 0.1;
case 'C':
discount = 0.2;

default:
discount = 0.3;
}
8. What value is assigned to discount ? 0.3
double discount;
char code = 'X' ;
switch ( code )
{
case 'A':
discount = 0.0;
break;
case 'B':
discount = 0.1;
break;
case 'C':
discount = 0.2;
break;
default:
discount = 0.3;
}
9. What value is assigned to discount ? The program will not compile
because code is the wrong type.
double discount;
String code = "A" ;
switch ( code )
{
case 'A':
discount = 0.0;
break;
case 'B':
discount = 0.1;

break;
case 'C':
discount = 0.2;
break;
default:
discount = 0.3;
}
10. What value is assigned to discount ? 0.1
double discount;
char code = 'b' ;
switch ( code )
{
case 'a':
case 'A':
discount = 0.0;
break;
case 'b':
case 'B':
discount = 0.1;
break;
case 'c':
case 'C':
discount = 0.2;
break;
default:
discount = 0.3;
}
Sometimes it is better to use a switch statement when there are multiple choices to
choose from. Under such conditions an if-else structure can become very long and
at times difficult to comprehend. There is a limitation of the switch statement and
the similarity of the logic used for the if-else statement and switch statement ans
how they can be used alternately. The switch statement can only be used to
implement multi-way branches on the value of a single expression.

The while and the do-while loops 5.4


Most modern machines work by endlessly repeating the some motions. Computer
programs uses cycles also. In programming a cycle is called a loop. When a
program has a loop in it. Most computer programs execute many millions of
program statements each time they are used. Here is a program with a loop. It
contains a while statement, followed by a block of code. Count is set to one, then
it is tested by the while statement. If the test returns true so the statements in the
block following the while are executed. The current value of the count is printed,
and count is incremented. The execution goes back to the while statement and the
test is performed again. After the block has executed three times, count is four,
Execution goes back to the while statement, but now the test returns false, and
execution goes to the done with loop statement. Here is the syntax for the while
statement: while (condition) statement. The condition is a Boolean expression:
sometimes that evaluates to rue of false. The condition can be complicated, using
many relational operators and logical operators. The statement is a single
statement. However it can be and usually is a block statement containing several
other statements. The statement is sometimes called the loop body.
Varieties of while statements
while(condition) statement;
while(condition)
{
one or more statements
}
Since the statement can be a single statement or a block statement looks like
either choice in the table. Almost always thought a while statement is used with a
block. A style of indenting used here leads to fewer errors than alternative styles.
The statements controlled by the while are indented. The braces of the block are
aligned with each other and with the while and each is put on its own line. Here is
how the while statement works. In the following , the word controls means the
statement that is executing. When control reaches the while statement the
condition determines if the loop body is to be executed. When the condition is
true, the loop body is executed. After the loop body is executed, control is sent to
the while, which again evaluated the condition. When the condition is false, the
loop body is skipped. Control is sent to whatever statement follows the loop body.
Once execution has passed to the statement after the loop, the while statement is
finished, at least for now. If the condition is false the very first time it is evaluated
the loop body will not be executed even once. This loop uses the variable count.
The initial values must be set up correctly. The condition in the while statement
must be correct. The change in variable(s) must be done correctly. The variable
count is initialized, tested, and changed as the loop executes. It is an ordinary int

variable, but it is used in a special role. The role is that of a loop control variable.
Not all loops have loop control variables. The type of loop we have been looking
at is a counting loop since it counts upwars using the loop control variable as a
counter. You can make counting loops with statements other than the while
statement, and not while loops are counting loops.

Blank Exercise for Loops and the While Statement 5.4


1. When a mechanical machine repeatedly does something in performing its work it
contains a
a

loop

cycle

. When a program repeatedly executes the same statements it contains

2. Fill in the following blanks to show the syntax of a while statement:


while (

condition

statement

3. The statement immediately following the while is called the


block statement

loop body

It can be a

by including several statements between braces { and }.

4. What three things must be coordinated in order for a loop to run correctly?
1. The

initial values

2. The

condition

3. The

must be set up correctly.

in the while statement must be correct.

change in variable

in the loop body must be correct.

5. The condition of the while must evaluate to


executes.

true

each time before the loop body

6. An variable (usually an int) that is used to control how a loop works is called
a

loop control variable

7. The following program is supposed to write out the integers 1, 2, 3, and 4. Decide
what should go in the blanks.
class Counter
{
public static void main (String[] args)
{

int count ;
1

count =

;
<=

while ( count
4)
{
System.out.println( count );
1

count = count +

}
}
}
8. The following program is supposed to write out the integers 10, 11, 12, 13, 14, and
15. Decide what should go in the blanks.
class Counter2
{
public static void main (String[] args)
{
int j ;
j=

10

;
16

while ( j <
)
{
System.out.println( j );
1

j=j+

}
}
}
9. The following program is supposed to write out the integers 0, 2, 4, 6. Decide what
should go in the blanks.
class Counter3
{
public static void main (String[] args)
{
int j ;
j=

while ( j <=

{
System.out.println( j );
j=j+

}
}
}
10. The following program is supposed to write out the integers 2, 1, 0, -1 . Decide
what should go in the blanks.
class Counter3
{
public static void main (String[] args)
{
int count ;
count =

;
-1

while ( count >=


)
{
System.out.println( count );
count = count -

}
}
}

A programming language needs to have only one general looping method . In Java
the while statement can be used to implement any type of loop. However as we
have seen. The for statement is very convenient. The do loop is occasionally
convenient. The do statement is similar to the while statement with an important
difference: the do statement performs a test after each execution of the loop body.
Notice how the do and the while bracket the statements that form the loop body.
The statements in the loop body are executed. The the condition after the while is
tested. It if is true the loop body is executed again. Otherwise control passes to the
statement after the test. All loops must do three things: The loop must be
initialized correctly. The ending condition must be tested correctly. The body of
the loop must change the condition that is tested. The code fragment include all
three. But in a different order than usual. The ending condition test is done after
the loop body has executed. Loops with the test at the top of the loop (while and
for loops) are called top-driven loops. Loops implemented with the test at the

bottom ( a do loop) are called bottom-driven loops. Since testing is done at the
bottom of the loop. The loop body must be execute at least once regardless of
conditions. Java does not look ahead to the condition that is tested. It executes the
loop body then tests the condition to see if it should execute it again. You will
save hours of hair-tearing debugging time if you remember that The body of a do
loop is always executed at lease once. Almost always there are situations where a
loop body should not execute not even once. Because of this s do loop is almost
always not the appropriate choice. The for loop version also seems awkward. You
have to remember that the change part of the for statement can be omitted. This is
correct syntax but now you must be careful to make the change in the loop body.
Since any one choice is all we need, the OR operation is the appropriate way to
combine the choices.
Quiz on the do Statement 5.4
1. What does the following print? 0 1 2 3 4 5
int count = 0;
do
{
System.out.print( count +" ");
count++ ;
}
while ( count < 6 );
2. What does the following print? 10
int count = 10;
do
{
System.out.print( count +" ");
count++ ;
}
while ( count < 6 );
3. What does the following print? 10 9 8 7 6 5
int count = 10;
do
{
System.out.print( count +" ");
count-- ;

}
while ( count >= 5 );
4. What does the following print?
int row = 1;
do
{
int col = 1;
do
{
System.out.print( "*" );
col++ ;
}
while ( col <= 5 );
System.out.println();
row++ ;
}
while ( row <= 3 );
*****
*****
*****
5. What does the following print?
int row = 1;
do
{
int col = 1;
do
{
System.out.print( "*" );
col++ ;
}
while ( col <= row );
System.out.println();
row++ ;
}
while ( row <= 3 );

*
**
***
6.

What type of loop is implemented with a do statement? Bottom-driven loop

7. Is the do statement a necessary feature in Java? No everything it does could be


done with a while.
8. What are the branching statements in a programming language? Statements like
if that makes choices.
9. What fact about a do loop is responsible for many program bugs? The body of a
do loop is always executed at least once.
10. Examine the following code fragment:
int j = 1;
do
{
System.out.println( j );
j++ ;
}
while ( j <= 3 );
Which of the following for loops does the same thing? For (int j=1; j<=3; j++)
System.out.println(j);
Control Structures Programming 5.4
Guide to Responding to the Control Structures Programming Activity
Define five integer type variables, each to hold a temperature of a weekday, and a
double type variable to hold the average temperature. For example,
int tempM, tempT, tempW, tempR, tempF;
double average;
Define another variable to hold the option of the user, either Y (continue to calculate
the average of another week) or N (quit the program).
char option;
Use the Java Scanner class to get input from the keyboard.
import java.util.Scanner;
Scanner input = new Scanner(System.in);
For integers, use
tempM = input.nextInt();
For characters, use
option = input.nextLine().charAt(0);
Use if-else structure:

if (average > 100)


...
else if (average < 0)
...
and do-while structure
do
{
...
} while (option == Y)
Sample Solution
import java.util.Scanner
public class AverageTemperature
{
public static void main (string args[ ])
{
int tempM, tempT, tempW, tempR, tempF;
double average;
char repeat;
Scanner input = new Scanner(System.in);
do
{
System.out.print(Enter temperature of Monday: );
tempM = input.nextlnt();
System.out.print(Enter temperature of Tuesday: );
tempT = input.nextlnt();
System.out.print(Enter temperature of Wednesday: );
tempW = input.nextlnt();
System.out.print(Enter temperature of Thursday: );
tempR = input.nextlnt();
System.out.print(Enter temperature of Friday: );
tempF = input.nextlnt();
average = (tempM + tempT + tempW + tempR + tempF) / 5.0;
System.out.println(The average temperature this week is + average);
if (average > 100)
System.out.println(Its so hot!);
else if (average < 0)
System.out.println(Its so cold!);
System.out.println(Enter Y to continue or N to quit);
option = input.nextLine().charAt(0);
} while (option == Y)
}
}

'In a do-while loop, the body of the loop is executed at least one time, whereas in
a while loop, the loop may never execute if the loop condition is false. They both
are essentially the same except that the while loop is a pre-test loop and may
never execute if the condition is false to begin with. On the other hand, the dowhile loop is a post-test loop and always executes at least one time, even if the
condition is false.

The 'for' Loop 5.5


Counting loop uses a loop control variable to count upwards or downwards
( usually by an integer increment.) sentinel-controlled loop keeps going until a
special value is encountered in the data. Result-controlled loop keeps going until a
test determines that the desired result has been achieved. Each type of loop can
be built using the while along with other statements. There are three things ( in
each of the three types of loops) that must be done correctly: 1. The loop must be
initialized. 2. A condition must be tested. 3. The loop body must change
something that is tested. Overlooking one of these aspects results in a defective
loop. Usually each of these aspects is found in a different place in a program.
Java has a for statement which combines all three aspects of a loop. for(initialize;
test; change) loopBody; The initialize test and change are expressions that usually
perform the name action. The loopBody can be a single statement or a block
statement. It does the same thing as this loop built using a while statement. The
variable count in both loops id the loop control variable. ( A loop control variable
is an ordinary variable used to control the actions of a looping structure. )
Remember that count ++ has the same effect as count=count +1. The for
statement can be used to implement any of the three types of loops. The three
parts, initialized, text, and change can be as complicated as you want. Here is a for
loop with several statements in the loop body. Since the loop body consists of
several statements that are enclosed in braces { and } to make a block. The test is
performed every time, just before execution is about to enter the loop body. The
change is performed at the bottom of the loop body. Just before the test is reevaluated. Loops that work this way are top-driven loops and are usually
mentally easier to deal with than other arrangements. The change part can be
complicated, if you want. It is best to keep it small and understandable. Count+=
2 adds the value 2 to the variable count. The change to count is done wt the
bottom of the loop body. This means that the last value that counts gets is the first
one that fails the test count < 7. This is the value count will have just outside the
loop body. Parts of a for can be omitted. Since the three parts of a for are the three
parts of any loop; when a part is eliminated from a for it has to be made up
elsewhere. Recall that the for is equivalent to a while. You can omit the initialize
part from the for loop. It now acts the same as a while loop with its initialize part
omitted. Doing this is useful when initialization is complicated and you wish to do

it in several statements before the loop.


Sentinel controlled loop the change part depends on data from the user. It is
awkward to do this inside a for statement. So the change part is omitted from the
for statement and put in a convenient location. When the test part of a for is
omitted it is as if the value true were put in its place. So, for (initialize; ; change)
loopBody; is the same as for(initialize; true; change) loopBody; This is done for
compatibility with the language C. The phrase for( ; ; ) is the same while (true).
Sometimes people do this although it is not very clear and should be avoided.
Quiz on For Loops 5.5
1. What are the three general types of looping structures? Counting loop, sentinelcontrolled loop, and result-controlled loop.
2. What is the output of the following program fragment?
Int j;
for ( j=0; j<5; j++)
{
System.out.print(j+ );
}
System.out.println( );
0,1,2,3,4
3. What is the output of the following code fragment?
Int j;
for(j=10;j>5; j)
{
System.out.print(j+ );
}
System.out.println ( ) ;
10, 9 , 8 , 7, 6
4. What must the test be so that the following fragment prints out the integers 5
through and including 15?
int j;
for( j=5; j<16; j++)
{
System.out.print(j+ );
}
System.out.println ( ) ;
5. What must the change be so that the following fragment prints out the even
integers 0 2 4 6 8 10?
int j;
for(j=0; j<=10; j=j+2)
System.out.print(j+ );
System.out.println( );

6. What must the initialization be so that the following fragment prints out the
integers -3 -2 -1?
int j;
for(j=-3 ; j<0; j++ )
System.out.print(j+ );
System.out.println ( );
7. What is the output of the following code fragment?
Int j ;
for( j=5; j>-5; j)
System.out.print( j+ );
Sysyem.out.println( );
5 4 3 2 1 0 -1 -2 -3 -4
8. What is the output of the following code fragment?
Int count=0
for( ; count<9; ++count)
System.out.print( count + );
System.out.println( );
012345678
9. What is the output of the following code fragment?
Int count;
for( count = 0; count <9;)
{
System.out.print( count + );
count ++;
}
System.out.println( );
012345678
10. What is the output of the following code fragment?
Int j;
for(j=0; j<5;)
{
System.out.print(j+ );
j++;
}
System.out.println( );
01234
The for is a useful and frequently used statement. The loop control variable count
has been declares somewhere in the program. Possibly many statements away
from the for statement. This violates the idea that all the parts of the loop are
combined in one statement. It would be nice if the declaration of count were part
of the for statement. In fact this can be done, as in the following: for( int count=0;

count<10; count++) System.out.print(count + ); In this example the declaration


of count and its initialization have been combined. A variable declared in a for
statement can only be used in that statement and the body of the loop. Since the
println() statement is not part of the loop body, count cannot be used here. The
compiler will complain that is cannot find the symbol: count when it sees this
count. The scope of a variable is the span of statements where it can be used. The
scope of a variable declared as part of a for statement is the statement and its loop
body. A loop control variable as part of a for statement can only be seen by the for
statement and the statements of that loop body. Other for statements might use the
same identifier ( the same name) in declaring their loop control variable, but each
of there is a different variable which can be seen only by its own loop. The two
loops work correctly and don't interfere with each other, even though each one has
its own variable named j. It is best to keep sections of code self contained. To use
the drawline( ) method, the endpoints of the need to be positive integers and we
want the graph to fill the drawing area. Declaring the loop control variable as part
of the for statement. The scope of a variable declared in a for statement. Floating
point loop control variable.
Quiz on Further For Loops 5.4
1. Pick the for loop which duplicates this while loop:
int x = 0;
while ( x < 500 )
{
System.out.println( x );
x = x + 5;
}
for ( int x = 0; x < 500; x+=5 )
System.out.println( x );
2. Pick the for loop which duplicates this while loop:
double x = 0.0;
while ( x < 100.0 )
{
System.out.println( x );
x += 0.1;
}
double x;

for ( x = 0.0; x < 100.0; x += 0.1 )


System.out.println( x );
3. Pick the for loop which duplicates this while loop:
int sum = 0 ;
int j = -5 ;
while ( sum <= 350 )
{
sum += j ;
j += 5 ;
}
int sum = 0;
for ( int j = -5; sum <= 350; j += 5 )
{
sum += j ;
}
4. What must the test be so that the following fragment prints out the integers -5 up
to and including 5?
for ( int j = -5; ________ ; j++ )
{
System.out.print( j + " " );
}
System.out.println( );
j<=5
5. Fill the blank so that the following fragment prints out values close to 0.2, 0.4,
0.6, 0.8, 1.0,
for ( int j = 2; j <= 10; j+=2 )
System.out.print( __________ + ", " );
System.out.println( ); j/10.0
6. Fill the blank so that the following two loops are equivalent: int count = 10

int sum = 0;
for ( _______; count <=
25; count++ )
sum += count;

int sum = 0;
int count = 10;
while ( count <= 25 )
{
sum += count;
count++;
}

7. What does the following print on the monitor?


for ( int j = 0; j < 5; j++ )
{
for ( int k = 0; k < 10 ; k++ )
System.out.print( "*" );
System.out.println( );
}
**********
**********
**********
**********
**********
8. What is the output of the following code fragment? 0 1 2 3 4 5 6 7 8 9
for ( int count=0; count <= 9; ++count )
System.out.print( count + " " );
System.out.println( );
9. What is the output of the following code fragment? 0 2 4 6 8 10 12 14 16 18 20
for ( int count = 0; count <= 20; count+=2 )
System.out.print( count + " " );
System.out.println( );
10. Fill in the blank so that the following adds up the odd numbers from 1 to 99

int sum = 0;
for ( int num = 1; num <=99; __________ )
sum += num;
System.out.println( sum ); num+=2
Advanced Topics 5.6
In the loop body, the current value of count is always added to the sum of all
integers. The loop body shows that the current value of count is always added to
sumAll. An if statement determines if count is added to sumEven or sumOdd. An
if statement that is part of a loop body is a nested if. ( another type of nested if is
when an if statement is part of another if statement.) The loop body in this
program contains an if statement. This is fine. An if statement inside of a loop
body is called a nested if. There is nothing special about it, it works just as it
would outside of the loop body.
Here is the definition of N factorial: N Factorial ==N! ==N * (N-1) * (N-2) * (N3) ....4 * 3* 2 *1 N must be a positive integer of zero and 0! is defined to be 1.
example: 6! == 6 * 5* 4 * 3 * 2 * 1== 720. Another problem with double is that
the result is only an approximation to the exact value. Doubles have the
equivalent of about 15 decimal digits of accuracy. Often math formulas use
factorial, but explicit calculation of factorial can be avoided by rearranging the
operations of the formula. Avoid explicit calculation of factorial. For example the
number of arrangements that can be made of r objects selected from n objects is n!
/ (n-r)!.
Gravity pulls upon the brick, causing it to go faster and faster. The distance
between the brick and where it was released after t seconds is:
distance=(1/2)*G*t2 T is the number of seconds sine the brick was released. G is
a constant: 9.80665 Distance is in meters. For maximum accuracy the loop
control variable should be an integer type.
Advance Topics 5.6

1. When an if-else is contained inside of a loop body, the if-else statement is called
a

nested

if.

2. Fill in the blanks so that the boolean expression is true when num is
ODD: ( num

== 1 )

3. Fill in the blanks in the following 5! ==

4. The following program is supposed to calculate 1*2*3*4*5*6*7*8*9*10 . Fill in the


blanks.
class Factorial
{
public static void main (String[] args)
{
int fact =

; // current factorial value


1

int count =
while ( count
{

fact = fact *

;// loop control


<=

10 )

count

System.out.println( count +"! is " + fact );


count = count +

}
}
}

5. The following program asks the user for two integers, X and Y and then adds up all
the integers (inclusive) between them. Fill in the blanks.
class AddRange
{
public static void main (String[] args)
{
Scanner scan = new Scanner(
int sum =

System.in

; // current sum

);

System.out.println("Enter start of range:");


nextInt()

int start = scan.

System.out.println("Enter end of range:");


int end = scan.
int count =

nextInt()

start

while ( count
{

<=

sum = sum +
count = count +

end )
count
1

;
;

}
System.out.println("sum is:" + sum);
}
}
Variable Scope within a Control Structure 5.6.2
The six control structures are, the block. The while loop, the do... while loop, the
for loop. The if statement, and the switch statement. Each of these structures is
considered to be a single statement, but each is in fact a structured statement
that can contain one or more other statements inside itself. The block is the
simplest type of structures statement. Block is the simplest types of structured
statement. Its purpose is simply to group a sequence of statements into a single
statement. It consists of a sequence of statements enclosed between a pair of
braces, { and }. In fact is is possible for a block to contain no statements at
all; such a block is called an empty block and can actually be useful at times. An
empty block consists of nothing but an empty pair of braces. Block statements
usually occur inside other statements where their purpose is to group together
several statements into a unit. In the case of main subroutine of a program the
definition of a subroutine is a block since it is a sequence of statements enclosed
inside a pair of braces.
Java is a free-format language. There are no syntax rules about how the language
has to be arranged on a page. You can write an entire block on one line if you
want . But as a matter of good programming style you should lay out your

program on the page in a way that will make its structure as clear as possible. It is
good style to declare a variable inside a block if that variable is used nowhere else
but inside the block. A variable declared inside a block is completely inaccessible
and invisible from outside that block. When the computer executes the variable
declaration statement it allocates memory to hold the value of the variable. When
the block ends that memory is discarded. The variable is said to be local to the
block. The scope of an identifier is the part of the program in which that identifier
is valid. The scope of a variable defined inside a block is limited to that block.
The block statement by itself really doesn't affect the flow of control in a program.
The five remaining control structures do. They can be divided into two classes:
loop statements and branching statements. You really just need one control
structure from each category in order to have a completely general-purpose
programming language.
A while loop is used to repeat a given statement over and over. Its not likely that
you would want to keep repeating it forever. ; that would be an infinite loop. A
while loop has the form: while (Boolean-expression) statement. Since the
statement can be and usually is a block many while loops have the form: While
(Boolean-expression) { statements }. When the computer comes to a while
statement, it evaluates the Boolean-expression which yields either true or false as
the value. If the false the computer skips over the rest of the while loop and
proceeds to the next command in the program. If the value of the expression is
true, the computer executes the statement or block of statements inside the loop.
Then it returns to the beginning of the while loop and repeats the process. That is
it re-evaluates the boolean=expression, end the loop if the value is false, and
continues it if the value is true. This will continue over and over until the value of
the expression is false; if that never happens then there will be an infinite loop.
If statement tells the computer to take one of two alternative courses of action,
depending on whether the value of a given boolean-valued expression is true or
false. It is an example of on whether the value of a given boolean=valued
expression is true or false. It is an example of a branching or decision statement.
An if statement has the form:
if( boolean-expression )statement else statement
When the computer executes an if statement. It evaluates the boolean expression.
In many caese you want the computer to choose between doing something and not
doing it. You can do this with an if statement that omits the else part:
if (boolean-expression) statement
Method Syntax in Java 6.1
In addition to the methods predefined in Java we can write user-defined methods.
Methods are the interface to communications between program components; they
provide a way to invoke the same operation form many places in your program,

avoiding code repetition; They hide implementation details for the component
using the method; Variables defined within a method are not visible to users of the
method, they have a local scope within the method; The method cannot see
variables in the component that calls it either. There is logical separation between
the two which avoids variable name conflicts. Scope of local variables, the only
kind we've seen so far is defined by additional rules. And there are other kinds of
variable, with their own scope rules. Local Variables in a method or block exist
from point of definition to end of block; blocks are defined by curly braces{};
blocks are most often used to define: method body; multiple statements in if-else
and loop operations. Local variables are very restricted: Other methods cannot see
local variables even in the same class. Variables of the same name in different
methods are different variables. More generally variables of the same name in
different blocks are different variables. Arguments to a method are local variables:
The method copies them upon receipt and they love until the ending curly brace
of the method.
A method must have a name but may not have parameters and return type. The
parameter list contains variables that receiver values for the caller. There variables
are local to the method. Method parameter are also referred to as arguments when
that are substituted with specific values during the method call. Some methods do
not return any value, while others return a value of certain data type. A method
that does not return a value uses the keyboard void in the method signature. The
scope of a variable refers to where the value of the variable is accessible or valid.
A variable declared inside a method is only available in that method. The values
of variables declared as parameter of a method are valid only inside that method
as well.
Overloaded Methods 6.2
Typical method declarations
public double calculateAnswer ( double wingSpan, int numberOfEngines, double
length, double grossTons){
// do the calculation here
}
The only required elements of a method declaration are the method's return type,
name, a pair of parentheses, (), and a body between braces{}. Method declarations
have six components in order: 1. Modifier- such as public, private, and others you
will learn about later. 2. The return type-that data type of the value returned by the
method, or void if the method does not return a value. 3. The method name- the
rules for field names apply to method names as well, but the convention is a little
different. 4. The parameter list in parenthesis comma-delimited list of input
parameters, preceded by their data types, enclosed by parentheses. () If there are
no parameters, you must use empty parentheses. 5. An exception list to be

discussed later. 6. The method body, enclosed between braces the method's
code, including the declaration of local variables, goes here. Two of the
components of a method declaration comprise the method's name and the
parameter types.
The signature of the method declared above is: calaculateAnswer( double, int,
double, double)
Although a method name can be any legal identifier, code conventions restrict
method names. Method names should be a verb in lowercase or a mult-word name
that begins with a verb in lowercase, followed by adjectives,nouns,etc. In multiword names the first letter of each of the second and following words should be
capitalized. Such as the examples: run, runFast, getBackground, getFinalData,
compareTo, setX, isEmpty. A method has a unique name within its class.
However, a method might have the same name as other methods due to method
overloading.
The Java programming language supports overloading methods, and Java can
distinguish between methods with different method signatures. Methods within a
class can have the same name if they have different parameter lists. Class that can
use calligraphy to draw various types of data ( strings, integers, and so on) and
that contains a method for drawing each data type. It is cumbersome to use a new
name for each method, drawString, drawInteger, drawFloat, and so on. In the Java
programming language, you can use the same name for all the drawing methods
but pass a different argument list to each method. The data drawing class might
declare four methods name draw, each of which has a different parameter list.
Overloaded methods are differentiated by the number and type of the arguments
passed into the method. In this code sample. Draw (String s) and draw (int I) are
distinct and unique methods because they require different argument types. You
cannot declare more than one method with the same name and the same number
and type of arguments. Because the compiler cannot tell them apart. The compiler
does not consider return type when differentiating methods, so you cannot declare
two methods with the same signature even if they have different return type.
1. The state of an object consists of the data it holds in its instance variables.
Instance variables hold their values until they are explicitly changed or until the
object is destroyed. An object's methods frequently work with other values that
are not held in instance variables. The values are help in local variables and
parameters. The parameter amount is used by a caller to send a value to the
method. This is called passing a value to the method. Then the method finishes
and control returns to main (). The object has been changed. An identifier is a
name used for a class a variable, a method or a parameter. The following
definitions are useful: formal parameter the identifier used in a method to stand
for the value that is passed into the method by a caller. Actual parameter the
actual value that is passed into the method by a caller. Actual parameters are often
called arguments. When a method is called the formal parameter is temporarily

bound to the actual parameter. The method uses the formal parameter to stand
for the actual value that the caller wants to be used. Formal parameters are bound
to an actual value only as long as their method is active. When a method returns to
its caller, the formal parameters no longer contain any values. Then cannot be
used to store the state of an object. The formal parameters of a method can be
seen only by the statements of their own method. This means that if a method tries
own method. If a method tries to use a parameter of some other method, the
compiler will find a syntax error. The scope of a formal parameter is the section
of code that can see the parameter is the section of code that can see the
parameter. The scope of a formal parameter is the body of its method. A method'
statements can see the instance variables of their object. They cannot see the
parameters and local variables of other methods. Two methods are using the same
identifier for the different formal parameters. Each method has its own formal
parameter completely separate for the other method. The scopes of the two
parameters do not overload is the statements in one method cannot see the
formal parameter of the other method. The scope of the formal parameter of the
other method does not include this statement. The formal parameters of any one
method must all have different names. It is like being surrounded by a box of
one-way glass. A method can see local variables and parameters that are inside
the box. A method can look out through the glass that surrounds it. But no outsider
can see into the box. A parameter is a one-way message that the caller uses to
send values to a method. The body of a method a parameter is used just like any
variable. It can be used in arithmetic expressions, in assignment statements and so
on. Changes made to the parameter do not have any effect outside the method
body. A parameter is a local copy of whatever value the caller passed into the
method. Any changes made to it affect only this local copy. A local variable is a
variable that is declared inside of the body of a method. It can be seen only by the
statements that follow its declaration inside of that method. The scope of a local
variable starts where it is declared and ends at the end of the block that it is in.
Recall that a clock is a group of statements inside of braces {}. The local variable
charge is used to hold a temporary value while something is being calculated.
Local variables are not used to hold the permanent values of an object's state.
They have a value only during the brief amount of time a method is active. The
scope of the formal parameter amount overlaps the scope of the local variable,
also with the same name) so this is a mistake. Although it is usually a bad idea
you can declare a formal parameter or a variable with the same name as one of the
instances. This is not a syntax error although it will probably result in a logic
error a bug. The compiler will compile this code without complaint. The scope
of this variable starts with its declaration and ends at the end of the block. The
next statement uses the local variable, not the instance variable. When this
modified method is called it will add amount to the local variable balance and
then return to the caller the local variable will not longer hold a value after the

method has returned. The instance variable will not have been changed. It is
almost always a mistake to us the same name for an instance variable and for a
local variable. It is not a syntax error, so the compiler will not warn you of
impending doom. Overloading is when two or more methods of a class have the
same name but have different parameter lists When a method is called the correct
method is picked by matching the actual parameters in the call to the formal
parameter lists od the methods. Another uses of the term overloading is when an
operator calls for different operations depending on its operands. For example +
can mean integer addition, floating point addition, or string concatenation
depending on its operands. When several methods have the same name only one
is picked by a method call. The types of the actual parameters in a method call
are matched with the types is the formal parameters of the methods. If an exact
match cannot be made then the actual parameters care converted types that match
the formal parameters if this can be done without potential loss of information.
Because the number and types of the actual parameters matched the number and
types of the formal parameters. The signature of a method is: Its name; The
number and types of its parameters in order. The signatures is the methods in a
class must be unique. The return type is not part of the signature. The visibility
modifier is not part of the signature. The names of the formal parameters are not
part of the signature nor is the return type. It might seem strange that the return
type is not part of the signature. Potentially confusing situation is avoided by
keeping the return type out of the signature. Either method matches the statement,
since both have and int parameter and both return a type that can be converted to
double. ( Both int and float can be converted to double.) To avoid confusion in
situations like this the return type is not counted as part of the signature.
Method overloading means two or more methods have the same name but have
different parameter lists: either different number os parameters ot different
parameter lists: either different number parameters or different types of
parameters. When a method is called the corresponding method is invoked by
matching the arguments in the call to the parameter list of the methods. When a
method is called the corresponding method is invoked by matching the arguments
in the call to the parameter lists of the methods. The name together with the
number and type of the parameter list of a method is called the signature of a
method. The return type itself is not part of the signature of a method.

Signature of a Method Assessment 6.2.2


1. In the following program skeleton, click on each button where it would be correct to
have the statement: target = 25

In other words, click on each button where the variable target is in scope.
class ScopeEg1
{
int target;
ScopeEg1()
{
target = 25;

....
}
void aMethod()
{
target = 25;

....
}
void bMethod()
{
target = 25;

....
}
}
class AnotherClass
{
int sum;
AnotherClass()
{
OUT OF SCOPE

....
}
void anotherMethod()
{
OUT OF SCOPE

....

}
void someMethod()
{
OUT OF SCOPE

....
}
}
class TesterClass
{
public static void main (String[] args )
{
OUT OF SCOPE

}
}
"Outsiders" can access instance variables of an object using "dot notation" unless
the instance variable is private (or has default access and is in a different package...but
ignore this for now.)
2. In the following program skeleton, click on each button where it would be OK to
have the statement:target = 25;
class ScopeEg2
{
int target;
....
}
class AnotherClass
{
int sum;
ScopeEg2 first = new ScopeEg2() ;
void anotherMethod()
{
first .

target = 25;

....
}
void someMethod()
{
first .

target = 25;

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

first is OUT OF SCOPE

}
}
3. In the following program skeleton, click on each button where it would be OK to
have the statementtarget = 25
class ScopeEg3
{
private int target;
ScopeEg3()
{
target = 25;

....
}
void aMethod()
{
target = 25;

....
}

void bMethod()
{
target = 25;

....
}
....
}
class AnotherClass
{
int sum;
ScopeEg3 first = new ScopeEg3() ;
void anotherMethod()
{
first .

NOT VISIBLE

....
}
void someMethod()
{
first .

NOT VISIBLE

....
}
}
class TesterClass
{
public static void main (String[] args )
{
ScopeEg3 second = new ScopeEg3() ;
second .
}
}

NOT VISIBLE

Formal parameters can only be seen by the body of their own method.
4. Click on each button where it would be OK to have the
statement System.out.println( data );
class SomeClass
{
int sum;
void aMethod( int data )
{
System.out.println( data );

....
}
void bMethod()
{
OUT OF SCOPE

....
}
}
class TesterClass
{
SomeClass some;
public static void main (String[] args )
{
some = new SomeClass();
some.aMethod( 99 );
OUT OF SCOPE

}
}

It is OK for formal parameters in two different methods to use the same identifier.
5. In the following program skeleton, click on each button where it would be OK to
have the statementsum = data ;
class SomeClass
{
int sum;
void aMethod( int data )
{
sum = data;

....
}
void bMethod( int data )
{
sum = data;

....
}
void cMethod( int value )
{
data is OUT OF SCOPE

....
}
}
A local variable can only be seen in the body of its method by
statements following its declaration. It is OK for local variables in different
methods to use the same name.
6. Click on each button where it would be OK to have the statement value = 5;
class SomeOtherClass

{
int sum;
void aMethod( int data )
{
int value;
value = 5;

....
}
void bMethod( int data )
{
value is OUT OF SCOPE

....
}
void cMethod( )
{
....
value is OUT OF SCOPE

int value;
....
}
void dMethod( )
{
double value;
value = 5;

....
}

}
If a local variable has the same name as an instance variable the local variable will
be the one seen by the statements in its method that follow its
declaration. (Although it is correct syntax to have both local and instance variables use
the same name, it is probably a bad idea since it confuses humans.)
7. Decide if each statements sets the instance variable sum or the local variable sum.
class YetOtherClass
{
int sum; // the instance variable
void aMethod( int data )
{
sum = data ;

// instance variable is set

....
}
void bMethod( int data )
{
int sum; // a local variable
sum = data ;

// local variable is set

....
}
void cMethod( )
{
....
sum = 23 ;
int sum;
....
}

// instance variable is set

}
If a local variable has the same name as an instance variable and you want to
specify the instance variable, use this.
8. In the following program skeleton, decide if each statements sets the instance
variable sum or thelocal variable sum.
class AfurtherClass
{
int sum; // the instance variable
void aMethod( int data )
{
int sum; // a local variable
this.sum = data ;

// instance variable is set

....
}
void bMethod( int data )
{
int sum; // a local variable
sum = data ;

// local variable is set

....
}
}
If a parameter has the same name as an instance variable and you want to specify
the instance variable, use this. This is often done with constructors, where it is
probably less confusing to use the same name for both.
9. Decide if each statement sets the instance variable sum or the parameter sum.
class AfurtherClass
{
int sum; // instance variable

AfurtherClass( int sum ) // constructor


{
this.sum = sum ;

// instance variable is set

....
}
void bMethod( int sum )
{
sum = 32 ;

// parameter is set

....
}
}
An "outsider" can change a private instance variable of an object by using an
access method of the object (if there is one.)
10. In the following program skeleton, click on those buttons next to statements that
change sum.
class SimpleClass
{
private int sum;
SimpleClass( int s )
{
sum = s ;

// sum is initialized

....
}
void setSum ( int s )
{
sum = s ;

// sum is set

....
}
}
class TesterClass
{
public static void main ( String[] args )
{
SimpleClass sim = SimpleClass( 34 );
sim.sum = 77 ;

// OUT OF SCOPE

sim.setSum( 14 ) ;

// sum is initialized

// sum is changed

}
}
Introduction to Arrays 7.1
Most real-world programs handle vast amounts of data. The data usually can be
organized and processed systematically. Arrays or similar structures are almost
always used for this. When data is organized into arrays and processed in loops a
relatively small program can handle a vast amount of data. Array is an object that
is used to store a list of values. It is made out of a contiguous block of memory
that is divided into a number of calls. Each cell holds a value, and all the values
are of the same type. Sometimes the calls of an array are called slots. The cells
are numbered sequentially starting at zero. If there are N cells in an array, the
indexes will be 0 through N-1. The value stored in a cell of an array is sometimes
called an element of the array. An array is sometimes called an element of the
array. An array has a fixed numbers of cells. The values in the cells ( the elements)
can be changed. Every cell of an array holds a value of the same type. You can
have an array of ints, an array of doubles, and so on. You can have an array of
object references. A sub scripted variable can be used anywhere an ordinary
variable of the same type can be used. Array declarations look like this: type[]
arrayName; This tells the compiler that arrayName contains a reference to an
array containing type. However, the actual array object is not constructed by this
declaration. The declaration merely declares a reference variable arrayName
which sometimes in the future is expected to refer to an array object. Often an
array is declared and constructed in one statement like this:
type[] arrayName= new type [length]; int [] data = new int [10];

This statement does two things (1) it tells the compiler that arrayName will refer
to an array containing cells of type. (2) It constructs an array object containing
length number of cells. An array is an object and like any other object in Java, it
is constructed out of main storage as the program is running. The array
constructor uses different syntax than any other object constructors: new type
[length] This names the type of data in each cell and the number of cells. Once an
array has been constructed, the number of cells it has does not change. The length
of an array is how many cells it has. An array of length N has cells indexed 0...(N1). It is not legal to refer to a cell that does not exist. Say that an array were
declared: int[] data = new int[10]; Often size of an array is not known to the
compiler. The size of an array often determined by data at run time. Since the
array is constructed as the program is running the compiler does not know its
length ans can't detect some errors. As a Java program is running each time an
array index is used it is checked to be sure that it is OK. This is called bounds
checking and is extremely important for catching errors. If an executing program
refers to a cell that does not exist, an ArrayIndexOutOfBoundsException is
thrown and usually the program is terminated. Lacking any other information, the
cells of an array are initialized to the default value for their type. Each cells of a
numeric array is initialized to zero. Each cell is an array of object references is
initialized to null. The program can assign values to cells after the array has been
constructed. Index of an array is always an integer type. It can be a literal, or an
expression that evaluates to an integer. Using an expression for an array index is
a very powerful tool. You often solve a problem by organizing the data into arrays
and then processing that data in a systematic way using variables as indexes. You
can declare, construct and initialize the array all in one statement. You do not
have to say how many cells the array has. The compiler will count the values in
the initializer list and make that many cells does not change. Initializer lists are
usually used only for small arrays. A program can use any number of arrays.
Often values are copied back and forth between the various arrays. Super Bug
alert the following statement does not do the same thing: valB=valA; Arrays are
objects. The statement above will merely copy the object reference into the object
reference available resulting in two ways to access the single array object.
An array is a container object that holds a fixed number of values of a single type.
The length of an array is established when the array is created. After creation, its
length is fixed. The following program declares an array ( named anArray) with
the following line of code: //declares an array of integers
int[ ] anArray;
Like declarations for variables of other types, an array declaration has two
components: the array's type and the array's name. An arrays type is written as
type [ ], where type is the data type of the contained elements; the brackets are

special symbols indicating that this variable holds an array. The size of the array
is not part of its type. An array's name can be anything you want provided that it
follows the rules and conventions. An with variables of other types the declaration
does not actually create an array; it simply tells the compiler that this variables
will hold an array of the specified type. The brackets identify the array type and
should appear with the type designation. One way to create an array is with the
new operator. The next state,ent in the ArrayDemo program allocates an array
with enough memory for 10 integer elements and assigns the array to the anArray
variable.
//create an array of integers
anArray = new int [10];
If this statement is missing then the compiler prints an error like the following and
compilation fails:
ArrayDemo.java:4: Variable anArray may not have been initialized.
You can also declare an array of arrays by using two or more sets of brackets
such as String [ ] [ ] names. Each element , therefore, must be accessed by a
corresponding number of index values. In the Java programming language, a
multidimensional array is an array whose components are themselves arrays. A
consequence of this that the rows are allowed to vary in length. You can use the
built-length property to determine the size of any array. The following code prints
the array's size to standard output:
System.out.ptinln(anArray.length);
The system call has an arraycopy method that you can use to efficiently copy ata
from one array into another. The two Object arguments specify the array to copy
from and the array to copt to. The three int arguments specify the starting position
in the source array, the starting position in the destination array. And the number
of array elements to copy. Arrays are a powerful and useful concepts used in
programming. Java SE provides methods to perform some of the most common
manipulations related to arrays. The ArrayCopyDemo example uses the arraycopy
method of the System class instead of manually iterating through the elements of
the source array and placing each one into the destination array. This is
performed behind the scene enabling the developer to use just one line of code to
call the method. It also provides several methods for performing array
manipulations ( common tasks, such as copying, sorting and searching arrays) in
the java.util.Arrays class. Some other useful operations provided by methods in
the java.util.Arrays class are:
Searching an array for a specific value to get the index at which its I placed ( the
binarySearch method).

Comparing two arrays to determine if they are equal or not ( the equals method).
Filing an array to place a specific value at each index ( the fill method).
Sorting an array into ascending order. This can be done either sequentially using
the sort method or concurrently, using the parallelSort method introduced in Java
SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than
sequential array sorting.

An array is a data structure that can contain a fixed number of values of a single
type. The length of an array, i.e., the number of elements the array can hold, is
established when the array is created. A one-dimensional array occupies a
consecutive block of memory. Each element in the array can be accessed through
an index. The range of the index goes from zero to the size of the array minus one.
A for loop is commonly used to initialize the values in a two-dimensional array.

Use of One Dimensional Arrays 7.1.2 Assessment


1. Complete the following sentence. Each element in an array is accessed by its

numerical : Index
2. Which of the following correctly declared an array of integers? Int [ ] array;
3. Which of the following correctly allocates memory for 10 integers ? array=new

int [10];
4. Which of the following correctly initializes the 5th element in an array ? Array [4]

= 500;
5. Which of the following correctly creates and initializes an array?

Int [ ]anArray={10,20,30,40,50,60,70};
Two-Dimensional Arrays 7.2
Often data comes naturally in a two dimensional form. Web browser screens are
two dimensional, as are spreadsheets, printed pages, and images. A compact
notation for specifying a cell uses the row and column indexes like this:
gradeTable [ row] [col]
As with one dimensional arrays indices start at zero. A table may be implemented
as a 2D array. Each cell of the array is a variable that can hold a value and works
like any variable. As with one dimensional arrays, every cell in a 2D array is of
the same type. The type can be a primitive type of an object reference type. Each
cell of the array is specified with a row and column number in that order. The subscripted variables are used in assignment statements and arithmetic expressions

just like any variable. The row and column numbers are not part of the array. The
array object does not explicitly contain the indexes. Java knows what cell you
mean and goes there directly. Rows are numbered from 0 to N-1, where N is the
number of rows. Columns are numbered from 0 to M-1; where M is the number of
columns. A 2D array with N rows are M columns per row sill have N times M
number of cells. It is possible for a 2D array to have a different number of cells in
each row. When your program is running and it tries to access an element of an
array, te Java virtual machine checks that the array elements actually exists. This
is called bounds checking. If your program tries to access an array element that
does not exist, the Java Virtual machine will generate an:
ArrayIndexOutOfBoundsException
This will halt your program. Of course as with 1D arrays array indexes must be an
integer type. As with a 1D array an array index may be an integer literal a variable
of integer type a method that evaluates to an integer or an arithmetic expression
involving all of these things. The declaration of table uses an initializes list as a
short-cut way to create a 2D array object and place values into it. Twodimensional arrays are objects. A variable such as gradeTable is a reference to a
2D array object. The declaration
int [ ] [ ] myArray;
says that myArray is expected to hold a reference to a 2D array of int. Without
further initialization, it starts out holding null. myArray can hold a reference to a
2D array of int, create an array object , and puts the reference in myArray. All the
cells of the array are initialized to zero. Each row of a 2D array may have a
different number of cells. If a program refers to a call that does not exist, bounds
checking will catch the error and generate an exception. The length of a 2D array
is the number of rows it has. Length could be defined as a number of pair ( rows,
columns) The number of columns may vary from row to row so this will not
work. The number of rows does not change so it works as a length. The length of
a 2D array is the number of row it has. The length of a 2D array is the number of
rows it has. The row index runs form 0 to length -1. Each rows of a 2D array can
have a different number of cells so each row has its own length. A two
dimensional array is implemented as an array of one dimensional arrays. The
declaration declares a variable myArray which in the future may refer to an array
object. At this point, nothing has been said about the number of rows or columns.
Now myArray refers to an array object. Each cell may refer ( in the future) to an
array of int, an int [ ] object. None of the cells yet refer to an object. They are
initialized to null. This creates a 1D array object and puts its reference in cell 0 of
myArray. The rows do not need to have the same number of cells. An initialize r
list can be used to initialize an array not to assign values to it after it already
exists. The suggested answer puts the values into the required cells of the existing

1D array object . The not-quite-right answer replaces the old 0 row with a new
row. It constructs a new 1D array object that holds the desired values in its cells,
then assigns that object to row 0 of myArray. The way that the nested loops are
written enable the program to print out the correct number of cells for each row.
The expression uneven[row].length evaluates to a different integer for each row of
the array.

Quiz on 2D Arrays 7.2


1. Examine the following:

double[][] values =
{ {1.2, 9.0, 3.2},
{9.2, 0.5, 1.5, -1.2},
{7.3, 7.9, 4.8} } ;
what is in values[2][1] ? 7.9

2. Examine the following:


double[][] values =
{ {1.2, 9.0, 3.2},
{9.2, 0.5, 1.5, -1.2},
{7.3, 7.9, 4.8} } ;
what is in values[3][0] ? There is no such array element
3. You want to create a table that looks like:
12

8
9

14

- 0
32 1
Which of the following will work?
double[][] table =
{ {12, -9, 8},
{7, 14},
{-32, -1, 0} };
4. Given the following:
double[][] things =
{ {1.2, 9.0},
{9.2, 0.5, 0.0},
{7.3, 7.9, 1.2, 3.9} } ;
What is the value of things.length ? 3

5. Given the following:


double[][] things =
{ {1.2, 9.0},
{9.2, 0.5, 0.0},
{7.3, 7.9, 1.2, 3.9} } ;
What is the value of things[2].length ? 4
6. Given the following:
long[][] stuff ;
Which of the following statements constructs an array with 5 rows of 7 columns each
and assign its reference to stuff ? stuff = new long[5][7] ;
7. Given the following:
int[][] items =
{ {0, 1, 3, 4},
{4, 3, 99, 0, 7 },
{3, 2} } ;
Which of the following statements replaces the 99 with 77? items[1][2] = 77;
Which of the following constructs and assigns to array a 2D array with 7 rows,
but does not yet construct the rows? int[][] array = new int[7][];
8.

9. Given:
int[][] items =
{ {0, 1, 3, 4},
{4, 3, 99, 0, 7 },
{3, 2} } ;
Which of the following fragments prints out every element of items?
for ( int row=0; row < items.length; row++ )
{
System.out.println();
for ( int col=0; col < items[row].length; col++ )
System.out.print( items[row][col] + " ");
}
10. Given:

int[][] items =
{ {0, 1, 3, 4},
{4, 3, 99, 0, 7 },
{3, 2} } ;
Which of the following fragments replaces row 0 of items with an entierly new row?
int[] temp = { 8, 12, 6 };
items[0] = temp;

A two-dimensional array is a data structure that contains a collection of cells laid


out in a two-dimensional grid, similar to a table with rows and columns although
the values are still stored linearly in memory. Each cell in a two-dimensional array
can be accessed through two indexes that specify the row number and column
number respectively. Like-one dimensional array, the range of each index is from
zero to the size of the row or column minus one. A nested for loop is commonly
used to initialize the values in a two-dimensional array.

Common Array Algorithms 7.3


An array that uses a single subscript is called a one dimensional array. This is
because one index is used to access the values in the array. Its cells are like
numbered boxes lined up one after the other in a line. A two dimensional array
requires to indexes to access values. Its called are like boxes arranged into a
rectangle. Arrays of even higher dimension are possible, although rarely used. In
Java the index of an array starts at 0 and counts up to one less than the number of
elements in the array. The variable egArray refers to an array object that has been
constructed using an initializer list. The length instance variable of an array is the
number of cells it has. The for statement can be written like this:
for(int index = 0; index < egArray. Length; index ++)
Programs often use several arrays, and often visit each element of an array, in
order. The array is hard coded to be five elements long. The two for loops are the
same. Recall that the scope of the identifier index declared in the for statement is
limited to just the body of its loop. An array object is constructed as the program
runs. An array is constructed its size can be in a variable. The largest integer in a
list of integers is the maximum value. The maximum may occur several times but
no other integer in the list is larger. The smallest integer in the list is the
minimum. The minimum may occur several times. A systematic procedure used to
compute something is called an algorithm. The procedure described in the answer
is an algorithm for finding the maximum of a list. An algorithm is a description of

how to do something. It is not tied to any particular language. An algorithm can


be implemented in any computer programming language. The variable max
should be initialized to a value that is guaranteed to be no larger than the
maximum element of the array. A program should always work correctly
regardless of the quirks of the data. Don't make assumptions about what the data
look like. Class bug (1) IT is tempting to initialize max of something you think is
much less that the maximum, like -999. However in doing so you make a risky
assumption about the data. The array holds the national debt for each of the last
ten years. All these value are negative and -999 would easily exceed the true
maximum. The for loop is set up to look at every element in the array, starting
with the first element in cell 0 to see if that element is larger that the current
maximum. It would be OK ( and perhaps preferable) to start out index at 1 since
index 0 was written used to initialize max. Classic Bug (2) IT is tempting to say
that the maximum is -92 since -92 seems to be a bigger number that -12. But this
confuses the absolute value of a number with its position on the number line. IF
you are looking for the maximum of a list of numbers you are looking for the
number which is furthest to the right on the number line. Debugging a program is
often difficult . Finding test cases that thoroughly test a program is an important
part of this. Test must be done with an actual running program and with actual
data. Running a program one with toy data and sying that is works is not good
enough for professional program development. Compile and run the program.
Once you have it running see if you can break it by initializing the array to
different values, such as the following:
Put the largest element at the beginning
Put the largest element at the end.
Put in more than one copy of the largest element.
Put in an extremely large element.
Make all elements the same.
Make all elements negative.
Make all elements zero.
Sometimes a program works for the data a programmer was thinking about when
the program was written but not for all the kinds of data the program is used with.
Classic Bug (3) Not testing the boundaries. Bugs are often found at the
boundaries: at the beginning and ends of loops, at the beginning and ends of data,
with large or small values.. with a very large amount of data or with not data at

all. The change to the program introduces an off by one error. The array index
does not go far enough to test the last cell of the array. With a ten-element
initializer list the buggy program will fail about one time in ten assuming random
lists of data. Failure might not be obvious because the answer it computes is close
to the maximum. With a ten thousand element array the program will fail about
one time in ten thousand. Sloppy testing will never find this bug. Off-by-one
errors can be very subtle. Off-by-one errors are very common. A running Java
program checks each array index before it is used to be sure it is within bounds.
Java has enhanced for loop that visits each element of an array in order. It
automatically avoids off-by-one bugs. Sometimes the enhanced for loop is called
a foreach loop. As with the maximum- finding program the trial minimum is
initialized to the first element of the array. Thn it is updates as needed as each
element of the array is inspected in the loop. You want to compute the sum of a
list of numbers. You could initialize the sum to the first number and then proceed
through the remaining numbers adding each through the remaining numbers
adding each one to the sum. In the program that implements that algorithm. Its
array contains values of type double. The variable total is declared to be of type
double because the elements in the array are doubles as is their sum total is
initialized to zero. Sums should always be initialized to zero. Initialize total to the
first element of the array and then use the loop to add in the remaining elements.
This is much less clear that the expected way of doing things and is an open
invitation to bugs. The program visits each element of the array. In order adding
each to the total. When the loop exits total will be correct. The statement
total = total + array [index] ;
would not usually be used. It is more common to use the += operator.
Total += [ index];
You might think that it is strange to test if array contains any elements, since it is
obvious that it does. In a more realistic program the array would come form an
external source and might contain not elements.
Input/Output in Java 8.1
Two important programming concepts in Java : input and output, and well as
exception handling. Input and output techniques allow programmers to design
more compiles and useful programs. You must fully understand how to use a
programing languages built in I/O functionality. In Java before moving on to file
I/O both writing and reading data to and from files. Exception handling
mechanism allows a program to continue executing even if an error occurs in the

program instead of terminating it abruptly. Most programs input data process it


and then output the results. I/O operations are very complicated both at the
software level and at the electronic level. Part of the problem is that the way in
which data is organized outside the computer is different from the way it is
organized inside the computer. Lots of computation is needed to convert data
between its various forms. Most of the complication has been hidden inside the
methods that your program can use. Scanner is not part of the fundamental Java
language but is part of the package, java.util that you can include in your program.
A package is a collection of classes which may used in your program. A package
is a tool box and the classes within its as tools. Different programs need different
tools and include different packages. Java itself does not have I/O built into it.
The reason for this is 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 such as Java, C, C++ or any of several others
allow the programmer to pick the right I/O package for the job. In Java a source
of input data is called an input stream and the output data is called an output
stream. Data input is called reading data and data output is called writing data ( or
printing data if the output stream is connected to a monitor or a printer.) The input
stream is like a string of pearls which the program inputs one at a time in order.
The output stream is another string of pearls . Often a program will read several
data and them combine them somehow to produce one output value. Some
programs read in the entire input stream before they write the output stream.
Programs read the input stream item by item and write one output item for each
input item. There are many other patterns of input and output. A program may
have several input streams flowing into it and several output streams flowing out
of it. There are three standard streams:
System.in the input stream. (connected to the keyboard and the data are
characters)
System.out the output stream for normal results ( connected to the monitor and
also contain character data.)
System.err the output stream for error messages

The keyboard send character data to the computer even when the characters look
like numbers. The program sends character to the monitor even when it has
calculated a numerical result. If your program does the arithmetic the input
characters must be converted into one of the primitive numeric data types. This is
done using a Scanner object. Then a result is calculated using arithmetic with the
numerical data. The result must then converted into character data before it is
sent to the monitor. This done using a method of System.out. The nextLine( )
method of Scanner reads a line of character data from the keyboard. The
characters go into a String object. An assignment statement 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. In a Java program it reads
characters for the keyboard and creates a String object to contain them. A
reference to the object is put in inData. Then it sends the characters for that String
to the monitor. 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. A string of digits is a string og characters and is treated like
any string of characters. The digits are not automatically converted into a numeric
type.
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 );
}
}
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.
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.

Collecting characters from the keyboard is done by the OS. While this is going on
Java program is suspended. The user can edit the line and then hit enter to signal
that it is complete. Only then does the Java program see the characters and resume
execution. In order for your program to convert character data to numeric type
your program must convert it. The nextInt( ) method of a Scanner object reads in
a string of digit 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 numerical value. Usually that value is stored
in an int variable. The nextInt( ) method scans through the input stream character
by character gathering characters into groups that can be converted into numeric
data. It ignores any spaces and end-of-lines that may separate these groups.
Beginning programmers are often confused about character data and numeric
data and conversions between the two.

Statement program:
num=scan.nextInt()
assignment works in two steps:
1. evaluates the expression on the right of the equal sign, 2. Put the value into the
variable on the left.
The expression on the right scans a group of characters from the input stream and
converts them into an int. The 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. 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 will
throw an exception.

This exception was passed out of the running program to the Java System, which
stopped the program and wrote the error messages.
Input /Output in Java Assessment 8.1
This exercise reviews simple Java input and output. Much of this is detailed and hard to
remember, so don't expect to get every question correct.
into

1. When a program does INPUT, data flows


2. The Java package that contains Scanner is:
3. Data flows into a program from an input
an

output stream

the program.

java.util

stream

of characters and is written to

of characters.

4. The standard input stream is

System.in

5. Examine the following program, which reads in a line of text and then writes it to the

monitor. Fill in blanks.


java.util.Scanner

import
;
class Echo
{
public static void main (String[] args)
{
Scanner scan = new

Scanner

( System.in );

String inData;
System.out.println("Enter the data:");
inData = scan.

nextLine();

System.out.println("You entered:" + inData );


}
}
Exception

6. An
operation.

is an object that contains information about what went wrong in an

7. When a program sends an Exception to a higher level of the system, it


Exception.

throws

8. To input numeric data, first character data is input, then the characters are
into a primitive numeric type.

the

converted

9. Examine the following program, which reads in a number and writes its square to the
monitor. Fill in blanks.
import

java.util.* ;
class EchoSquare
{
public static void main (String[] args)
{
System.in

Scanner scan = new Scanner (


);
int num, square;
// declaration of 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 );
}
}
10. If the characters "one hundred forty two" were entered as data for the above
program, it would throw an

Exception

.
into

1. When a program does INPUT, data flows


2. The Java package that contains Scanner is:
3. Data flows into a program from an input
an

output stream

the program.

java.util

stream

of characters and is written to

of characters.

4. The standard input stream is

System.in

5. Examine the following program, which reads in a line of text and then writes it to the
monitor. Fill in blanks.
java.util.Scanner

import
;
class Echo
{
public static void main (String[] args)
{
Scanner scan = new

Scanner

( System.in );

String inData;
System.out.println("Enter the data:");
inData = scan.

nextLine();

System.out.println("You entered:" + inData );


}
}
Exception

6. An
operation.

is an object that contains information about what went wrong in an

7. When a program sends an Exception to a higher level of the system, it


Exception.

throws

8. To input numeric data, first character data is input, then the characters are
into a primitive numeric type.

the

converted

9. Examine the following program, which reads in a number and writes its square to the
monitor. Fill in blanks.
import

java.util.* ;
class EchoSquare
{
public static void main (String[] args)
{
System.in

Scanner scan = new Scanner (


);
int num, square;
// declaration of two int variables
System.out.println("Enter an integer:");
nextInt

num = scan.
();
square = num * num ;
// compute the square
System.out.println("The square of " + num + " is " + square );
}
}
10. If the characters "one hundred forty two" were entered as data for the above
program, it would throw an

Exception

Java provides a Scannerclass to facilitate the data input/output. Java also defines
various methods from the Scannerclass can convert user input into appropriate
data type before conducting any operation on the data.
The print and println methods are used to display text output. System is a class
in the Java Api that contains objects and methods that perform system-level
operations. One of the objects in the System class is named out and it has
methods such as print, printf and println for performing output on the system
console. The difference between print and println is that println advances the
cursor to the next line after printing the current message.
The first way to interact with the Java For-matter is via the method printf:
String s1=Hello

String s2 = World
system.out.printf(%s New %s ! , s1, s2);
This will print the following out: Hello New World!
If we just need to create a formatted string without a need to print it, we can use
the stati mehod format on the String Class.
String s1=Hello;
String s2=World;
int a 2;
String s=
String.format (%s New %s %d!, s1, a,s2);
This will set the value of string s to:
Hello New World 2!
Format also uses format specifiers . Some of the format specifiers include:
%s= String conversion
%d=signed integer (decimal) conversion
%f= floating-point number conversion
%b= a Boolean Value
%e- a number in standard scientific notation
String format can also take numeric positions:
String.format(%2$s%1$s,s1, s2);
This will output:
World Hello
Formatter provides a number of date-related conversion as well. The following
code:
String.format(%1$td %1$td %1$ty, new Date())
This will output:
6 February 2013
The 1$ designates which argument to use. In this example all three format
specifiers target the first argument, i.e., new Date().
The last part of each format specifier is how you carry out date conversions. It
uses a two-character sequence starting with a t. td in the first specifier

converts the day of the month.


Java provides support for the following: layout justification and alignment
common formats for numeric, string. And date/time data and locale-specific
output.
Writing Data to a File 8.2
Redirection is when output that would normally go to the monitor is sent to a desk
file. I/O streams are either character-oriented or byte-oriented. Character-oriented
I/O streams have special features for handling character data. Character printed
output to a desk file using a writer stream. You know that the class descends from
writer. If you do not know what class you need, look under Writer in the Java
documentation.

Class FileWriter is used for output of character data to a disk file. A FileWriter is
a kind of OutputStreamWriter which is a kind of Writer. When you read Java
documentation you might need to look at several ancestors of the class you are
interested in. The file .txt is an ordinary ASCII text file, with one byte per
character. Character string inside a running Java program are two bytes per
character. A Writer stream translates between the internal format and the external
disk file format. Disk file uses UTF which is identical to 8 bit ASCII format for
the common characters of English. In the USA text files are usually ASCII.

Computer terms often come from office practice of past decades. Compute files
are like the paper files used in offices. Closing a file means gathering up
everything that should go into it and filing it away. Use the close () method when
a program is done with a file. FI you don't the program might stop running before
the operating system has finished writing data to the file. The data written to the

file might be lost. Depending on how busy the operating system is. This is a
notorious computer bug. It can be very frustrating because sometimes a buggy
program will work correctly and sometimes not. There are two FileWriter
constructors:
FileWriter(String fileName)
FileWriter(String fileName, boolean append)
The first constructor's argument fileName is the name of a disk file that will be
created in the current sub directory. If there is already a file with that name, it will
be replaced. The second form of the constructor has an argument append, If the
append is true, the constructor will open an existing file for writing without
destroying its contents. If the file does not exist, it will be created. Most I/O
methods throw an IOException when an error is encountered. A method that uses
one of these I/O methods must either (1) include throws IOException in its
header, or (2) perform its I/OExceptions. The above program is modified to catch
exceptions. The constructor the write() method and the close() method each can
throw an IOException. All are caught by the catch block. With FileWriter use the
write () method to write characters to the file. There are several write () methods
with different parameters inherited from Writer and OutputStreamWriter. The
example program uses a method that write characters from a string:
public void write (String str) throws IOException
To output numerical results as characters use string concatenation:
int answer;

stream.write (The answer is: + answer)


This constructs a new sting by converting the data in answer into characters and
concatenation then to characters from the literal. All the methods used with
FileWrite. All of the methods are inherited from its ancestors. When you write
write() characters to a file, you are asking the operating system to write to the
disk. But the operating system might not do the work until later depending on how
busy it is. The flush () method ensures that all data is actually sent to the disk.
Constructors
FileWriter(String fileName)
An IOException is thrown if the file cannot be created.
FileWriter(String fileName, boolean append)
An IOException is thrown if the file cannot be opened for appending.

Methods
public void close() throws IOException
Flush the stream and close the file.
public void flush() throws IOException
Flush the stream.
public void write(String str) throws IOException
Write a string.
The trim methods leading and trailing spaces from the user data. Two try {}
blocks are used. The first catches errors in creating the file; the second catches
errors in writing data to it. Dsik input and output is more efficient when a buffer
is used. Programs that do have extensive I/O should use buffers. BufferedWriter
to do this with character output stream. To do this with a character output stream.
BufferedWriter( Writer out)
Construct a buffered character-output stream. Since a FileWriter is a writer it is
the correct type for the parameter. Here is how this might be done:
BufferedWriter out
= new BufferedWriter( new FileWriter (stuff.txt));

Different operating systems separate lines in text files in different ways. To the
annoyance of programmers everywhere, Microsoft operating systems use two
byte sequence at the end of a line of text, but Unix and Linux operating systems
use just one byte. The class PrintWriter is used to deal with the end-of-line
problem and other frustrations of file output. PrintWriter provides may methods
that are useful for printing characters. Printing in this context means sending
characters to an output destination, not usually a hard-copy printer. The println()
method uses the appropriate line separator or the operating system the program is
running on. Often a PrintWriter stream is connected to a BufferedWriter stream
which is connected to a FileWriter. For small programs where buffering is not

needed, the middle pipe (the BufferedWriter) can be omitted. A further advantage
of PrintWriter is that none of its methods (including println()) throw exceptions.
Usually output is more reliable that input (because the program has control over
its output), so exception handling is sometimes not needed. The updated example
program uses a BufferedWriter and a PrintWriter. The println() prints one line of
text and ends each line with the correct codes for whatever operating system you
are running. Creating the file might throw an exception, so a try / catch structure
is needed for the constructor. The println() statements do not throw exceptions and
can be moved outside of the structure. Another advatnage of PrintWriter is that
you can asking it to automatically flush its data every time a println() is executed.
It is still a good precaution to close () the stream when you are through with it.
List of some of the constructors and methods used with PrintWriter. For complete
list of methods refer to the Java documentation.
Constructors
PrintWriter(Writer out)
Create a new PrintWriter and connect it to the Writer out.
Automatic line flushing is not enabled.
PrintWriter(Writer out, boolean autoFlush)
Create a new PrintWriter and connect it to the Writer out.
Automatic line flushing is enabled if autoFlush is true.
Methods
public boolean checkError()
Flush the stream. If there has been an error in output the
method returns true.
public void close()
Flush the stream and close the file.
public void flush()
Flush the stream.
public void print(char c)
Print the character neld in c.
public void print(double d)
Translate into characters and print the double value d.
public void print(float f)

Translate into characters and print the float value f.


public void print(int i)
Translate into characters and print the int value i.
public void print(String s)
Print the String s.
public void print( various other data types )
See your complete documentation.
public void println()
Terminate the current output line and (possibly) flush the stream.
public void println( various data types )
See Java on-line documentation.
'\t' is the tab character.
Assessment on Writing Text Files 8.2.1
1.

What is the ancestor class of streams that do character-oriented output? Writer

2.

How many bits per character does a Java program use? 16

3. What is the class that translates characters from the internal form( used by a Java
Program) to the external form(used by a disk file). FileWriter
4. What is the disk file format for characters that is intended to work for all human
languages? UTF
5. Which of the following opens an existing file myFile.txt so that characters may
be added to its end? FileWriter fw=new FileWriter(myFile.txt,true);
6. What does the flush() method of a stream do? It ensures that all pending output
operations are completed.
7. What is a buffer? A section of main memory used as a work area for input or
output operations.
8. What is an advantage in using the PrintWriter class? Its methods use the
appropriate line termination character for your operating system.
9. Does the println() method of PrintWriter throw exceptions? No. No methods of
PrintWriter throw exceptions.
10. Which operation is usually more reliable: input or output? Output
Although suing System.out to write to the console is till permissible under Java, its

use is recommended mostly for debugging purposes or for sample programs. For
real-world programs, the recommended method of writing to the console when using
Java is through a PrintWriter stream. PrintWriter is one of the character-based
classes. Suing a character-based class for console output makes it easier to
internationalize your program. PrintWriter defines several constructors:
PrintWriter(OutputStream output Stream, boolean flushOnNewline)
Output stream is an object of type OutputStream and flushOnNewline controls
whether Java flushes the output stream every time a newline('\\n') character is
output. If flushOnNewline is true, flushing automatically takes place. If false
flushing is not automatic. PrintWriter supports the print() and println() methods for
all types including Object. You can use these methods in the same way as they have
been used with System.out. If an argument is not a simple type, the PrintWriter
methods call the object's toString() method ans then print the result. To write to the
console by using a PrintWriter, specify System.out for the output stream and flush
the stream after each newline. This line of code creates a PrintWriter that is
connected to console output:
PrintWriter pw= new PrintWriter(System.out,true);
There is nothing wrong with using System.out to write text output to the console
when you are learning Java or debugging your programs. Using PrintWriter will
make your real-world applications easier to internationalize.
Reading Data from a file 8.3
An input stream can be connected to a text file. With character-oriented input
streams. Characters are automatically translated from the external format to the
internal format.

The diagram shows some of the classes in the Reader hierarchy. The reader
hierarchy looks much like the Writer hierarchy. FileReader is used for input of
character from a disk file. The input file can be ordinary ASCII, one byte per
character text file. A reader stream automatically translates the characters from the
disk file format into the internal char format. The characters in the input file
might be from other alphabets supported by the UTF format, in which case there
will be up to four bytes per character. In this case characters from the file are
translated into char format. As with output, it is good practice to use a buffer to
improve efficiency . You use a BufferedReader for this.

The readLine() method reads a line of text from a character-oriented input


stream, and puts it into a new String object which it returns as a reference. If
these is not more data in the file, it returns null. When a file is opened it is
prepared for use. This program opens a file for reading . The file is opened for
reading when the FileReader stream is constructed. If the file does not exist in
the current directory an IOException is thrown. The program reads each line o
the file and writes it to the monitor. When end-of-file is detected the program
quits. This is an extremely common programming pattern: reading and
processing data while not end-of-file. Usually in documentation, end-of-file is
abbreviated EOF.

Constructors
The constructor for BufferedReaderlooks like this:
BufferedReader( Reader in )
The constructor for FileReader looks like this:
FileReader( String fileName ) throws FileNotFoundException
The methods from BufferedReader which interest us are:
void close() throws IOException
int read() throws IOException

// close the stream


// read a single character into an int

String readLine() throws IOException // read one line of characters into a String.
Closing an input file is less important that closing an output file. When EOF is
detected there is no more data. Close input files anyway. Doing so less the
operating system manage resources more effectively. To write to a file after
reading it in, the file must first be closed and then opened for output (with a
FileWriter stream). A word processor program might do this. A program can open
a file so that it can be both read and written during the same session. A file
opened this way is said to be open for direct access or random access. An already
existing file with the same name as destination file will be destroyed. The names
of the source and destination come from the command line. Most operating
systems come with a user interface that includes a file copy command. The order
of the source file and the destination file differs between operating systems.
Getting them backwards might be disastrous. Program requires the word to in
the command line to ensure that the user knows the correct order. The program
will use a FileReader and a BufferedReader for input and a FileWriter and a
BufferedWriter for output. Rather than write one big main () it is convenient to
define an object whose several methods implement the steps in copying files.
Potentially the object could be used as a component of a larger program. The main
90 method collects information from the user. It the information looks correct, it
creates a copy maker object and calls its methods. The openFiles() method it open
a BufferedReader stream with the source file and a PrintWriter with the
destination file. It is possible though rare for closing a file to fail The close
method() of PrinterWriter does not throw an exception. The copyFiles () method
finally gets down to copying the file. Here is the loop form the copyFile ()

method. Here is the same loop written in a style that is commonly used with the C
programming language. The key to understanding this is to understand that an
assignment statement is an expression and has a value. That value is the value
that is assigned to the variable. So this has a value that is non-null after a
successful readLine () and null upon EOF.
Quiz on FileReader and BufferedReader 8.3
1. What is the ancestor class of all character-oriented input streams? Reader
2. What stream type provides input from a disk file? FileReader
3. What class does readLine() belong to? BufferedReader
4. What data type does readLine() return? String
5. What value does readLine() return upon encountering EOF? Null
6. What happens when readLine() encounters an error? It throws an IOException
7. What method is used to notify the operating system that a file is no longer needed?
Close()
8. Should FileReader be used to read a Java bytecode (*.class) file? No-the bytes in
bytecode files are not intended to interpreted as characters.
9. Can a FileReader object be constructed that is not connected to any file? No-the
constructor must specify a file.
10. Which of the following is used in a C-style input loop? while(line
=source.readLine())!=null)
ReaderStream class hierarchy. FileReader and BufferedReader classes are used
together when reading data from an external file. The use of BufferedReader class
allows data to be buffered as it is read from the file before manipulating it. The
readLine() method of the BufferedReader class reads a line of text from a
character-oriented input stream, and puts it into a new String object.

Exception Handling 8.4


A program often encounters problems as it executes. It may have trouble reading

data there might be illegal characters in the data or an array index and go out of
bounds. The java Exception class enables you to deal with such problems. Using
it you can write programs that recover from problems and keep on running. Most
programs should not crash when the user makes an error I/O is especially error
prone. Exception handling is essential for I/O programming.
Inspect the following. What went wrong?
C:\cs151\chap80>java Square
Enter an integer: rats
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Square.main(Square.java:12)
The stack trace tells the story: the user entered rats which Scanner could not
convert to an integer, so an Exception was thrown.
Nothing is wrong with the program. The problem is with the data. NextInt()
cannot convert rats into an int. When next() found the problem it threw an
InputMismatchException. The Java runtime system caught the exception, halted
the program, and printed the error message. An exception is a problem that occurs
when a program is running. Often the problem is external to the program, such as
bad user input, or mechanical failure of an I/O device. When an exception occurs,
the Java Virtual Machine creates an object of class Exception which holds
information about the problem. A Java program itself may catch an exception. If
can then use the Exception object to recover from the problem. An error is a
problem that occurs when a program is running. An error is represented by an
object of class Error. But an error is too severe for a program to handle. Most
application program must stop running.

Class exception and class error both extend Throwable. A java method can
throw an object of class Throwable. Scanner threw an exception when it tried to
convertrats into an integer. Exceptions are different for Errors because programs
can be written to recover from exceptions, but program can not be written to
recover for Errors. Exceptions can be caught by a prat of the program that tries to
recover from the problem. To catch an exception: put code that might throw an
exception inside a try{} block. Out code that handles the exception inside a catch
{} block. If a statement inside the try{} block throws an
InputMistmatchException, the catch{} block immediately starts running. The
remaining statements in the try{} block are skipped. The reference variable ex
refers to the Exception object. After the catch {} block is executed, execution
continues with the statement that follows the catch{} block. Execution does not
return to the try{} block.
Syntax of try{} and catch{}
try
{
// statements which might throw
// various types of exceptions
}
catch ( SomeExceptionType ex )
{

// statements to handle this


// type of exception
}
catch ( AnotherExceptionType ex )
{
// statements to handle this
// type of exception
}
catch ( YetAnotherExceptionType ex )
{
// statements to handle this
// type of exception
}
// Statements following the structure
Here are a few syntax rules:
1.The statements in the try{} block can include:

Statements that always work.


Statements that might throw an Exception of one type or another.
2.One or several catch{} blocks follow the try() block.
Sometimes there can be no catch{} block. This will be discussed later in

this chapter.
3.Each catch{} block says which type of Exception it catches.
It does this in a one-item parameter list:( ExceptionType parameter )
The parameter is a reference variable that will refer to the Exception object

when it is caught.
This is how and try catch work: When an Exception is thrown by a statement in
the try{} block the catch {} blocks are examined one by one starting with the first.
The first catch {} block to match the type of the Exception gets control. Only one
catch block gets control. IF no catch {} block matched the exception none is

picked and execution leaves this method, jus as if there were not try{} block. The
most specific exception types should appear first in the structure, followed by the
more general exception types. The statemetns in the chosen catch{} block execute
sequentially. After the last statement executes control goes to the first statement
theat follows the try / catch structure. Control does not return to the try block.
Exception handling is important for user friendly programs. Above is the
compute-the square program again. This time written so that the user is prompted
again if the input is bad: This is a common style for reading user input.

Here are two of the rules about how try/catch blocks work:
4.The first catch{} block to match the type of Exception thrown gets control.
5.The most specific Exception types should appear first in the structure, followed

by the more general Exception types.

To make full sense of these rules you need to know more about Exception types.
An Arithmetic Exception is thrown for some types of arithmetic problems, such as
when a division by zero is attempted. In arraigning the try{} block a child class
should appear before any of its ancestors. If an
ArrayIndexOutOfBoundsException occurs this program immediately looses
control. The exception is thrown to the method that called it, which in this case is
the Java run time system. By using a finally {} block you can ensure that some
statements will always run, no matter how the try{} block was exited.

try
{
// statements, some of which might
// throw an exception
}
catch ( SomeExceptionType ex )
{
// statements to handle this
// type of exception
}
.... // more catch blocks
catch ( AnotherExceptionType ex )
{
// statements to handle this
// type of exception
}
finally
{
// statements which will execute no matter
// how the try block was exited.
}
// Statements following the structure

There can only be one finally block and it must follow the catch blocks. If the try
block exits normally (no exceptions occurred), the control goes directly to the
finally block. After the finally block is executed the statements following it get
control. If the try block exitx because of an Exception which is handled by a catch
block, first that block executes and then control goes to the finally block. After the
finally block is executes and then control goes to the finally block. After the
finally block is executed the statements following it get control. If the try block
exits because of an exception which is not handled by a catch block control goes
directly to the finally block. After the finally block is executed the Exception is
thrown to the caller and control returns to the caller.
Here is a picture of how the finally{} block works:

If there is a finally {} block then the catch {} block can be omitted. This might be
done if you don't want to handle exception in your method, but you ave a few
statements that must execute no matter what before control is returned to the
caller. If a method has a lock on some resources that it should give up before
exiting. If the method opens a file it should close it before exiting. If the last catch
block catches exception then it will catch any type of exception not caught in the
proceeding blocks. Do this so the user sees a pleasant error message rather than a
confusing stack tract. ArithmeticExceptions are caught in the first block and all

other exceptions in the other.


Both exceptions and errors are problem that ma happen when a program is
running. They can disrupt the normal execution of the program, and halt the
program abruptly. An exception is usually external to the program such as invalid
values from an input and output device. Which can be recovered so that the
program can resume execution while an error is usually severe so the at he
program has to be stopped. Java uses Exceptionclass to hold information about the
exception. At the core of exception handling mechanism are the keywords try and
catch. They work to catch and fix problems in a program. The try block contains
code that might throw an exception while the catch block contains code that
handles the exception. Once an execution of a program stops due to a problem.
Java default exception handler terminates program execution and displays an error
message followed by a list of method calls that lead to the exception. This is
referred to as stack trace.

Quiz on Exceptions and Errors 8.4


1. From which problems is it possible for a program to recover? Exceptions
2. Both class Error and class Exception are children of this parent: Throwable
3. Is a program required to catch all exceptions that might happen? no. You can write
a program to catch just the exceptions you want.
4. What type of exception is thrown by nextInt() if it gets illegal data?
InputMismatchException
5. Which statement is False about the try{} block? The try{} block can not contain
loops or branches.
6. Which statement is False about catch{} blocks? The catch{} block for a child
exception class must follow that of a parent exception class.
7. Which of the following lists exception types from most specific to lease specific?
ArithmeticExceptions, RunTimeException
8. What happens in a method if an exception is thrown in a try {} block and there is
no matching catch {} block? The method throws the exception to its caller exactly
if there were no try{} block.
9. How many finally{} blocks may there be in a try/catch structure? There can be
zero or one following the last catch {} block.
10.When is a finally {} block executed? Always after execution has left a try{} block,
no matter for what reason.

You might also like