Sei sulla pagina 1di 58

BCA-501.

INTERNET APPLICATIONS AND JAVA


Section I
Introduction
Internet Architecture board
The IAB is an independent committee of researchers and professionals with a technical interest in the health and
evolution of the Internet system... IAB members are deeply committed to making the Internet function effectively and
evolve to meet a large scale, high speed future.
The IAB evolved from the Internet Configuration Control Board (ICCB) originally established in 1979 by the
ARPANET Program Manager Vinton Cerf, and oversees development of the Internettechnology standards. In 1983, the
ICCB was reorganized around a series of technical task forces by Cerf's successor, Dr. Barry Leiner, and named the
Internet Activities Board (IAB).
The IAB was supported throughout the 1980's by the Federal Research Internet Coordinating Committee (FRICC), an
informal group of US Government managers supporting inter-networking that was absorbed into the Federal
Networking Council in 1990.
In June, 1992, the Internet Activities Board was renamed theInternet Architecture Board by the Internet Society at the
INET92 conference in Kobe, Japan. The roles and responsibilities of the IAB are described in RFC 2850, and
summarized below:
Oversight. Provide oversight of the Internet architecture, protocols, procedures, and standards.
RFC management. Provide editorial management and publication of the Request For Comments documents.
IESG selection. Appoint the members of the Internet Engineering Steering Group, and the chair of the Internet
Engineering Task Force.
IETF oversight. Responsible for the IETF's relationships with other standards bodies and related organizations.
IANA administration. Provide administration of the Internet Assigned Numbers Authority, which manages the
various Internet numbers and parameters.
The IAB is composed of 13 members, made up of 12 members nominated by the IETF and approved by the Board of
Trustees of the Internet Society, plus the IETF chair who may vote on all official actions except approval of Internet
Engineering Steering Group members and IESG appeals. Each member serves for two years, and may serve more than
one term. Interestingly, members of the IAB must serve as individuals, and not as representatives of a company, agency,
or other organization. The process is further described inIAB and IESG Selection, Confirmation, and Recall Process:
Operation of the Nominating and Recall Committees, RFC 3777.
Resources. Request For Comments documents by and about the IAB are listed below:
RFC 1160; Vinton Cerf; The Internet Activities Board; May 1990
RFC 1601; C. Huitema; Charter of the Internet Architecture Board; Mar 1994
RFC 2026; S. Bradner; The Internet Standards Process -- Revision 3; 9 Oct 1996
RFC 2850; B. Carpenter, Ed.; Charter of the Internet Architecture Board; May 2000
RFC 3869; R. Atkinson, Ed.; S. Floyd, Ed.; IAB Concerns and Recommendations Regarding Internet Research
and Evolution; Aug 2004.
Understanding the internet
What is the Internet?
Protocols, computers and communities
Information, servers and browsers
A packet-switched network using TCP/IP
Strictly speaking, the Internet is a communications protocol, a language which computers use to talk to each other,
called TCP/IP. This language is designed to enable computers to exchange data reliably and efficiently, though not
necessarily quickly.
More generally, the term is used to signify the network of computers connected using TCP/IP: the connecting wires and
the equipment used to route the information (the network infrastructure), and the computers themselves.
Even more generally, the Internet is often used to indicate the community of users and computers collectively. Though a
very broad definition, this is perhaps the most useful and interesting the Internet is really an information-based
society.

Protocols created by the community


Internet protocols are constantly evolving
Democratic decisions guard against control by individuals
A technocracy?
The TCP/IP and related protocols that are used across the Internet are designed and agreed upon by the users and
administrators of the individual parts of the Internet: anyone can contribute to the growth and direction of the Internet,
though you do need to know a fair amount of technical detail to get involved. In this way, the Internet is not so much
controlled by an organisation, as encouraged in a certain direction by its members. It's a kind of open, contributory
democracy.
Sometimes, companies will try to force the net to go the way they want, but usually there's enough resistance from the
mass of contributors to only go that way if the idea or direction is good for the 'net as a whole.
The influence each person has on the direction of the Internet is usually related to their technical knowledge and
reputation, with widely respected techies holding the most power. It's perhaps more of a technocracy than a traditional
democracy.
Protocols serving information to a community
Protocols serving information to a community
Internet hosts
Clients and servers
Exponential growth, and still growing?
The Internet, as a network of networks, consists of many computers, called servers or hosts, which are linked by
communication lines. The administrators of these hosts may make information or software stored on them publically
available, so that others can view, download or use the data. At the last count (Jul 2007), there were an estimated 489
million hosts [http:// www.isc.org/index.pl?/ops/ds/] connected to the Internet.
Dynamic and permanent connections
However, most Internet-connected computers act only as clients ; they access the data storedon other servers, but don't
store or share any information themselvesi. It's hard to estimate how many client computers there are in cyberspace,
because many connect dynamically or are hidden behind firewalls, but a conservative estimate (according to
Nielsen//Netratings [http://www.nielsen-netratings.com]) would be more than 800 million, possibly much higher.
According to Internet World Stats [http://www.internetworldstats.com/], nearly 1.5 billion people have some form of
Internet access.
Dynamic and permanent connections
Dynamic vs. static Internet addresses
Instant connection vs. dial-up
Dedicated cabling vs. telephone lines
Clients may be permanently connected (often known as always-on), or may connect dynamically when needed.
Permanent connections are most commonly made through a local area network (LAN) or a digital subscriber line (DSL
or ADSL ), and give instant 24/7 access.
A temporary, dynamic connection such as that provided by a modem link needs to be connected each time the Internet is
used, which can cause a delay. Modem links also tend to be slower than dedicated digital links, because they use normal
voice telephone lines which are not designed to carry digital signals.
DSL connections also carry a digital signal across wiring designed for analogue signals, but do so by overlaying a very
high frequency signal (well beyond human hearing) onto the normal connection. This means that not only can the same
line carry voice and data simultaneously, but that for short distances, a much higher bandwidth can be carried.
Dedicated wiring for Internet traffic is most commonly found in companies and other organisations, where a LAN is
used to connect clients and hosts together. Usually, this forms an enclosed network which connects to the outside world
through a single point, which can be controlled and protected against intrusion and viruses. Connection to this type of
network is normally instantaneous and 'always-on'.
In fact, the distinction between clients and servers is becoming very blurred, with the advent of peer-to-peer software,
personal web servers and other new uses.

How does information travel through the Internet?


How does information travel through the Internet?
Data is divided up into packets
Data routes across the Internet can be switched to avoid congestion
Entire mechanism is handled by the TCP/IP protocols
The Internet is based on packet-switched protocols. Information is carried in packets, which can be imagined as small
parcels being passed from computer to computer. Large chunks of data are usually broken up into several smaller
packets before being sent through the network. The delivery mechanism, or protocol, that is used to encode the packet
ensures safe transit, and provides a way of reconstructing the data when it reaches its destination. The protocols used on
the Internet are referred to as TCP/IP, standing for Transmission Control Protocol / Internet Protocol.
As a switched network, the physical connections between computers do not matter as far as Internet traffic is concerned
the protocols ensure that guaranteed information delivery is more important than speed or use of a particular route.
This means that a sequence of packets might arrive out of order, with some travelling through the net by a faster, shorter
route than others. TCP/IP provides the means for your software to piece together those packets into meaningful data.
The ability to take different routes through the network is a fundamental part of the original design of TCP/IP, as it
allows the Internet to route around damaged areas of the network. The Internet in the Academic World
How the University connects...
via the Joint Academic NETwork (JANET)
which is managed by UKERNA
which provides a high-speed dedicated backbone
The University has a permanent Internet connection, which connects it to the JANET (Joint Academic NETwork).
JANET is maintained by UKERNA (UK Education and Research Networking Association), which in turn is part of JISC
(the Joint Information Services Committee).
The JANET connection is a high speed, permanent connection over a leased line, which means that, whilst expensive to
maintain, it provides enough bandwidth to cope with a large institution and is relatively reliable.
Be careful!
Because the connection is funded and provided by government bodies, there are various conditions implied when you
connect. Don't forget to read the terms and conditions!
Connecting using an ISP
Internet Service Provider
... extends the Internet into your computer
An ISP, or Internet Service Provider, is a company that provides you with a point of access to the Internet. When you
connect to your ISP, your computer (or your own network) becomes an extension of the Internet itself whilst you remain
connected.
How does the connection work from home?
Modems and routers
Negotiating a connection
To connect from home you need several things. Apart from a computer (obviously!) you'll need a phone connection, a
modem or ADSL router, and some Internet software. Things will be easier if you're using a relatively recent operation
system, such as Windows Vista/XP or MacOSX, but it's possible to connect with older or more obscure systems. With a
modem and the appropriate software, you can dial up another modem connected to another computer, and establish a
network connection with it. Usually, this computer is linked into the Internet, and so you're online.

With an ADSL modem or router, a similar procedure happens, but a filter splits the telephone line into voice and data
(low and high frequencies) and your router negotiates a connection with the ADSL equipment in the telephone
exchange.
Choosing an ISP
Frequencies used on an ADSL line: PSTN is the normal telephone ("voice") usage, and the upstream/downstream areas
are for data. Note the unequal proportions of the data range (i.e. Assymetric DSL)
Choosing an ISP
Dialup, broadband or mobile?
Occasional or extensive use?
Tied to single line, or available anywhere?
Within the University, the computers are connected permanently to the Internet. If you want to connect from home,
you'll need to connect temporarily to an Internet Service Provider, or ISP, each time you need to access Internet
resources. Setting this up is a fairly painless process, though you need to choose your ISP carefully.
What to look for. The first decision to make is the type of connection you want. If you're a very occasional user, then
getting a dialup connection is still often the cheapest and simplest. It's also useful if you travel around a lot, as it's not
(usually) tied to a particular phone line/number.
Choosing a broadband provider
Most people, however, will want a broadband connection, because it gives a reliable, almost instant connection (or
'always-on' operation) at a high bandwidth. You might also consider a wireless connection using data over a mobile
phone network. These offer the ultimate mobile solution, but can be very expensive, often charging per megabyte of
download.
Choosing a broadband provider
Reliability, speed, contention ratio, cost
Download limits and fair use
For broadband ISPs, there are several important factors to check, including reliability, speed of connection, how many
other customers share the total bandwidth (the Contention Ratio), and of course, cost. Most charge a set-up cost, and
many have a minumum contract period, so be careful you don't get locked into a poor deal for many months!
There are now also variable packages, where you can control the amount of bandwidth available, paying extra for more
capacity if you need it. For more recommendations and relatively independent advice I find ThinkBroadband
[http://www.thinkbroadband.com/] (formerly ADSLGuide.org.uk) useful.
A recent development is the capping of Internet connections by limiting the monthly downloads to, say, 10GB. This may
seem reasonable at first, but if you wish to listen to Internet radio or download video clips from the BBC, for example,
then you'll hit this limit sooner than you expect.
Check whether your ISP offers an unlimited or unmetered service.
How fast? How reliable?
Balance speed, reliability and extra features
Think about your typical usage
Don't get locked into a long contract
Keep a separate emailbox

Another thing to look out for is the speed and reliability of the connection. This is partly dependent upon the speed of
your modem and your computer (see above), but also depends on Connecting through the University
your ISPs facilities too. Again it's worth shopping around to see which service provides fastest access, and the quickest,
most reliable connection. There are a number of websites that run independent tests and surveys on each of the major
ISPs, so there's no shortage of advice!
It's also worth shopping around for extras, such as webspace and email boxes, domain names,
and even telephone deals.
Remember, though, that if you use your ISP's email facilities, your email address will change
each time you change your ISP; it's often better to have a separate, permanent account from an
independent email provider, such as Microsoft's hotmail [http://www.hotmail.com/] or Google's
gmail [http://mail.google.com/mail/help/intl/en/about.html].
Connecting through the University
Basic dial-up service
ResNet in student halls/accommodation
For accessing the Uni network, Virtual Private Network is better
You can use the University as your ISP. Check the DialUp page [http://www.its.ex.ac.uk/dialup/] for more details.
If you live in University-run accommodation that has a built-in network connection, you can also connect to ResNet
[http://www.its.ex.ac.uk/resnet/], the University's residential network. For a small(ish) fee, currently 70 per year, you
get an always-on connection into the campus network. Note that this is only a limited service; you get full web and
email access, but other services such as chat, filesharing or multimedia streaming may be limited.
Whenever you connect to the campus network you're also bound by the University's rules and regulations
[http://www.its.ex.ac.uk/regs.shtml], so don't do anything naughty - someone may be watching!
Configuring your computer
Your ISP should provide an installation CD
Should also provide settings for manual configuration
Measuring Bandwidth
If you're using your own PC, you'll need to configure networking for your operating system (eg Windows XP). The
easiest way to do this is to obtain a CD with the tools and settings combined--- most ISPs give these away free. If you
know all the details of the connection (usually obtainable from the ISP's tech-support website), you can set up the
connection by hand, but this is often not for the faint-hearted!
There are some hints on configuring Windows for the University's dialup [http:// www.its.ex.ac.uk/dialup/] and ResNet
[http://www.its.ex.ac.uk/resnet/] services on the IT Services website (the ResNet pages are particularly good).
Measuring Bandwidth
basic unit is the bit per second
megabits per second (Mb/s) more commonly used
a megabit is around a million bits
Don't confuse with megabytes per second (MB/s)
divide Mb/s by 8 to get MB/s
Though the speed and quality of links are not the most important factors for Internet traffic, they will still affect your use
of the net. In particular, you'll notice the difference (hopefully) between connecting on Campus, and connecting from
home using a modem. Modems are described by their bandwidth; a typical analogue modem may have a bandwidth (or

speed) of 56kb/s (kilobits per second), and a broadband modem anything between 256 to 2048 kb/s. This compares to
the campus ethernet network, which has bandwidths of between 10 and 2000 Mb/s (megabits per second). Of course, on
the campus ethernet, this bandwidth is often shared between many users (eg all computers in a single building) whereas
the bandwidth of your analogue modem at home is exclusively yours. Broadband (DSL) connections often state how
many others you'll be sharing your bandwidth with - this is called the Contention Ratio.
Mind your bits and bytes
A bit is a single binary digit (a zero or a one). A kilobit (kb) is about thousand bits (actually 1024, or 2 to the power 10),
and a megabit (Mb) is around a million bits (1024 x 1024, or 2 to the power 20). You're probably more familiar with
bytes, which are a group of eight bits, and can represent a single character or digit. Hard disk drives, for example, are
measured in megabytes (MB - very small), gigabytes (GB) or terabytes (TB - very large) - note that in abbreviations,
bytes are capital B's and bits are lower case!
Who governs/regulates/controls the Internet?
Who governs/regulates/controls the
Internet?
A collective free-for-all?
A collaborative technocracy?
A commercial communications network?
This is a difficult question! The Internet grew as a collaborative network of researchers keen to share their discoveries in
a simple, accessible way. Because of this, there was no real need to regulate or control the Internet; the information was
already free and was of interest only to other researchers, so it didn't need protection. But as the Internet has grown, it
has become a more commercial, public entity, and some who use it now wish it to be governed and policed to prevent
certain types of abuse.
However, there are various bodies that govern parts of the Internet, which we'll look at in the next few paragraphs.
Domain names
Map numeric addresses to mnemonic names
Allocated first-come, first-served (usually)
One of first areas of dispute over control
Internet Protocol Addresses
Internet Protocol Addresses
System of unique numbers needed to find each host
Managed by the Internet Assigned Numbers Authority (IANA)
Other bodies and institutions
Internet Society (ISOC)
oversees other Internet organisations
Internet Architecture Board (IAB)
manages technical direction of the Internet
Internet Engineering Task Force (IETF)
standardises technical developments (through RFCs)

Section II
Introduction to Java
Java : A simple, object-oriented, distributed interpreted, robust, secure, architecture neutral, portable, high-performance,
multi-threaded and dynamic language.
- The Java Language: A White Paper Sun Microsystems Java applets were a breakthrough in interactive content on
the Web, and many top sites used them to deliver news, present information, and attract visitors. There are still
thousands of applets on the Web today. First used to create simple programs on World Wide Web pages, Java can be
found today in each of the following places and many more:
Web servers
Relational databases
Mainframe computers
Telephones
Orbiting telescopes
Personal digital assistants
Credit card-sized smartcards
Although Java remains useful for Web developers trying to enliven sites, it extends far beyond the Web browser. Java is
now a popular general-purpose programming language, and some surveys indicate that there are more professional Java
programmers than C++ programmers.
FEATURES OF JAVA
Java Is Object-Oriented
Object-oriented programming also called OOP is a way of conceptualizing a computer program as a set of
separate objects that interact with each other. An object contains both information and the means of accessing and
changing that information an efficient way to create computer programs that can be improved easily and used later
for other tasks. Java inherits many of its object-oriented concepts from C++ and borrows concepts from other
objectoriented languages as well.
Java Is Easy to Learn
Java was intended to be easier to write, compile, debug, and learn than other object-oriented languages. It was modeled
strongly after C++ and takes much of its syntax from that language. Despite Javas similarities to C++, the most
complex and error-prone aspects of that language have been excluded from Java. You wont find pointers or pointer
arithmetic because those features are easy to use incorrectly in a program and even harder to fix. Additionally, memory
management is handled automatically by Java rather than requiring the programmer to allocate and deallocate memory,
and multiple inheritance is not supported. Although Java is easier to learn than many other programming languages, a
person with no programming experience at all will find Java challenging. It is more complicated than working in
something such as HTML or JavaScript, but definitely something a beginner can accomplish.
Java Is Platform Neutral
Because it was created to run on a wide variety of devices and computing platforms, Java was designed to be platform
neutral, working the same no matter where it runs. The original goal for Java programs to run without modification on
all systems has not been realized. Java developers routinely test their programs on each environment they expect it to be
run on, and sometimes are forced into cumbersome workarounds as a result. However, Javas platform-neutral design
still makes it much easier to employ Java programs in a diverse range of different computing situations. As with all
high-level programming languages, Java programs are originally written as source code, a set of programming
statements entered into a text editor and saved as a file.

When you compile a program written in most programming languages, the compiler translates your source file into
machine code (Object Code) instructions that are specific to the processor your computer is running. If you compile
your code on a Windows system, the resulting program will run on other Windows systems but not on Macs or other
machines. If you want to use the same program on another platform, you must transfer your source code to the new

platform and recompile it to produce machine code specific to that system. In many cases, changes to the source will be
required before it will compile on the new machine, because of differences in its processors and other factors. Java
programs are compiled into machine code for a virtual machine a sort of computer-within-acomputer. This machine
code is called bytecode, and the virtual machine interprets this code by convertingit into a specific processors machine
code. The virtual machine is more commonly known as the Java interpreter, and every environment that supports Java
must have an interpreter tailored to its own operating system and processor. Java also is platform neutral at the source
level. Java programs are saved as text files before they are compiled, and these files can be created on any platform that
supports Java. For example, you could write a Java program on a Windows 98 machine, upload it to a Linux machine
over the Internet, and then compile it. Java interpreters can be found in several places. For applets, the interpreter is
either built into a Javaenabled browser or installed separately as a browser plug-in. The interpreter does cause some
significant performance issues as a rule, Java bytecode executes more slowly than platform-specific machine code
produced by a compiled language such as C or C++.

Sun, IBM, Symantec and other Java developers are addressing this with technology such as HotSpot, a new faster virtual
machine included with Java 2, and compilers that turn bytecode into platform-specific machine code. Every new
generation of processors also increases Javas sometimes-laggard performance. The architecture neutral (or platform
independent) feature of Java makes it highly suitable for Internet programming. The way it happens with Java: your
source code is translated to machine code (called Bytecode) for an imaginary machine - the Java Virtual Machine
(JVM). Figure 2.2 shows compilation of a Java program on different machines.
Error handling
Error handling in C is a notorious problem, and one that is often ignoredfinger-crossing is usually involved. If youre
building a large, complex program, theres nothing worse than having an error buried somewhere with no clue as to
where it came from. Java exception handling is a way to guarantee that an error is noticed, and that something happens
as a result.
Distributed
Java is designed as a distributed language for creating applications on networks. It has the ability to share both data and
programs. Java applications can open and access remote objects on Internet as easily as they do in a local system. This
enables multiple programmers at multiple remote locations to collaborate
and work together on a single object.
Multithreaded
Java supports multithreaded programs. This means that we need not wait for the application to finish one task before
starting another. For example, we can listen to an audio clip while scrolling down a page and at the same time download
an applet from a distant computer. This feature improves the interactive performance of graphical applications.
JAVA ENVIRONMENT
Java environment includes a large number of development tools and hundreds of classes and methods. The
development tools are part of system known as Java Development Kit (JDK) and the classes and methods are part
of the Java Standard Library, also known as Application Programming Interface (API).
javac is the java compiler. It creates bytecode for applications, applets and servlets. The file containing your java source
code must end with the file extension .java. The output (bytecode) is stored in one or more files with a .class extension
java is the Java interpreter. To run an application you must enter the java command followed by the name of the class
you want to run (and any command line arguments you want to pass to the program). appletviewer is the utility that
runs applets outside a Web browser. You must follow the command with the name of the html document file with

<applet> tag. jdb is the Java debugger. It has limited functionality. You may find it more useful to include
System.out.println statements in your program. javadoc generates a collection of HTML documents that make up online
documentation for the classes used in your application. You need to include javadoc comments including tags in your
source code to fully utilize this tool.
native2ascii is a tool which converts the files from Unicode to ASCII. Useful if you are developing software for the
international market.
jar is a utility which combines several files into a single Java archive (JAR) file - known as .jar files. A JAR file is like a
zip file except that the data is not always compressed and is convenient for distribution. It can combine resources such
as sound clips or graphics together with the files that use them. Downloading one JAR file is much more efficient than
downloading related files separately.

Steps used to compile a Java Program are


Step 1: Create a text file and store Java source code with the extension as .java.
Step 2: Use javac, JAVA compiler to get the class file
Step 3: Use java, Interpreter to get the output.
VERSIONS OF JAVA
Sun has released four major versions of the Java language:
Java 1.0 A small Web-centered version uniformly available in all popular Web browsers Chapter 26 2 - Java
Evolution
Java 1.1 A 1997 release with improvements to the user interface, completely rewritten event handling, and a
component technology called JavaBeans
Java 2 with SDK 1.2 A significantly expanded version released in 1998 with retooled graphical user interface
features, database connectivity, and many other improvements
Java 2 with SDK 1.3 A 2000 release that adds new core features such as improved multimedia, more accessibility,
and faster compilation A Java development kit has always been available at no cost from Suns Java Web site, and this
availability is one of the factors behind the languages rapid growth. It is the first development tool that supports new
versions of Java, often six months to a year before other Java development software.
JAVA PACKAGES
A package is a collection of classes which logically fit together and which may interact between themselves.
applet - for creating Java programs to run on the Web

awt - the original toolkit for graphics and graphical user interfacing
swing - extensive set of lightweight components built on top of awt
event - for managing program events
io - for managing program input and output
lang - for routine functions
net - for networking
util - for additional useful utilities
PROGARM STRUCTURE
A java program may contain many classes of which only one class defines a main method. Classes contain data
members and methods that operate on the data members of the class. A java program may contain one or more sections

as shown in the figure 2.4.


Documentation Section
This section comprises of a set of comment lines giving the names of the program, author and other relevant details
about the program. Documentation comment uses /** and */ . This form of comment is used for generating HTML
documentation automatically.
Package Section
This statement declares the package name and informs the compiler that the classes defined here belong to this package.
Example package packageName;
The package statement is optional.
Import Statements
Similar to #include in C/C++ we have import statements in JAVA. This statement instructs the interpreter to load the
classes contained in the package specified.
import student.*;
The above statement instructs the interpreter to load all the classes in the package named student. If the import statement
is as follows: import student.PGstudents;
Then it instructs the interpreter to load a specific class named PGstudents from the package student. By default all
java programs import java.lang.* package. If any other packages are required only then import statements need to be
used.
Interface Statement
An interface is like a class but includes a group of method declarations. This is also an optional statement and used only
when required.
Class Definitions
A java program may contain multiple class definitions. Classes are primary and essential elements of java program.
These classes are used to map the objects of real-world problems.
Main Method Class

Since every java stand-alone program requires a main method as its starting point, this class is essential part of any Java
program.
Applet Programming
INTRODUCTION
Every applet is implemented by creating a subclass of the Applet class. The following figure shows the inheritance
hierarchy of the Applet class.

The Simplest Java Applet


The Java programming language and libraries enable you to create applets that are as simple or as complex as you like.
In fact, you can write the simplest Java applet in only a few lines of code.
MyApplet.java: The Simplest Java Applet.
import java.applet.*;
public class MyApplet extends Applet
{
}
The first line of Listing tells the Java compiler that this applet will be using some or all of the classes defined in the
applet package (the asterisk acts as a wildcard, just as in DOS file names). All of the basic capabilities of an applet are
provided for in these classes, which is why you can create a usable applet with so few lines of code. The second line of
code declares a new class called MyApplet. This new class is declared as public so that the class can be accessed when
the applet is run in a Web browser or in the Appletviewer application. If you fail to declare the applet class as public, the
code will compile fine, but the applet will refuse to run. In other words, all applet classes must be public. As you can
see, you take advantage of object-oriented programming (OOP) inheritance to declare your applet class by subclassing
Javas Applet class. The only difference is that Applet is a class thats included with the Java Developers Kit (JDK),
rather than a class you created yourself. Compile the applet shown to get the MyApplet.class file, which is the byte-code
file that can be executed by the Java system. To run an applet, just create an HTML document. If you were to run the
MyApplet applet, however, you wouldnt see anything much in Appletviewer or in your Web browser.
The APPLET Tag
When you build <APPLET> tags, keep in mind that words such as APPLET and CODEBASE can be typed in either as
shown or in any mixture of uppercase and lowercase. Bold font indicates something you should type in exactly as
shown (except that letters dont need to be uppercase). Italic font indicates that you must substitute a value for the word
in italics. Square brackets ([ and ]) indicate that the contents of the brackets are optional.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile //mandatory
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels //mandatory
HEIGHT = pixels //mandatory
Chapter 9 158 - Applet Programming
PDF created with pdfFactory Pro trial version www.pdffactory.com
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>

[< PARAM NAME = appletParameter1 VALUE = value >]


[< PARAM NAME = appletParameter2 VALUE = value >]
...
[alternateHTML]
</APPLET>
CODEBASE = codebaseURL
This optional attribute specifies the base URL of the applet the directory or folder that contains the applets code. If
this attribute is not specified, then the documents URL is used.
CODE = appletFile
This required attribute gives the name of the file that contains the applets compiled Applet subclass. This file is relative
to the base URL of the applet. It cannot be absolute.
ALT = alternateText
This optional attribute specifies any text that should be displayed if the browser understands the APPLET tag but cant
run Java applets.
NAME = appletInstanceName
This optional attribute specifies a name for the applet instance, which makes it possible for applets on the same page to
find (and communicate with) each other.
WIDTH = pixels
HEIGHT = pixels
These required attributes give the initial width and height (in pixels) of the applet display area, not counting any
windows or dialogs that the applet brings up.
ALIGN = alignment
This optional attribute specifies the alignment of the applet. The possible values of this attribute are the same (and have
the same effects) as those for the IMG tag: left, right, top, texttop, middle, absmiddle, baseline, bottom, absbottom.
VSPACE = pixels
HSPACE = pixels
These optional attributes specify the number of pixels above and below the applet (VSPACE) and on each side of the
applet (HSPACE). Theyre treated the same way as the IMG tags VSPACE and HSPACE attributes.
< PARAM NAME = appletParameter1 VALUE = value >
<PARAM> tags are the only way to specify applet-specific parameters. Applets read user-specified values for
parameters with the getParameter() method.
alternateHTML
If the HTML page containing this <APPLET> tag is viewed by a browser that doesnt understand the <APPLET> tag,
then the browser will ignore the <APPLET> and <PARAM> tags, instead interpreting any other HTML code between
the <APPLET> and </APPLET> tags. Java-compatible browsers ignore this extra HTML code.
Here is an example HTML document for the applet MyApplet
MYAPPLET.html: MyApplets HTML Document.
<title>Applet Test Page</title>
<h1>Applet Test Page</h1>
<applet
code=MyApplet.class
width=250
height=250
name=MyApplet>
</applet>

LIFE CYCLE OF AN APPLET


Every Java applet you create inherits a set of default behaviors from the Applet class. In most cases, these default
behaviors do nothing, unless you override some of Applets methods in order to extend the Chapter 9 160 - Applet
Programming applets basic functionality. However, although a simple applet like MyApplet doesnt seem to do much, a
lot is going on in the background. Figure 9.2 shows different stages in the life cycle of an Applet.

There are five parts to this cycle, each of which has a matching method that you can override to gain access to that cycle
of the applets life. The five stages of an applets life cycle are listed here:
Initialization stage. This is the part of an applets life cycle in which the applet object is created and loaded. At this
point, its appropriate to create objects needed by the applet, as well as initialize v alues that must be valid when the
applet runs. The initialization stage occurs only once in the applets life cycle. You can tap into the initialization stage by
overriding the Applet classs init() method.
Start stage. This stage occurs when the system starts running the applet. The start stage can occur right after the
initialization stage or when an applet is restarted. This usually happens when the user switches back to the applets page
after viewing a different page in his or her Web browser. Unlike the initialization stage, the start stage can occur several
times over the life of the applet. To provide your own start code, override the Applet classs start() method.
Paint stage. The paint stage occurs whenever the applets display must be drawn on the screen. This happens right after
the applets start stage, as well as whenever the applets display must be restored or changed. This can happen when the
applet is exposed fromunderneath another window or when the program changes the applets display in some way and
explicitly repaints the applet. Almost every applet you write will have a paint() method, which is the method you
override to provide your applet with its display.
Stop stage. As you may have guessed, the stop stage is the counterpart to the start stage. Java executes this stage of the
applets life cycle when the applet is no longer visible on the screen, such as when the user switches to a different Web
page. The default behavior for this cycle, however, is to keep the applet running in the background. If you want to
handle the stop cycle differently, you should override the Applet classs stop() method.
Destroy stage. This is the counterpart to the initialization stage and occurs when the system is about to remove the
applet from memory. Like the initialization cycle, the destroy cycle occurs only once. If your applet has resources that
need to be cleaned up before the applet exits, this is the place to do it. You tap into this cycle by overriding the Applet
classs destroy() method.
Example: Overriding the Life Cycle Methods
All this talk about life cycles and overriding methods may have left you a little confused as to how all this actually
applies to the applets you want to create. In previous chapters, you managed to create applets without dealing with most
of this stuff because the Applet class, from which you derived your own applet classes, handled the life-cycle methods in
the default manner proscribed by the Java system. If you look at Listing 15.3, youll see a small applet that overrides all
the methods needed to provide custom behaviors for all the applets life-cycle stages.
Overriding the Applet Life-Cycle Methods.
import java.applet.*;
import java.awt.*;
public class MyApplet2 extends Applet
{
public void init()
{

// Place initialization cycle code here.


}
public void start()
{
// Place start cycle code here.
}
public void paint(Graphics g)
{
// Place paint cycle code here.
}
public void stop()
{
// Place stop cycle code here.
}
public void destroy()
{
// Place destroy cycle code here.
}
}
Notice that in order to override the paint() method, you must import the java.awt.* libraries, which contain information
about the Graphics class. As you learned when writing previous applets in this book, the Graphics class enables you to
display information and graphics in an applets display area. If you look for the previous methods in Javas source code,
youll discover that the default implementations of init(), start(), paint(), stop(), and destroy() all do nothing at all. If you
want your applet to do something in response to these cycles, you have to provide the code yourself by overriding the
appropriate method.
LOCAL AND REMOTE APPLETS
One of Javas major strengths is that you can use the language to create dynamic content for your Web pages. That is,
thanks to Java applets, your Web pages are no longer limited to the tricks you can perform with HTML. Now your Web
pages can do just about anything you want them to. All you need to do is write the appropriate applets. But writing Java
applets is only half the story. How your Web pages users obtain and run the applets is equally as important. Its up to
you to not only write the applet (or use someone elses applet), but also to provide users access to the applet. Basically,
your Web pages can contain two types of applets: local and remote. In this section, you learn the difference between
these applet types, which are named after the location at which they are stored.
Local Applets
A local applet is one that is stored on your own computer system. When your Web page must find a local applet, it
doesnt need to retrieve information from the Internet-in fact, your browser doesnt even need to be connected to the
Internet at that time.
Specifying a Local Applet.
<applet
codebase=tictactoe
MSIT 13 Oops with Java 163
PDF created with pdfFactory Pro trial version www.pdffactory.com
code=TicTacToe.class
width=120
height=120>
</applet>
The codebase attribute specifies a path name on your system for the local applet, whereas the code attribute specifies the
name of the byte-code file that contains the applets code. The path specified in the codebase attribute is relative to the
folder containing the HTML document that references the applet.
Remote Applets

A remote applet is one that is located on another computer system. This computer system may be located in the building
next door or it may be on the other side of the world-it makes no difference to your Java-compatible browser. No matter
where the remote applet is located, its downloaded onto your computer via the Internet. Your browser must, of course,
be connected to the Internet at the time it needs to display the remote applet. To reference a remote applet in your Web
page, you must know the applets URL (where its located on the Web) and any attributes and parameters that you need
to supply in order to display the applet correctly. If you didnt write the applet, youll need to find the document that
describes the applets attributes and parameters. The applets author usually writes this document.
Specifiying a Remote Applet.
<applet
codebase=http://www.myconnect.com/applets/
code=TicTacToe.class
width=120
height=120>
</applet>
The only difference between local applet and remote applet accessing is the value of the codebase attribute. In the first
case, codebase specifies a local folder, and in the second case, it specifies the URL at which the applet is located.
CREATING AN APPLET
Importing Classes and Packages
The first two lines of the following listing import two classes used in the applet: Applet and Graphics.
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString(Hello world!, 50, 25);
}
}
If you removed the first two lines, the applet could still compile and run, but only if you changed the rest of the code like
this:
public class HelloWorld extends java.applet.Applet {
public void paint(java.awt.Graphics g) {
g.drawString(Hello world!, 50, 25);
}
}
As you can see, importing the Applet and Graphics classes lets the program refer to them later without any prefixes. The
java.applet. and java.awt. prefixes tell the compiler which packages it should search for the Applet and Graphics classes.
Both the java.applet and java.awt packages are part of the core Java API API that every Java program can count on
being in the Java environment. The java.applet package contains classes that are essential to Java applets. The java.awt
package contains the most frequently used classes in the Abstract Window Toolkit (AWT), which provides the Java
graphical user interface (GUI). Besides importing individual classes, you can also import entire packages. Heres an
example:
import java.applet.*;
import java.awt.*;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString(Hello world!, 50, 25);
}
}
In the Java language, every class is in a package. If the source code for a class doesnt have a package statement at the
top, declaring the package the class is in, then the class is in the default package. Within a package, all classes can refer
to each other without prefixes. For example, the java.awt Component class refers to the java.awt Graphics class without
any prefixes, without importing the Graphics class.
Defining an Applet Subclass
The first bold line of the following listing begins a block that defines the HelloWorld class. import java.applet.Applet;

import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString(Hello world!, 50, 25);
}
}
The extends keyword indicates that HelloWorld is a subclass of the class whose name follows: Applet. From the Applet
class, applets inherit a great deal of functionality. Perhaps most important is the ability to respond to browser requests.
For example, when a Java-capable browser loads a page containing an applet, the browser sends a request to the applet,
telling the applet to initialize itself and start executing. An applet isnt restricted to defining just one class. Besides the
necessary Applet subclass, an applet can define additional custom classes. When the applet attempts to use a class, the
application thats executing the applet first looks on the local host for the class. If the class isnt available locally, its
loaded from the location that the Applet subclass originated from.
Implementing Applet Methods
The bold lines of the following listing implement the paint method.
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString(Hello world!, 50, 25);
}
}
Every applet must implement one or more of the init, start, and paint methods. Besides the init, start, and paint methods,
applets can implement two more methods that the browser calls when a major event occurs (such as leaving the applets
page): stop and destroy. Applets can implement any number of other methods, as well. Returning to the above code
snippet, the Graphics object passed into the paint method represents the applets onscreen drawing context. The first
argument to the Graphics drawString method is the string to draw onscreen. The second and third arguments are the
(x,y) position of the lower left corner of the text onscreen. This applet draws the string Hello world! starting at
location (50,25). The applets coordinate system starts at (0,0), which is at the upper left corner of the applets display
area.
Running an Applet
The bold lines of the following listing comprise the <APPLET> tag that includes the Hello World
applet in an HTML page.
<HTML>
<HEAD>
MSIT 13 Oops with Java 167
PDF created with pdfFactory Pro trial version www.pdffactory.com
<TITLE> A Simple Program </TITLE>
</HEAD>
<BODY>
Here is the output of my program:
<APPLET CODE=HelloWorld.class WIDTH=150
HEIGHT=25>
</APPLET>
</BODY>
</HTML>
The above <APPLET> tag specifies that the browser should load the class whose compiled code is in the file named
HelloWorld.class. The browser looks for this file in the same directory as the HTML document that contains the tag.
When the browser finds the class file, it loads it over the network, if necessary, onto the computer the browser is running
on. The browser then creates an instance of the class. If you include an applet twice in one page, the browser loads the
class file once and creates two instances of the class. The WIDTH and HEIGHT attributes are like the same attributes in
an <IMG> tag: They specify the size in pixels of the applets display area. Most browsers do not let the applet resize

itself to be larger or smaller than this display area. For example, every bit of drawing that the Hello World applet does
in its paint method occurs within the 150x25-pixel display area that the above <APPLET> tag reserves for it.
HELLOWORLD APPLET
Now you will create a Java applet called HelloWorld, which also displays the greeting Hello world!. Unlike
HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, Netscape Navigator, or
Microsoft Internet Explorer. To create this applet, youll perform the basic steps as before: create a Java source file;
compile the source file; and run the program.
a. Create a Java Source File.
Again, you have two options:
You can save the files HelloWorld.java and Hello.html on your computer and avoid a lot of typing. Then, you can go
straight to step b.
Or, you can follow these instructions:
1. Start NotePad. Type the following code into a new document:
import java.applet.*;
import java.awt.*;
/**
* The HelloWorld class implements an applet that
* simply displays "Hello World!".
*/
public class HelloWorld extends Applet {
public void paint(Graphics g) {
// Display "Hello World!"
g.drawString("Hello world!", 50, 25);
}
}
Save this code to a file called HelloWorld.java.
2. You also need an HTML file to accompany your applet. Type the following code into a new NotePad document:
<HTML>
<HEAD>
<TITLE>A Simple Program</TITLE>
</HEAD>
<BODY>
Here is the output of my program:
<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>
Save this code to a file called Hello.html.
b. Compile the Source File.
At the prompt, type the following command and press Return:
javac HelloWorld.java
The compiler should generate a Java bytecode file, HelloWorld.class.
MSIT 13 Oops with Java 169
PDF created with pdfFactory Pro trial version www.pdffactory.com
c. Run the Program.
Although you can view your applets using a Web browser, you may find it easier to test your applets using the simple
appletviewer application that comes with the JavaTM Platform. To view the HelloWorld applet using appletviewer, enter
at the prompt:

WHAT APPLETS CAN AND CANT DO


This section gives an overview of both the restrictions applets face and the special capabilities they have.
Security Restrictions
Every browser implements security policies to keep applets from compromising system security. This section describes
the security policies that current browsers adhere to. However, the implementation of the security policies differs from
browser to browser. Also, security policies are subject to change. For example, if a browser is developed for use only in
trusted environments, then its security policies will likely be much more lax than those described here. Current browsers
impose the following restrictions on any applet that is loaded over the network:
An applet cannot load libraries or define native methods.
It cannot ordinarily read or write files on the host thats executing it.
It cannot make network connections except to the host that it came from.
It cannot start any program on the host thats executing it.
It cannot read certain system properties.
Windows that an applet brings up look different than windows that an application brings up.
Each browser has a SecurityManager object that implements its security policies. When a SecurityManager detects a
violation, it throws a SecurityException. Your applet can catch this SecurityException and react appropriately.
Applet Capabilities
The java.applet package provides an API that gives applets some capabilities that applications dont have. For example,
applets can play sounds, which other programs cant do yet. Here are some other things that current browers and other
applet viewers let applets do:
Applets can usually make network connections to the host they came from.
Applets running within a Web browser can easily cause HTML documents to be displayed.
Applets can invoke public methods of other applets on the same page.
Applets that are loaded from the local file system (from a directory in the users CLASSPATH) have none of the
restrictions that applets loaded over the network do.
Although most applets stop running once you leave their page, they dont have to.
INTRODUCTION
Object Oriented Programming (OOP) is an approach to program organization and development, which attempts to
eliminate some of the pitfalls of conventional programming methods by incorporating the best of structured
programming features with several new concepts. The world is object-oriented, and the object-oriented programming
paradigm attempts to express computer programs in ways that model how people perceive the world. An introductory
description of OOP can be based on the following guideline: The solution to the problem should resemble the problem,
and observers of the solution should be able to recognize the problem without necessarily knowing about it in advance.
A good example of this guideline from the computing world is the use of OOP to develop a stack class from which stack
objects can be instantiated. If a stack is implemented as a class, instantiated as an object, and documented appropriately,
programmers familiar with stacks, queues, and other similar data structures will recognize it as a stack without other
prior knowledge.

We are object-oriented creatures living in an object-oriented world. We tend to think in object-oriented ways. Previous
approaches to programming tend to separate the data from the methods used to manipulate that data, or at least dont
strongly encourage them to be considered in concert. The world and its applications are not organized into values and
procedures separate from one another. People who solve problems in other crafts do not perceive the world that way.
They deal with their problem domains by concentrating on the objects and letting the characteristics of those objects
determine the procedures to apply to them.
BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING
Objects
In the real world, objects are the entities of which the world is comprised. Everything that happens in the world is
related to the interactions between the objects in the world. The real world consists of many objects interacting in many
ways. While each object may not be overly complex, their myriad of interactions creates the overall complexity of the
natural world. It is this complexity that we wish to capture in our software systems. In an object-oriented software
system, objects are entities used to represent or model a particular piece of the system. Objects are the primary units
used to create abstract models. An object is characterized solely by it behaviors. Essentially this defines an object by the
way it interacts with its world. An object that does not interact with anything else effectively does not exist. Access to
internally stored data is necessarily through some sort of defined behavior of the object. It is impossible for an outside
entity to truly know whether or not a particular piece of data is being stored inside of another object. This does not
mean however, that an object may not contain data (information) in fields. The essence of the object is in how the object
behaves in relationship to or as a result of its data, should it contain any. The existence of data in an object is an
implementation technique used to generate the required behavior of that object.
Everything is an object. Think of an object as a fancy variable; it stores data, but you can make requests to that
object, asking it to perform operations on itself. In theory, you can take any conceptual component in the problem youre
trying to solve (dogs, buildings, services, etc.) and represent it as an object in your program.
A program is a bunch of objects telling each other what to do by sending messages . To make a request of an object,
you send a message to that object. More concretely, you can think of a message as a request to call a method that
belongs to a particular object.
Each object has its own memory made up of other objects. Put another way, you create a new kind of object by
making a package containing existing objects. Thus, you can build complexity into a program while hiding it behind the
simplicity of objects.
Every object has a type. Using the parlance, each object is an instance of a class, in which class is synonymous with
type. The most important distinguishing characteristic of a class is What messages can you send to it?
All objects of a particular type can receive the same messages. This is actually a loaded statement, as you will see
later. Because an object of type circle is also an object of type shape, a circle is guaranteed to accept shape
messages. This means you can write code that talks to shapes and automatically handle anything that fits the description
of a shape. This substitutability is one of the powerful concepts in OOP.
Classes
Many objects differ from each other only in the value of the data that they hold. For example, both a red crayon and a
blue crayon are crayons; they differ only in the value of the color attribute, one has a red color and the other a blue color.
Our object-oriented system needs a way to capture the abstraction of a crayon, independent of the value of its color. That
is, we want to express that a set of objects are abstractly equivalent, differing only in the values of their attributes and
perhaps, thus differing in the behaviors that result from those values. Many objects are similar in many overall,
generalized ways, differing only in smaller, more specific details. Object-oriented systems use classes to express abstract
equivalence. A class is an abstract description of a set of objects. A class thus contains the descriptions of all the
behaviors of the objects that it represents. In computer science parlance, we call the individual behaviors of a class its
methods. In addition, a class may, but not always, contain descriptions of the internal data held by the objects, called its
fields, as well as implementation details about its methods and fields. Turning the description around, we can say that a
class is a template or recipe for the creation of a particular type of object. That is, one can use a class to create
(instantiate) objects of the type described by the class. Be careful not to make the very beginners common mistake of
equating classes and objects. A class is a specification of a set of objects; it is not the actual object.
Messages
A single object alone is generally not very useful. Instead, an object usually appears as a component of a larger program
or application that contains many other objects. Through the interaction of these objects, programmers achieve higher-

order functionality and more complex behavior. Software objects interact and communicate with each other by sending
messages to each other. When object A wants object B to perform one of Bs methods, object A sends a message to
object B.
Sometimes, the receiving object needs more information so that it knows exactly what to do; for example, when you
want to change gears on your bicycle, you have to indicate which gear you want. This information is passed along with
the message as parameters. Messages provide two important benefits.
An objects behavior is expressed through its methods, so (aside from direct variable access) message passing
supports all possible interactions between objects.
Objects dont need to be in the same process or even on the same machine to send and receive messages back and
forth to each other.
Abstraction
The implicit characteristic of an object-oriented program is Abstraction. Abstraction is the specification of an abstract
data type, which includes a specification of the types data representation and behavior. In particular,
what kind of data can be stored in an entity of the new type, and
what are all the ways that that data can be manipulated.
For our purposes, an abstract data type is a new type (not intrinsic to the language). It is not one of the primitive data
types that are built into the programming language (such as int, long, float, etc.). The representation and behavior of an
abstract type is not known to the compiler until the programmer specifies it and presented to the compiler in an
appropriate manner.
How do we present the specification of an abstract type to the compiler? Java programmers define the data
representation and the behavior of a new type using the keyword class. In other words, in Java and C++, the keyword
class is used to convert the specification of a new type into something that the compiler can work with. Once the new
type is defined, one or more objects of that type can be brought into being (instantiated, caused to occupy memory).
Once instantiated, the object is said to have state and behavior. The state of an object is determined by the current
values of its data (instance variables) and the behavior of an object is determined by its methods (member functions or
instance methods).
Encapsulation
Another major characteristic of an object-oriented program is encapsulation. If abstraction is the design or specification
of a new type, then encapsulation is its definition and implementation.

A programmer encapsulates the data representation and behavior of an abstract data type into a class, thereby defining
its implementation and interface. According to good object-oriented programming practice, an encapsulated design
usually hides its implementation from the class user and reveals only its interface. This is accomplished in different
ways with different languages as described below. Just as most of us dont usually need to care about how the steering
mechanism of a car is implemented, a user of a class should not need to care about the details of implementation only
that it works as advertised. Of course this assumes that the user of the class has access to good documentation describing
the class.
Polymorphism
An important aspect of OOP is polymorphism. This is a Greek word meaning something like one name, many forms.
Polymorphism is used to customize the behavior of an instance of a type (an object) based on existing conditions. The
purpose of polymorphism as it applies to OOP is to allow one name to be used to specify a general class of actions.
Within a general class of actions, the specific action to apply in any particular instance is determined by the type of data
involved. More generally, the concept of polymorphism is the idea of one interface, multiple methods. Polymorphism
exists when functions are overloaded or overridden to cause them to perform operations not implicitly recognized by the
compiler.

Inheritance: Reusing the interface


By itself, the idea of an object is a convenient tool. It allows you to package data and functionality together by concept,
so you can represent an appropriate problem-space idea rather than being forced to use the idioms of the underlying
machine. These concepts are expressed as fundamental units in the programming language by using the class keyword.
It seems a pity, however, to go to all the trouble to create a class and then be forced to create a brand new one that might
have similar functionality. Its nicer if we can take the existing class, clone it, and then make additions and
modifications to the clone. This is effectively what you get with inheritance, with the exception that if the original class
(called the base class or superclass or parent class) is changed, the modified clone (called the derived class or
inherited class or subclass or child class) also reflects those changes.

BENEFITS OF OOP
OOP offers several benefits to both program designer and the user. The new technology promises greater programmer
productivity, better quality of software and lesser maintenance cost. The principal advantages are as follows:
Easy to partition the work based on Objects.
Easy to upgrade.
Eliminates redundant code through Inheritance.
Reusability leads to higher productivity.
Software complexity can be easily managed.
Software that is easy to use is hard to build. It is hoped that the object-oriented programming languages like C++ and
Java would help manage this problem.
APPLICATIONS OF OOP
OOP is useful in many areas of applications. Using the concepts of OOP we can solve any complex problem. The
promising areas for application of OOP includes:
Real time Systems
Simulation and Modeling
Object Oriented Databases
Hypermedia
AI and expert systems
CAD/CAM system
Neural networks etc.,
It is believed that OOP environment will enable the software industry to improve not only the quality of software
systems but also its productivity.
Constructors
The allocation, reclamation, and reuse of dynamic memory from the heap is an important aspect of most object-oriented
programs, and some non-object-oriented programs as well. The next few sections discuss how these requirements are
met with respect to objects in Java and C++. Other object-oriented language use other techniques to accomplish the
same objectives:
to allocate memory when it is needed by the program,
to reclaim that memory when it is no longer needed, and
to reuse it as appropriate.

Failure to deal with this important issue results in a condition often referred to as memory leakage. Both Java and C++
and possibly other object-oriented languages as well, support the notion of a onstructor. The following Java code
fragment shows a constructor at work
. //instantiate an object of the class Oop01 in Java
Oop01 obj = new Oop01();
A constructor is a special method of a class that is used to instantiate (and optionally initialize) a new object of the class
type. In the above statement, the invocation of the constructor method is highlighted in boldface. Constructors can be
overloaded just like other methods in Java and C++. In this particular statement, the new operator is used to allocate
dynamic memory from the heap, and the constructor is used to construct the object in that memory space. The address of
the memory containing the object is returned and assigned to the reference variable named obj. If the memory cannot be
allocated, an exception will be thrown.
In Java and C++, if you do not define a constructor when you define a new class, a default constructor that takes no
parameters is defined on your behalf. This is often referred to as the default constructor or the noarg constructor. It is
also possible for you to define a constructor for your class which takes no arguments and which performs some special
action when it is invoked. Defining a constructor is only slightly different from defining any other method in Java or C+
+ (it must have the same name as the class, does not have return type, and must not have a return statement). Although
you are free to cause your constructor to perform just about any action that you want, the intended purpose of a
constructor is to perform some form of initialization (open a file, initialize instance variable values, etc.) If you provide
such a noarg constructor, it will be invoked in place of the default constructor when you invoke the constructor as
shown in the above code fragment with no arguments. The constructor shown above is a Java constructor. The
invocation of a constructor in C++ is even simpler. An example is shown below:
Oop01 obj; //instantiate an object of the class Oop01 in C++
C++ provides other formats for invoking the constructor in addition to that shown above. It is also possible for you to
define one or more overloaded versions of the constructor that do take parameters. These are commonly called
parameterized constructors. Typically you will include code in the body of the constructor to use the arguments passed
as parameters for some sort of initialization, but again, you can write the code to perform just about any action that you
want. The following code fragment shows the important parts of a Java program, similar to the previous one which has
been modified to use a parameterized constructor.
Oop02(int iV, int cV){ //parameterized constructor
instanceVariable = iV; //initialize the instance variable
classVariable = cV; //initialize the class variable
}//end parameterized constructor
...
public static void main(String[] args){
//instantiate an object of the class Oop02
Oop02 obj = new Oop02(2,3);
This code fragment shows the parameterized constructor method named Oop02 and then shows the statement used in
the main method to instantiate and initialize an object of the class Oop02 named obj. As you can see, the parameterized
constructor in Java looks just like a method except that it has no return type or return statement.
Adding a Constructor to a Class.
class MyClass
{
int myField;
public MyClass(int value)
{
myField = value;
}
}
As you can see, the classs constructor starts with the public keyword. This is important because you want to be able to
create an object from the class anywhere in your program, and when you create an object, youre actually calling its
constructor. After the public keyword comes the name of the constructor followed by the constructors arguments in
parentheses. When you create an object of the class, you must also provide the required arguments. Example: Creating
an Object by Calling a Constructor If you want to create an object from MyClass, you must supply an integer value that

the class uses to initialize the myField data field. This integer is the MyClass constructors single argument. Youd create
an object of the class like this:
MyClass myObject = new MyClass(1);
This line not only creates an object of the MyClass class, but also initializes the myField data field to 1. The first word
in the line tells Java that myObject is going to be an object of the MyClass class. The next word is the objects name.
After the equals sign comes the keyword new and the call to the classs constructor.
Constructors are
automatically executed when an object is created
used to initialize instance variable belonging to the class -> good programming practice!
may be overloaded to give alternative ways of initializing objects
Eg Circle c = new Circle(5);
Circle b = new Circle();
should always provide a constructor for declaring an object with no arguments (builtin in Java 1.1)
Using Objects
Once youve created an object, you probably want to use it for something. You may need information from it, want to
change its state, or have it perform some action. Objects give you two ways to do these things:
1. Manipulate or inspect its variables.
2. Call its methods.
Referencing an Objects Variables
The following is the general form of a qualified name, which is also known as a long name:
objectReference.variableName
Calling an Objects Methods
You also use qualified names to call an objects method. To form the qualified name of a method, you append the
method name to an object reference, with an intervening period (.). Also, you provide, within enclosing parentheses, any
arguments to the method. If the method does not require any arguments, use empty parentheses.
objectReference.methodName(argumentList);
or
objectReference.methodName();
The garbage collector automatically cleans up unused objects. An object is unused if the program holds no more
references to it. You can explicitly drop a reference by setting the variable holding the reference to null. This program
ClassDemo.java demonstrates the usage of period to access the variable and method of a class.
class ClassDemo
{
public static void main(String arg[])
{
cal ob=new cal();
ob.set(); //referencing an objects method
ob.disp();
System.out.println(ob.add());
System.out.println(ob.sub());
}
}
class cal
{
int x,y;
int add()
{
return(x+y);
}
int sub()
{
return(x-y);
}
void set()

{
x=10;
y=5;
}
void disp()
{
System.out.println(x+\t+y);
}
}
A destructor is a special method typically used to perform cleanup after the program no longer needs
an object. C++ supports destructors, but Java does not support destructors. Other object-oriented languages
may or may not support destructors.
Garbage Collection
Java supports another mechanism for returning memory to the operating system when it is no longer needed by an
object: garbage collection. The garbage collector is a part of the runtime system that runs in a low-priority thread
reclaiming memory that is no longer needed by objects used by the program. An object becomes eligible for garbage
collection in Java when there are no longer any reference variables that reference the object. In Java, you can have one
or more reference variables, which reference the same object. That object will not become eligible for garbage
collection until all of those reference variables go out of scope, are assigned to a different object, or are assigned a value
of null.
INSTANCE AND CLASS VARIABLES
Instance Variables
Instance variables are those data members of a class that are defined such that every individual instance of the class
(object) has its own set of variables, totally independent of the variables associated with all other objects of the same or
different classes. In other words, each object has its own memory space where its own set of variables is stored. Because
instance variables are bound to an object, they can be accessed only by way of the object to which they are bound.
Assuming that access to an instance variable is not prohibited by access control mechanisms (such as the use of the
keyword private), it is usually accessed by joining the name of the object (or the name of a pointer to the object) to the
name of the instance variable using the appropriate joining operator. The joining operator for Java is a simple period
(sometimes called the dot operator). The joining operator for C++ depends on whether the instance variable is being
accessed using the name of the object or the name of a pointer to the object. When the name of the object is used, the
joining operator is a simple period. When the name of a pointer to the object is used, the pointer operator (->) is used.
Chapter 4 - Classes, 86 Objects and Methods Other languages may use different methods for accessing the instance
variables of an object.
Class Variables
Class variables are those data members of a class that are shared among all objects of the class. Its not too far-fetched to
think of them as quasi-global variables whose accessibility is restricted only to objects of a particular class, or to the
class itself. In other words, only one copy of a class variable exists in memory and all objects of the class can access that
copy. An important characteristic of class variables is that they can also be accessed without the requirement to
instantiate an object of the type. In this case, they are usually accessed using the name of the class joined to the name of
the variable using the appropriate joining operator. The joining operator for Java is a simple period. In Java and C++,
class variables are designated as such using the static keyword. (Designation of a class variable in C++ also involves a
requirement to re-declare the variable outside the class definition.) Also in Java and C++, member variables declared
without the use of the static keyword are instance variables. In other words, by default, all member variables of a class
are instance variables unless you designate them as class variables using the static keyword.
INSTANCE AND CLASS METHODS
Note the following very important statements: The methods of a class have direct access to the member variables of the
same class regardless of their access control designation such as public, private, or protected (except that class methods
can usually access only class variables). There is no requirement for the code in a method of the class to use either the
name of an object or the name of the class to access the member variables of the same class. The methods of a class

come in two varieties: instance methods and class methods. As with instance and class variables, those methods
designated static are class methods in Java and C++. Methods not designated static are instance methods.
Instance Methods
An instance method can only be invoked by way of an object of the class. In that sense, an instance method is bound to
an object. However, unlike an instance variable, an object normally doesnt have its own separate copy of an instance
method. It would be wasteful of memory resources to provide a separate copy of every instance method for every object
of a class. It is very important to understand that when an instance method is invoked on a particular object, and when
the code in that method needs to access an instance variable of the class, it will access the particular copy of the instance
variable belonging to the object on which it was invoked. It is this ability to temporarily bind the method to the instance
variables of the object on which the method is invoked that causes it to behave as an instance method.
The this Pointer or Reference
Instance methods in Java and C++ (and perhaps other object-oriented languages as well) exhibit another interesting
characteristic. In particular, whenever an instance method is invoked, a pointer variable or reference variable named this
comes into existence automatically. This reference variable refers to the object on which the method was invoked, and
can be used by the code in the method for any purpose that a reference to that object might be needed.
Class Methods
Class methods can only access other class members (class variables or other class methods). They cannot access
instance variables or instance methods. The most important thing about class methods is that they can be accessed using
the name of the class without a requirement to instantiate an object of the class. As with class variables, class methods
can be accessed by joining the name of the class to the name of the method using the appropriate joining operator.
Sample Program
Much of what we have been discussing can probably be better understood when seen in the context of an actual
program. The following sample program illustrates the use of class and instance variables along with class and instance
methods in a Java program. This is not an attempt to teach the Java programming language at this point. Rather, it is
simply an attempt to illustrate OOP concepts using an actual Java program as the vehicle. As before, because of the
access control complexity caused by the package concept in Java, and the desire to keep this sample program as simple
as possible, no attempt was made to hide the implementation. When compiled and executed, this program will produce
the following output on the standard output device. You might want to remember this place so that you can refer to it as
you examine the program.
A - Instance variable contains 5
Chapter 4 - Classes, 88 Objects and Methods
B - Class variable contains 10
C - Class variable contains 10
Before we take a look at the complete program, lets examine some of the interesting code fragments that make up the
program. The first interesting code fragment shows the declaration of two member variables of the class. One is a class
variable named classVariable and the other is an instance variable named instanceVariable.
int instanceVariable; //declare an instance variable
static int classVariable; //declare a class variable
These are typical variable-declaration statements in Java and C++ consisting of the name of the type followed by the
name of the variable. The important thing to note in the context of this discussion is the use of the statickeyword in the
declaration of the class variable. The next code fragment shows the definitions of two methods (with the bodies of the
methods deleted for brevity). One of these methods is a class method named classMethod and the other is an instance
method named instanceMethod.
void instanceMethod(){//define an instance method
//body of method deleted for brevity
} //end instanceMethod()
static void classMethod(){//define a class method
//body of method deleted for brevity
} //end classMethod()
Again, these are typical method or member function definitions for Java and C++ consisting of the name of the return
type (where void means that nothing is returned) followed by the name of the method, followed by the formal argument

list (which happens to be empty in this case). The body of the method is then enclosed within a matching pair of curly
braces { }. Again, the important thing to note in the context of this discussion is the use of the static keyword in the
definition of the class method. The next code fragment is a single statement taken from the body of one of the methods.
This statement causes output to be displayed on the standard output device. This single statement incorporates classes,
class variables, instance methods, and overloaded operators, and illustrates some of the syntactical complexity that can
be encountered in object-oriented programming.
System.out.println(
A - Instance variable contains + instanceVariable);
This is a Java statement. A completely different syntax would be required to achieve the same result in C++.
Note first that this statement has three elements joined with periods. The first element is the word System which is the
name of one of the classes in the standard Java class library. As background information, the System class is
automatically loaded whenever a Java application is started. The name of the System class is joined to the word out
using a period. The word out is the name of a member variable of the System class. The member variable named out is
a public class variable. This makes it possible to access the variable using the name of the class and the name of the
variable joined by the period. Note that the class variable named out is also joined to the word println using the period
as the joining operator. The variable out is not only a class variable, it is also a reference variable (as opposed to a
primitive variable) and it contains a reference to an object of the PrintStream class. The PrintStream class has an
instance method named println(). In fact, there are ten overloaded versions of the println() method in the PrintStream
class. The behavior of the version used here is to cause its string argument to be displayed on the standard output device.
Now consider the string argument to the println method as shown below: (A - Instance variable contains +
instanceVariable) In Java (and C++ as well), literal strings are enclosed in quotation marks. You will note that not
everything in this argument is enclosed in quotation marks. Note in particular the plus sign near the middle of the
argument. In Java, the plus sign is overloaded so that in addition to being used as an arithmetic addition operator, it is
also used to concatenate strings.
An overloaded operator exhibits different behavior depending of the types of its operands. Furthermore, the behavior of
the overloaded plus operator also includes the ability to coerce its right operand into a string representation if it isnt
already a string. In this case, the right operand is not a string, but rather is the instance variable named
instanceVariable. Thus the behavior of the overloaded plus operator is to first convert the value of instanceVariable to
a string representation and than to concatenate it to the left operand. Some object-oriented languages such as C++ allow
the programmer to overload almost all of the operators so as to define the behavior of those operators when used with
operands of new abstract data types. However, Java does not provide that capability. In this case, the plus operator is
intrinsically overloaded by the system.
Now lets take another look at the same two methods as before, this time preserving the bodies of the methods for
further examination.
void instanceMethod(){ //define an instance method
System.out.println(
A - Instance variable contains + instanceVariable);
System.out.println(
B - Class variable contains + classVariable);
} //end instanceMethod()
static void classMethod(){ //define a class method
System.out.println(
C - Class variable contains + classVariable);
}//end classMethod()
Here we see the code in the body of the methods accessing the member variables of the class. Recall that one of the
member variables is an instance variable named instanceVariable and the other member variable is a class variable
named classVariable. The instance method named instanceMethod is able to access and display both the instance
variable and the class variable while the class method named classMethod is only allowed to access and display the
class variable. Class methods cannot access instance variables. Now consider the contents of the main method as shown
below. Both Java and C++ applications (not applets) require a main method or function as the controlling method of the
application. In our simple application, we will use code in the main method to instantiate an object and to access both
the instance method and the class method. Recall that in order to access an instance method, it is necessary to access it
via an object of the class. The next code fragment is the code in the main method that instantiates an object named obj
of the class named Oop01.
//instantiate an object of the class Oop01

Oop01 obj = new Oop01();


This is a typical Java statement for instantiating an object and is similar to one form of statement that can be used to
instantiate an object in C++. (C++ provides other forms as well.) This statement uses the new operator to request that
the operating system provide memory from the heap to store one copy of an object of type Oop01. If the required
memory is successfully allocated, the address of that block of memory will be assigned to the reference variable named
obj. If unsuccessful, the Java runtime system will throw an exception. This is a type of exception which can either be
ignored, or can be caught and processed by the program. If ignored, it will cause the runtime system to shut down the
program. (Exception handling is discussed later in this lesson.)
Both Java and C++ support exception handling, but do so in slightly different ways. Once we have access to an object of
the class (or more correctly access to a reference variable which refers to an object of the class), we can use that
reference variable to access the public member variables and to invoke the public methods of the class. This is illustrated
in the following code fragment. The two statements in the following code fragment use the reference variable named obj
along with the period to access the instance variable and the instance method of the object. Recall that the instance
variables and the instance methods can be accessed only via an object of the class. obj.instanceVariable = 5; //access
instance variable via the object
obj.instanceMethod(); //access instance method via the object
Equally important is the fact that the class variable and the class method can be accessed without the requirement to use
an object of the class. The two statements in the following code fragment simply use the name of the class to access the
class variable and the class method of the class.
Oop01.classVariable = 10; //access class variable via the class
Oop01.classMethod(); //access class method via the class
Class variables and class methods can be accessed either via an object of the class, or via the name of the class alone.
However, this sample program does not illustrate accessing class variables and methods using an object of the class.
Finally, we put it all together in the Java application shown below.
/*
The output from this program is:
A - Instance variable contains 5
B - Class variable contains 10
C - Class variable contains 10
**********************************************************/
class Oop01{ //define controlling class
int instanceVariable; //declare an instance variable
static int classVariable; //declare a class variable
void instanceMethod(){ //define an instance method
System.out.println(
A - Instance variable contains + instanceVariable);
System.out.println(
B - Class variable contains + classVariable);
} //end instanceMethod()
static void classMethod(){//define a class method
System.out.println(
C - Class variable contains + classVariable);
} //end classMethod()
public static void main(String[] args){
//instantiate an object of the class Oop01
Oop01 obj = new Oop01();
//access instance variable via the object
obj.instanceVariable = 5;
//access class variable via the class
Oop01.classVariable = 10;
//access instance method via the object
obj.instanceMethod();
//access class method via the class
Oop01.classMethod();
} //end main()

} //end class Oop01


METHOD OVERLOADING
A problem arises when mapping the concept of nuance in human language onto a programming language. Often, the
same word expresses a number of different meaningsits overloaded. This is useful, especially when it comes to so
the listener doesnt need to make any distinction about the action performed. Most human languages are redundant, so
even if you miss a few words, you can still determine the meaning. We dont need unique identifierswe can deduce
meaning from context. This program Sum.java demonstrates polymorphism by overloading the same function sum with
different
parameter list.
class Sum {
public static void main(String arg[]){
int x=10,y=30,z=50;
float a=3.45f,b=45.678f;
System.out.println(sum(a,b));
System.out.println(sum(x,y,z));
System.out.println(sum(x,y));
}
static int sum(int a, int b){
return(a+b);
}
static float sum(float a, float b){
return(a+b);
}
static int sum(int a, int b, int c){
return(a+b+c);
}
}
First call sum(a,b) invokes sum(float,float) method. The second call sum(x,y,z) invokes the method sum(int,int,int) and
the last call sum(x,y) invokes the first method defined that is sum(int,int). In Java, another factor forces the overloading
of method names: the constructor. Because the constructors name is predetermined by the name of the class, there can
be only one constructor name. But what if you want to create an object in more than one way? For example, suppose
you build a class that can initialize itself in a standard way or by reading information from a file. You need two
constructors, one that takes no arguments (the default constructor also called the no-arg constructor), and one that takes
a String as an argument, which is the name of the file from which to initialize the object. Both are constructors, so they
must have the same namethe name of the class. Thus, method overloading is essential to allow the same method name
to be used with different argument types. And although method overloading is a must for constructors, its a general
convenience and can be used with any method. Heres an example that shows both overloaded constructors and
overloaded ordinary methods:
// Demonstration of both constructor
// and ordinary method overloading.
class Tree {
int height;
Tree() {
System.out.println(Planting a seedling);
height = 0;
}
Tree(int i) {
System.out.println(Creating new Tree that is + i + feet tall);
height = i;
}
void info() {
System.out.println(Tree is + height + feet tall);
}
void info(String s) {

System.out.println(s + : Tree is + height + feet tall);


}
}
public class Overloading {
public static void main(String[] args) {
MSIT 13 Oops with Java 95
PDF created with pdfFactory Pro trial version www.pdffactory.com
new Tree();
for(int i = 0; i < 5; i++) {
Tree t = new Tree(i);
t.info();
t.info(overloaded method);
}
}
}
A Tree object can be created either as a seedling, with no argument, or as a plant grown in a nursery, with an existing
height. To support this, there is a default constructor, and one that takes the existing height. You might also want to call
the info( ) method in more than one way. For example, if you have an extra message you want printed, you can use
info(String), and info( ) if you have nothing more to say. It would seem strange to give two separate names to what is
obviously the same concept. Fortunately, method overloading allows you to use the same name for both.
Distinguishing overloaded methods
If the methods have the same name, how can Java know which method you mean? Theres a simple rule: each
overloaded method must take a unique list of argument types. If you think about this for a second, it makes sense. How
else could a programmer tell the difference between two methods that have the same name, other than by the types of
their arguments? Even differences in the ordering of arguments are sufficient to distinguish two methods.
DATA TYPES
In attempting to give you a quick introduction to constants and variables, the preceding sections skipped over a very
important attribute of all constants and variables: data type. Java has eight different data types, all of which represent
different kinds of values in a program. These data types are byte, short, int, long, float, double, char, and boolean. In
this section, youll learn what kinds of values these various data types represent.
Integer Values
The most common values used in computer programs are integers, which represent whole number values such as 12,
1988, and -34. Integer values can be both positive and negative, or even the value 0. The size of the value thats allowed
depends on the integer data type you choose. Java features four integer data types, which are byte, short, int, and long.
Although some computer languages allow both signed and unsigned integer values, all of Javas integers are signed,
which means they can be positive or negative. Java provides four different types of integer data types.

byte:
Byte, takes up the least amount of space in a computers memory. When you declare a constant or variable as byte, you
are limited to values in the range -128 to 127. In Java, you declare a byte value like this:
byte identifier; / byte identifier = value;
byte count; / byte count = 100;
After Java executes the preceding line, your program will have a variable named count that currently holds the value of
100. Of course, you can change the contents of count at any time in your program. It only starts off holding the value
100.
short:

A variable declared as short can hold a value from -32,768 to 32,767. You declare a short value like this:
short identifier; / short identifier = value;
short abc; / short abc=1234;
In Java, short values are twice as big in memory-16 bits (or two bytes)-as byte values.
int:
int can hold a value from -2,147,483,648 to 2,147,483,647. The int data type can hold such large numbers because it
takes up 32 bits (four bytes) of computer memory. You declare int values like this:
int identifier; / int identifier = value;
int X; / int X=1234567;
long :
long data type takes up 64 bits (eight bytes) of computer memory and can hold truly immense numbers. Unless youre
calculating the number of molecules in the universe, you dont even have to know how big a long number can be. Id
figure it out for you, but Ive never seen a calculator that can handle numbers that big. You declare a long value like this:
long identifier; / long identifier = value;
long Y; / long Y=1234567891011;
Floating-Point Values
Whereas integer values can hold only whole numbers, the floating-point data types can hold values with both whole
number and fractional parts. Examples of floating-point values include 32.9, 123.284, and -43.436. As you can see, just
like integers, floating-point values can be either positive or negative. Java includes two floating-point types, which are
float and double. Each type allows greater precision in calculations. Floating-point numbers can become very complex
when theyre used in calculations, particularly in multiplication and division. For example, when you divide 3.9 by 2.7,
you get 1.44444444. In actuality, though, the fractional portion of the number goes on forever. That is, if you were to
continue the division calculation, youd discover that you keep getting more and more fours in the fractional part of the
answer. The answer to 3.9 divided by 2.7 is not really 1.44444444, but rather something more like
1.4444444444444444. But even that answer isnt completely accurate. A more accurate answer would be
1.44444444444444444444444444444444. The more 4s you add to the answer the more accurate the answer becomesyet, because the 4s extend on into infinity, you can never arrive at a completely accurate answer. Dealing with floatingpoint values frequently means deciding how many decimal places in the answer is accurate enough. Thats where the
difference between the float and double data types shows up.

float :
In Java, a value declared as float can hold a number in the range from around -3.402823 x 1038 to around 3.402823 x
1038. These types of values are also known as single-precision floating-point numbers and take up 32 bits (four bytes)
of memory. You declare a single-precision floating-point number like this:
float identifier; / float identifier = value;
float F; / float F = 3.112F;
In the second line, value must be a value in the range given in the previous paragraph, followed by an upper- or
lowercase F.
double:
double, represents a double-precision value, which is a much more accurate representation of floatingpoint numbers
because it allows for more decimal places. A double value can be in the range from 1.79769313486232 x 10308 to 1.79769313486232 x 10308 and is declared like this:
double identifier; / double identifier = value;

double d; / double d = 123.4567890;


Floating-point values of the double type are written exactly as their float counterparts, except you use an upper- or
lowercase D as the suffix, rather than an F.
Character Values
Often in your programs, youll need a way to represent character values rather than just numbers. A character is a
symbol thats used in text. The most obvious examples of characters are the letters of the alphabet, in both upper- and
lowercase varieties. There are, however, many other characters, including not only things such as spaces, exclamation
points, and commas, but also tabs, carriage returns, and line feeds. The symbols 0 through 9 are also characters when
theyre not being used in mathematical calculations. In order to provide storage for character values, Java features the
char data type, which is 16 bits. However, the size of the char data type has little to do with the values it can hold.
Basically, you can think of a char as being able to hold a single character. (The 16 bit length accommodates Unicode
characters, which you dont need to worry about in this book.) You declare a char value like this: char identifier; / char
identifier=value; char c; / char c = A;
In the second example, youre not only declaring the variable c as a char, but also setting its value to an uppercase A.
Notice that the character thats being assigned is enclosed in single quotes. Some characters cannot be written with only
a single symbol. For example, the tab character is represented in Java as \t, which is a backslash followed by a lowercase
t. There are several of these special characters, as shown below in table 3.1
Character Symbol
Backslash \\
Backspace \b
Carriage return \r
Double quote \"
Form feed \f
Line feed \n
Single quote \'
Tab \t
Table 3.1 Special Character Literals.
Although the special characters in the above table are represented by two symbols, the first of which is always a
backslash, you still use them as single characters. For example, to define a char variable as a backspace character, you
might write something like the following in your Java program: char backspace = \b;
When Javas compiler sees the backslash, it knows that its about to encounter a special character of some type. The
symbol following the backslash tells the compiler which special character to use. Because the backslash is used to
signify a special character, when you want to specify the backslash character yourself, you must use two backslashes,
which keeps the compiler from getting confused. Other special characters that might confuse the compiler because they
are used as part of the Java language are single and double quotes. When you want to use these characters in your
programs data, you must also precede them with a backslash.
Boolean Values
Many times in a program, you need a way to determine if a specific condition has been met. For example, you might
need to know whether a part of your program executed properly. In such cases, you can use Boolean values, which are
represented in Java by the boolean data type. Boolean values are unique in that they can be only one of two possible
values: true or false. You declare a boolean value like this:
boolean identifier; / boolean identifier = value;
In the second example, value must be true or false. In an actual program, you might write something like this:
boolean file_okay = true;
Boolean values are often used in if statements, which enable you to do different things depending on the value of a
variable.
Following table 3.2 summarizes Javas various data types. Take some time now to look over the table and make sure you
understand how the data types differ from each other. You might also want to think of ways you might use each data
type in an actual program.
Primitive Data Types

BRANCHING STATEMENTS
Program flow is the order in which a program executes its statements. Most program flow is sequential, meaning that the
statements are executed one by one in the order in which they appear in the program or method. However, there are Java
commands that make your program jump forward or backward, skipping over program code not currently required.
These commands are said to control the program flow. When a program breaks the sequential flow and jumps to a new
section of code, it is called branching. When this branching is based on a decision, the program is performing
conditional branching.
if statement
If the expression evaluates to true then the statements following the if statement will be executed and if the expression
evaluates to false, then the statements in the else block will be executed. The else block is optional. This is illustrated inif (expression) {
if (expression) {
Test
Expression?
True-block
Statements
False-block
Statements
Entry
Statement X
True False
Figure 3.2 Flowchart of if...else control
Example:
The program displays whether the given number is positive or negative
class Positive{
public static void main(String arg[]){
int n=25;
if ( n > 0 )
System.out.println(Positive);
else
System.out.println(Negative);
}

}
Example:
The program displays whether the given number is positive or negative
class Positive{
public static void main(String arg[]){
int n=25;
if ( n > 0 )
System.out.println(Positive);
else
System.out.println(Negative);
}
}
Nested if :
if(expression){ //outer if statement
statements;
if(expression){ //inner if statement
statements;
Chapter 3 - Overview 54 of JAVA Language
PDF created with pdfFactory Pro trial version www.pdffactory.com
.
}
else {
statements;
.
}
}
else {
statements;
.
}
Ladder if:
if (condition) {
statements;
} else if (condition) {
statements;
} else{
statements;
}
The program IfElseDemo.java demonstrates the use of ladder if. It gives the grade depending on the testscore.
public class IfElseDemo {

public static void main(String[] args) {


int testscore = 76;
char grade;
if (testscore >= 90) {
grade = A;
} else if (testscore >= 80) {
grade = B;
} else if (testscore >= 70) {
grade = C;
} else if (testscore >= 60) {
grade = D;
} else {
grade = F;
}
System.out.println(Grade = + grade);
}
}
The program salary java computes the salary when number of hours worked is specified as an argument.
class salary {
public static void main(String arg[]) {
int n=50,salary;
if (n<=30)
{
salary=n*150;
System.out.println(salary is:+salary);
}
else if (n>30 && n<45)
{
salary=n*150+(n-30)*200;
System.out.println(salary is:+salary);
}
else if (n>45)
{
salary=n*150+(n-30)*300;
Chapter 3 - Overview 56 of JAVA Language
PDF created with pdfFactory Pro trial version www.pdffactory.com
System.out.println(salary is:+salary);
}
}
}
Switch Statement
The switch is sometimes classified as a selection statement. The switch statement selects from among pieces of code
based on the value of an integral expression. Its form is:
switch(integral-selector) {
case integral-value1 : statement; break;
case integral-value2 : statement; break;
case integral-value3 : statement; break;
case integral-value4 : statement; break;
case integral-value5 : statement; break;
// ...
default: statement;
}
Integral-selector is an expression that produces an integral value. The switch compares the result of
integral-selector to each integral-value. If it finds a match, the corresponding statement (simple or

compound) executes. If no match occurs, the default statement executes.


The program SwitchDemo.java displays the numbers of days when the month and the year is given.
public class SwitchDemo {
public static void main(String args[]) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1: //number of days is 31
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4: //number of days is 30
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
//checks for leap year & assigns 28 or 29
if ( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
}
System.out.println(Number of Days = + numDays);
}
}
This program displays the class obtained by the student depending on the percentage of marks obtained.
class Switch1{
public static void main(String arg[])
{
int n=95,avg;
if(n>=80)
{
System.out.println(Distinction);
}
else if(n>60 && n<80)
{
System.out.println(1st class);
}
else if(n>40 && n<60)
{
System.out.println(Pass);
}
else
System.out.println(Fail);
}
}

This program displays the class obtained by the student depending on the percentage of marks obtained.
Another version of the above program.
class Switch2{
public static void main(String arg[]){
int i=35;
switch(i/10) {
case 9:
case 8:
case 7: System.out.println(Distinction);
break;
case 6: System.out.println(First Class);
break;
case 5: System.out.println(Second Class);
break;
case 4: System.out.println(Pass);
break;
default : System.out.println(FAIL);
}
}
}
This program makes use of the switch statement to demonstrate the usage of a character as switch expression. It
simulates a simple calculator with basic operations like +, -, * and /.
class Cal{
public static void main(String arg[]){
int a=6,b=3;
int res;
char oper=^;
switch(oper) {
case +: res=a+b;
System.out.println(Sum : +res);
break;
case -: res=a-b;
System.out.println(Difference : +res);
break;
case *: res=a*b;
System.out.println(Product : +res);
break;
case /: res=a/b;
System.out.println(Quotient : +res);
break;
}
}
}
LOOPING CONSTRUCTS
In computer programs, looping is the process of repeatedly running a block of statements. Starting at the top of the
block, the statements are executed until the program reaches the end of the block, at which point the program goes back
to the top and starts over. The statements in the block may be repeated any number of times, from none to forever. If a
loop continues on forever, it is called an infinite loop. Java supports three types of looping:
while loops,
for loops, and
do-while loops.
The control expression is a logical expression, much like the logical expressions you used with if statements. In other
words, any expression that evaluates to true or false can be used as a control expression for a while loop. An entry
controlled loop is shown in figure 3.3

While Loop
The while statement tests an expression and, if it is true, executes the next statement or block repeatedly until the
expression becomes false. When the variable or expression is false, control is passed to the next statement after while
statement. The syntax of while loop is as follows:
initialization;
while(condition)
{
statement1;
statement2;
updating statement;
.
}
Heres an example of simple while loop:
The program Natural.java displays natural numbers from 1 to 10.
class Natural{
public static void main(String arg[]){
int num = 1; //initialize num to 1
while (num <= 10) //condition for termination
{
System.out.println(num);
++num; //increment num
}
}
}
Output:
1
2
3
Chapter 3 - Overview 62 of JAVA Language
PDF created with pdfFactory Pro trial version www.pdffactory.com
4
5
6
7
8
9
10
For Loop
It is more compact when compared to while loop. Syntax for for loop is as follows. for(initialization; termination;
increment) {
statement1;
statement2;
..
}
The initialization is an expression that initializes the loop-its executed once at the beginning of the loop. The
termination expression determines when to terminate the loop. This expression is evaluated at the top of each iteration
of the loop. When the expression evaluates to false, the loop terminates. Finally, increment is an expression that gets
invoked after each iteration through the loop. All these components are optional. In fact, to write an infinite loop, you
omit all three expressions:
for ( ; ; ) { // infinite loop
...
}
The program even.java displays all the even numbers between 2 and 10, using for loop.
class even{

public static void main(String arg[]){


int num;
for(num=2;num<=10;num+=2) {
System.out.println(num);
}
}
}
output:
2
4
6
8
10
do-while loop
The do-while loop is a bottom-tested loop. It enters the loop and executes once and then checks the condition. Syntax for
do-while loop is as follows:
initialization;
do{
statement1;
statement2;
.
}while(condition);
do-while loop is an exit controlled loop. The test condition is evaluated at the bottom of the loop. The program odd.java
displays all the odd numbers between 1 and 10, using for do-while loop.
class odd{
public static void main(String arg[]){
int num=1;
do{
System.out.println(num);
num+=2;
}while(num<=10);
}
}
output:
1
3
5
7
9
The program multitable.java displays the multiplication table of 5 using while loop.
class multitable
{
public static void main(String arg[])
{
int i=1,j=5;
while(i<=10)
{
System.out.println(j+ X +i+ = +i*j);
i++;
}
}
}
output :
5X1=5

5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
The program fibo.java displays first 10 fibonacci series numbers. A fibonacci number is the sum of previous two
numbers in the series. i.e.,
fibo(n)=fibo(n-1)+fibo(n-2)
class fibo{
public static void main(String arg[]){
int i;
int p1=0,p2=1,t;
System.out.println(p1+\n+p2);
for (i=3;i<10;i++)
{
t=p1+p2;
System.out.println(t);
p1=p2;
p2=t;
}
}
}
Output :
0
1
1
2
3
5
8
13
21
35
BREAK AND CONTINUE
You can also control the flow of the loop inside the body of any of the iteration statements by using break and continue.
break quits the loop without executing the rest of the statements in the loop. continue stops the execution of the current
iteration and goes back to the beginning of the loop to begin the next iteration. public class BreakAndContinue {
public static void main(String[] args) {
for(int i = 1; i < 20; i++) {
if(i == 9) break; // Out of for loop
if(i % 3 != 0) continue; // Next iteration
System.out.println(i);
}
}
This program prints 1 and 2 and when i becomes 3, continue statement gets executed hence it skips the print and i is
incremented to 4. It prints 4 and 5 and skips 6 and prints 7 and 8. When i becomes 9 it breaks out of the loop. Hence
following is the output of the BreakAndContinue.java program.
output:
1
2

4
5
7
8
NESTED LOOPS
Nesting of loops, that is one for loop with in another for loop. The concept of nested loop can be depicted as follows:
This program puts 10 integer values into an array-a fixed length structure that can hold multiple values of the same typethen sorts them. The line of code in red declares an array referred to by arrayOfInts, creates the array, and puts 10 integer
values into it. The program uses arrayOfInts.length to get the number of elements in the array. Individual elements are
accessed with this notation: arrayOfInts [index], where index is an integer indicating the position of the element within
the array.
Note that indices begin at 0.
public class SortDemo {
Chapter 3 - Overview 68 of JAVA Language
PDF created with pdfFactory Pro trial version www.pdffactory.com
public static void main(String[] args) {
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
2000, 8, 622, 127 };
for (int i = arrayOfInts.length; i >= 0; ) {
for (int j = 0; j < i; j++) {
if (arrayOfInts[j] > arrayOfInts[j+1]) {
int temp = arrayOfInts[j];
arrayOfInts[j] = arrayOfInts[j+1];
arrayOfInts[j+1] = temp;
}
}
}
for (int i = 0; i < arrayOfInts.length; i++) {
System.out.print(arrayOfInts[i] + );
}
System.out.println();
}
}
The output from this program is a list of numbers sorted from lowest to highest:
3 8 12 32 87 127 589 622 1076 2000
The program num.java displays the numbers in a triangle pattern using nested loops.
class num{
public static void main(String arg[])
{ int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(j+\t);
}
System.out.println();
}
}
}
Output:
1
12
123
1234

12345
ARRAYS IN JAVA
Declaring a Variable to refer to an Array
This line of code from the sample program declares an array variable:
int[] anArray; // declare an array of integers
Like declarations for variables of other types, an array declaration has two components: the arraystype and the arrays
name. An arrays type is written type[], where type is the data type of the elements contained within the array, and []
indicates that this is an array. Remember that all of the elements within an array are of the same type. The sample
program uses int[], so the array called anArray will be used to hold integer data. Here are declarations for arrays that
hold other types of data:
float[ ] anArrayOfFloats;
boolean[ ] anArrayOfBooleans;
Object[ ] anArrayOfObjects;
String[ ] anArrayOfStrings;
As with declarations for variables of other types, the declaration for an array variable does not allocate any memory to
contain the array elements. The sample program must assign a value to anArray before the name refers to an array.
Creating an Array
You create an array explicitly using Javas new operator. The next statement in the sample program allocates an array
with enough memory for ten integer elements and assigns the array to the variable anArray declared earlier.
anArray = new int[10]; // create an array of integers
In general, when creating an array, you use the new operator, plus the data type of the array elements, plus the number of
elements desired enclosed within square brackets ([ and ]).
new elementType[arraySize]
If the new statement were omitted from the sample program, the compiler would print an error like the following one
and compilation would fail.
ArrayDemo.java:4: Variable anArray may not have been initialized.
Accessing an Array Element
Now that some memory has been allocated for the array, the program assign values to the array elements:
for (int i = 0; i < anArray.length; i++) {
anArray[i] = i;
System.out.print(anArray[i] + );
}
This part of the code shows that to reference an array element, either to assign a value to it, or to access the value, you
append square brackets to the array name. The value between the square brackets indicates (either with a variable or
some other expression) the index of the element to access. Note that in Java, array indices begin at 0 and end at the array
length minus 1.
Getting the Size of an Array
To get the size of an array, you write
arrayname.length
Be careful: Programmers new to the Java programming language are tempted to follow length with an empty set of
parenthesis. This doesnt work because length is not a method. length is a property provided by the Java platform for all
arrays. The for loop in our sample program iterates over each element of anArray, assigning values to its elements. The
for loop uses anArray.length to determine when to terminate the loop.
Array Initializers
The Java programming language provides a shortcut syntax for creating and initializing an array. Heres an example of
this syntax:
boolean[] answers = { true, false, true, true, false };
The length of the array is determined by the number of values provided between { and }.
Example:
int[] X= {1,2,3,4};

int A[]={2,3,4,5};
The program ArrayDemo.java creates an array of integers and prints them.
public class ArrayDemo {
public static void main(String[] args) {
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; //array declared
for (int i = 0; i < arrayOfInts.length; i++) { //prints the elements of the array
System.out.print(arrayOfInts[i] + );
}
System.out.println();
}
}
This program ArrayOfStringsDemo.java uses an array of strings and displays the names in lowercase.
public class ArrayOfStringsDemo {
public static void main(String[] args) {
String[] anArray = { String One, String Two, String Three };
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray[i].toLowerCase());
}
}
}
This program ArrayOfArraysDemo.java demonstrates the usage of multidimensional arrays in JAVA.
public class ArrayOfArraysDemo {
public static void main(String[] args) {
String[][] cartoons =
{
{ Flintstones, Fred, Wilma, Pebbles, Dino },
{ Rubbles, Barney, Betty, Bam Bam },
{ Jetsons, George, Jane, Elroy, Judy, Rosie, Astro },
{ Scooby Doo Gang, Scooby Doo, Shaggy, Velma, Fred, Daphne }
};
for (int i = 0; i < cartoons.length; i++) {
System.out.print(cartoons[i][0] + : );
for (int j = 1; j < cartoons[i].length; j++) {
System.out.print(cartoons[i][j] + );
}
System.out.println();
}
}
}

Section III

Exception handling threads


INTRODUCTION
Exception is an event during program execution that prevents the program from continuing normally; generally, an error.
The Java programming language supports exceptions with the try, catch, throw, throws and finally keywords. The Java
programming language provides a mechanism known as exceptions to help programs report and handle errors. When an
error occurs, the program throws an exception i.e., the normal flow of the program is interrupted and the runtime
environment attempts to find an exception handlera block of code that can handle a particular type of error. The
exception handler can attempt to recover from the error or, if it determines that the error is unrecoverable, provide a
gentle exit from the program. Three statements play a part in handling exceptions:
The try statement identifies a block of statements within which an exception might be thrown.
The catch statement must be associated with a try statement and identifies a block of statements that can handle a
particular type of exception. The statements are executed if an exception of a particular type occurs within the try block.
The finally statement must be associated with a try statement and identifies a block of statements that are executed
regardless of whether or not an error occurs within the try block.
Heres the general form of these statements:
try {
statement(s)
MSIT 13 Oops with Java 147
PDF created with pdfFactory Pro trial version www.pdffactory.com
} catch (exceptiontype name) {
statement(s)
} finally {
statement(s)
}
This has been a brief overview of the statements provided by the Java programming language used in reporting and
handling errors. However, other factors and considerations, such as the difference between runtime and checked
exceptions and the hierarchy of exceptions classes, which represent various types of exceptions, play a role in using the
exception mechanism. Many kinds of errors can cause exceptionsproblems ranging from serious hardware errors,
such as a hard disk crash, to simple programming errors, such as trying to access an out-of-bounds array element. When
such an error occurs within a Java method, the method creates an exception object and hands it off to the runtime
system. The exception object contains information about the exception, including its type and the state of the program
when the error occurred. The runtime system is then responsible for finding some code to handle the error. In Java
terminology, creating an exception object and handing it to the runtime system is called throwing an exception. After a
method throws an exception, the runtime system leaps into action to find someone to handle the exception. The set of
possible someones to handle the exception is the set of methods in the call stack of the method where the error
occurred. The runtime system searches backwards through the call stack, beginning with the method in which the error
occurred, until it finds a method that contains an appropriate exception handler. An exception handler is considered
appropriate if the type of the exception thrown is the same as the type of exception handled by the handler. Thus the
exception bubbles up through the call stack until an appropriate handler is found and one of the calling methods handles
the exception. The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches
all of the methods on the call stack without finding an appropriate exception handler, the runtime system (and
consequently the Java program) terminates. By using exceptions to manage errors, Java programs have the following
advantages over traditional error management techniques:
1: Separating Error Handling Code from Regular Code
2: Propagating Errors Up the Call Stack
3: Grouping Error Types and Error Differentiation
EXCEPTION HANDLING
The try Block
The first step in constructing an exception handler is to enclose the statements that might throw an exception within a try
block. In general, a try block looks like this:
try {
Java statements
}

The segment of code labelled Java statements is composed of one or more legal Java statements that could throw an
exception.
To construct an exception handler for the writeList method from the ListOfNumbers class, you need to enclose the
exception-throwing statements of the writeList method within a try block. There is more than one way to accomplish
this task. You could put each statement that might potentially throw an exception within its own try statement, and
provide separate exception handlers for each try. Or you could put all of the writeList statements within a single try
statement and associate multiple handlers with it. The following listing uses one try statement for the entire method
because the code tends to be easier to read. PrintWriter out = null;
try {
System.out.println(Entering try statement);
out = new PrintWriter(
new FileWriter(OutFile.txt));
for (int i = 0; i < size; i++)
out.println(Value at: + i + = + victor.elementAt(i));
}
The try statement governs the statements enclosed within it and defines the scope of any exception handlers associated
with it. In other words, if an exception occurs within the try statement, that exception is handled by the appropriate
exception handler associated with this try statement. A try statement must be accompanied by at least one catch block or
one finally block.
Catch Block
The try statement defines the scope of its associated exception handlers. You associate exception handlers with a try
statement by providing one or more catch blocks directly after the try block:
try {
...
} catch ( . . . ) {
...
}
There can be no intervening code between the end of the try statement and the beginning of the first catch statement.
The general form of Javas catch statement is:
catch (SomeThrowableObject variableName) {
Java statements
}
As you can see, the catch statement requires a single formal argument. The argument to the catch statement looks like an
argument declaration for a method. The argument type, SomeThrowableObject, declares the type of exception that the
handler can handle and must be the name of a class that inherits from the Throwable class defined in the java.lang
package. When Java programs throw an exception they are really just throwing an object, and only objects that derive
from Throwable can be thrown. Youll learn more about throwing exceptions in How to Throw Exceptions.
variableName is the name by which the handler can refer to the exception caught by the handler. For example, the
exception handlers for the writeList method (shown later) each call the exceptions getMessage method using the
exceptions declared name e:
e.getMessage()
You access the instance variables and methods of exceptions in the same manner that you access the instance variables
and methods of other objects. getMessage is a method provided by the Throwable class that prints additional
information about the error that occurred. The Throwable class also implements two methods for filling in and printing
the contents of the execution stack when the exception occurred. Subclasses of Throwable can add other methods or
instance variables. The catch block contains a series of legal Java statements. These statements are executed if and when
the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in
the call stack whose type matches that of the exception thrown.
Catching Multiple Exception Types with One Handler
The two exception handlers used by the writeList method are very specialized. Each handles only one type of exception.
The Java language allows you to write general exception handlers that handle multiple types of exceptions. The
writeList method from the ListOfNumbers class uses two exception handlers for its try statement, with one handler for
each of the two types of exceptions that can be thrown within the try block

ArrayIndexOutOfBoundsException and IOException.


try {
...
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println(Caught ArrayIndexOutOfBoundsException: +
e.getMessage());
} catch (IOException e) {
System.err.println(Caught IOException: +
e.getMessage());
}
As you know, Java exceptions are Throwable objects; they are instances of Throwable or a subclass of Throwable. The
Java packages contain numerous classes that derive from Throwable and thus, build a hierarchy of Throwable classes.
Lets modify the writeList method once again. Only this time, lets write it so that it handles both IOExceptions and
ArrayIndexOutOfBoundsExceptions.
The closest common ancester of IOException and ArrayIndexOutOfBoundsException is the Exception class. An
exception handler that handles both
types of exceptions looks like this:
try {
...
} catch (Exception e) {
System.err.println(Exception caught: + e.getMessage());
}
The Exception class is pretty high in the Throwable class hierarchy. So in addition to the IOException and
ArrayIndexOutOfBoundsException types that this exception handler is intended to catch, it will catch numerous other
types. Generally speaking, your exception handlers should be more specialized. Handlers that can catch most or all
exceptions are typically useless for error recovery because the handler has to determine what type of exception occurred
anyway to determine the best recovery strategy. Also, exception handlers that are too general can make code more error
prone by catching and handling exceptions that werent anticipated by the programmer and for which the handler was
not intended.
The finally Block
The final step in setting up an exception handler is providing a mechanism for cleaning up the state of the method before
(possibly) allowing control to be passed to a different part of the program. You do this by enclosing the cleanup code
within a finally block. The try block of the writeList method that youve been working with opens a PrintWriter. The
program should close that stream before allowing control to pass out of the writeList method. This poses a somewhat
complicated problem because writeLists try block has three different exit possibilities:
The new FileWriter statement failed and threw an IOException.
The victor.elementAt(i) statement failed and threw an ArrayIndexOutOfBoundsException.
Everything succeeded and the try block exited normally.
The runtime system always executes the statements within the finally block regardless of what happens within the try
block. Regardless of whether control exits the writeList methods try block due to one of the three scenarios listed
previously, the code within the finally block will be executed. This is the finally block for the writeList method. It cleans
up and closes the PrintWriter.
finally {
if (out != null) {
System.out.println(Closing PrintWriter);
out.close();
} else {
System.out.println(PrintWriter not open);
}
}
Exception Specification
Java provides syntax (and forces you to use that syntax) to allow you to politely tell the client programmer what
exceptions this method throws, so the client programmer can handle them. This is the exception specification and its

part of the method declaration, appearing after the argument list. The exception specification uses an additional
keyword, throws, followed by a list of all the potential exception types. So your method definition might look like this:
void f() throws IOException, NumberFormatException{ //...
If you say
void f() { // ...
It means that no exceptions are thrown from the method. If the code within your method causes exceptions, but your
method doesnt handle them, the compiler will detect this and tell you that you must either handle the exception or
indicate with an exception specification that it may be thrown from your method. By enforcing exception specifications
from top to bottom, Java guarantees that a certain level of exception correctness can be ensured at compile time.
Creating your own exceptions
The JDK exception hierarchy cant foresee all the errors you might want to report, so you can create your own to denote
a special problem that your library might encounter. To create your own exception class, you must inherit from an
existing exception class, preferably one that is close in meaning to your new exception (although this is often not
possible). The most trivial way to create a new type of exception is just to let the compiler create the default constructor
for you, so it requires almost no code at all:
// Inheriting your own exceptions.
class SimpleException extends Exception { } //user defined
exception
public class SimpleExceptionDemo {
public void f() throws SimpleException {
System.out.println(Throw SimpleException from f());
throw new SimpleException();
}
public static void main(String[] args) {
SimpleExceptionDemo sed = new SimpleExceptionDemo();
try {
sed.f();
} catch(SimpleException e) {
System.err.println(Caught it!);
}
}
}
The compiler creates a default constructor, which automatically (and invisibly) calls the base-class default constructor.
Of course, in this case you dont get a SimpleException(String) constructor, but in practice that isnt used much. As
youll see, the most important thing about an exception is the class name, so most of the time an exception like the one
shown here is satisfactory. Here, the result is printed to the console standard error stream by writing to System.err. This
is usually a better place to send error information than System.out, which may be redirected. If you send output to
System.err, it will not be redirected along with System.out so the user is more likely to notice it. You can also create an
exception class that has a constructor with a String argument:
class MyException extends Exception {
public MyException() {}
public MyException(String msg) { super(msg); }
}
Chapter 8 154 - Exception Handling
PDF

JAVA Components and Event


Handling
INTRODUCTION
Javas Abstract Windowing Toolkit provides many of the user interface objects we find in the Windows environment.
These are called Components of the Java AWT. The applet below contains most of the components we will use to
create a graphical user interface (GUI) for our applets. It simply initializes and creates the components but does not
handle any of the events they trigger. An Applet is a Panel.
Because Applet is a subclass of the AWT Panel class, applets can contain other Components, just as any Panel can.
Applets inherit Panels default layout manager: FlowLayout. Applets participate in the AWT drawing and event
hierarchy.
AWT COMPONENTS
The AWT supplies the following UI(User Interface) components (the class that implements each component is listed in
parentheses):
v Buttons (java.awt.Button)
v Checkboxes (java.awt.Checkbox)
v Single-line text fields (java.awt.TextField)
v Larger text display and editing areas (java.awt.TextArea)
v Labels (java.awt.Label)
Chapter 11 - JAVA Components 182 and Event Handling
PDF created with pdfFactory Pro trial version www.pdffactory.com
v Lists (java.awt.List)
v Pop-up lists of choices (java.awt.Choice)
v Sliders and scrollbars (java.awt.Scrollbar)
v Drawing areas (java.awt.Canvas)
v Menus (java.awt.Menu, java.awt.MenuItem, java.awt.CheckboxMenuItem)
v Containers (java.awt.Panel, java.awt.Window and its subclasses)
Methods for Using UI Components in Applets
Because the Applet class inherits from the AWT Container class, its easy to add components to applets and to use layout
managers to control the components onscreen positions. Here are some of the Container methods an applet can use:
add
Adds the specified Component.
remove
Removes the specified Component.
setLayout
Sets the layout manager.
DELEGATION MODEL OVERVIEW
Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event.
All the object has to do is implement the appropriate interface and be registered as an event listener on the appropriate
event source. Event types are encapsulated in a class hierarchy rooted at java.util.EventObject. An event is propagated
from a Source object to a Listener object by invoking a method on the listener and passing in the instance of the
event subclass, which defines the event type generated. A Listener is an object that implements a specific EventListener
interface extended from the generic java.util.EventListener. An EventListener interface defines one or more methods,
which are to be invoked by the event source in response to each specific event type handled by the interface. An Event
Source is an object, which originates or fires events. The sources defines the set of events it emits by providing a set
of set<EventType>Listener (for single-cast) and/or add<EventType>Listener (for multi-cast) methods which are used to
register specific listeners for those events.
In an AWT program, the event source is typically a GUI component and the listener is commonly an adapter object,
which implements the appropriate listener (or set of listeners) in order for an application to control the flow/handling of
events. The listener object could also be another AWT component which implements one or more listener interfacEvent
Hierarchy

A hierarchy of event classes is used to represent events. Each event class is defined by the data representing that event
type or related group of events types.
v java.util.EventObject
o java.awt.AWTEvent
java.awt.event.ComponentEvent (component resized, moved, etc.)
java.awt.event.FocusEvent (component got focus, lost focus)
java.awt.event.InputEvent
java.awt.event.KeyEvent (component got key-press, key-release, etc.)
java.awt.event.MouseEvent (component got mouse-down, mouse-move, etc.)
java.awt.event.ContainerEvent
java.awt.event.WindowEvent
java.awt.event.ActionEvent (do a command)
java.awt.event.AdjustmentEvent (value was adjusted)
java.awt.event.ItemEvent (item state has changed)
java.awt.event.TextEvent (the value of the text object changed)
Event Listeners
An EventListener interface will typically have a separate method for each distinct event type the event class represents.
So in essence, particular event semantics are defined by the combination of an Event class paired with a particular
method in an EventListener. For example, the FocusListener interface defines two methods, focusGained() and
focusLost(), one for each event type that FocusEvent class represents. The API attempts to define a balance between
providing a reasonable granularity of Listener interface types and not providing a separate interface for every single
event type. The interfaces defined by the AWT are as follows:
v java.util.EventListener
o java.awt.event.ComponentListener
o java.awt.event.ContainerListener
o java.awt.event.FocusListener
o java.awt.event.KeyListener
o java.awt.event.MouseListener
o java.awt.event.MouseMotionListener
o java.awt.event.WindowListener
o java.awt.event.ActionListener
o java.awt.event.AdjustmentListener
o java.awt.event.ItemListener
o java.awt.event.TextListener
AWT components can generate many kinds of events. Table 11.1 lists few examples.
Some Events and Their Associated Event Listeners Act that Results in the Event Listener Typ e
User clicks a button, presses Enter while typing in a text field, or chooses a menu item ActionListener User closes a
frame (main window) WindowListener User presses a mouse button while the cursor is over a component
MouseListener User moves the mouse over a component MouseMotionListener Component becomes visible
ComponentListener Component gets the keyboard focus FocusListener Table or list selection changes
ListSelectionListener Any property in a component changes such as the text on a label PropertyChangeListener
Table 11.1 Events and Associated Listeners
Event Sources
All AWT event sources support a multicast model for listeners. This means that multiple listeners can be added and
removed from a single source. The API makes no guarantees about the order in which the events are delivered to a
set of registered listeners for a given event on a given source.
EVENT HANDLER IMPLEMENTATION
AWTApplication class implements an event handler for button clicks (action events). Heres the relevant code:
public class AWTApplication implements ActionListener {
...
Button button = new Button(Im a AWT button!);
button.addActionListener(this); //register eventlistener

....
public void actionPerformed(ActionEvent e) { //handle event
numClicks++;
label.setText(labelPrefix + numClicks);
}
}
Every event handler requires three pieces of code:
1. In the declaration for the event handler class, one line of code specifies that the class either implements a listener
interface or extends a class that implements a listener interface. For example:
public class MyClass implements ActionListener {
2. Another line of code registers an instance of the event handler class as a listener on one or more components. For
example:
someComponent.addActionListener(instanceOfMyClass);
example : button.addActionListener(this);
3. The event handler class has code that implements the methods in the listener interface. For example:
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}
In general, to detect when the user clicks an onscreen button (or does the keyboard equivalent), a program must have an
object that implements the ActionListener interface. The program must register this object as an action listener on the
button (the event source), using the addActionListener method. When the user clicks the onscreen button, the button
fires an action event. This results in the invocation of the action listeners actionPerformed method (the only method in
the ActionListener interface). The single argument to the method is an ActionEvent object that gives information about
the event and its source.

LAYOUT MANAGERS
JDK provides a set of generic layout manager classes, which arrange java components within a Container in various
predictable ways
v FlowLayout
v BorderLayout
v GridLayout
FlowLayout
The FlowLayout manager is a good place to start, as it is the default for Applets. The FlowLayout manager simply
places components on a background one after the other from left to right. If it runs out of space to the right it wraps
around the components to the next line. The following code creates a very simple application and adds a series of
buttons
import java.awt.*;
public class FlowAp extends Frame{
public static void main(String argv[]){
FlowAp fa=new FlowAp();
//Change from BorderLayout default
fa.setLayout(new FlowLayout());
fa.setSize(400,300);
fa.setVisible(true);
}
FlowAp(){
add(new Button(One));
add(new Button(Two));

add(new Button(Three));
add(new Button(Four));
add(new Button(Five));
add(new Button(Six));
add(new Button(Seven));
add(new Button(Eight));
add(new Button(Nine));
add(new Button(Ten));
}//End of constructor
}//End of Application
The program FlowAp is created as an application by extending it from Frame class. Adding java
components are done in the constructor. An object of the class is created which invokes constructor to
create ten buttons. The layout of the components is set to Flow layout using setLayout() method. Set the
size of the applet displayed using setSize() method. Set the visibility of the applet to true. Figure 11.3 is the
default appearance when you fire it up from the command line

Bear in mind that both images are the display for exactly the same Java code. The only thing that has changed is the
width. The FlowLayout manager automatically changes the layout of the components when the Frame is re-sized as
shown in figure 11.4. If you were to make the Frame very small the FlowLayout manager would change the layout so
that the buttons were wrapped around in several rows.
BorderLayout
If you add multiple components to a Container that uses the BorderLayout but do not pass a Constraint parameter
(North, South, etc), you may get unexpected results. Here is a sample that illustrates this.
import java.awt.*;
public class FlowAp extends Frame{
public static void main(String argv[]){
FlowAp fa=new FlowAp();

// fa.setLayout(new FlowLayout());
fa.setSize(400,300);
fa.setVisible(true);
}
FlowAp(){
add(new Button(One));
add(new Button(Two));
add(new Button(Three));
add(new Button(Four));
add(new Button(Five));
add(new Button(Six));
add(new Button(Seven));
add(new Button(Eight));
add(new Button(Nine));
add(new Button(Ten));
}//End of constructor
}//End of Application

The reason you get this unexpected big button in the center is that the BorderLayout uses a set of coordinates when
arranging components. It divides its surface area up into
v North
v South
v East
v West
v Center
You might guess that the default when laying out components would be for them to be placed clockwise around the
points of the compass or some such arrangement. Instead the designers decided to make the default the center of the
layout area. Thus in this example every button has been laid out on the previous button, taking up the entire available
area. As a result it appears that you only have one button, the last one added. Because the BorderLayout only divides the
area up into the five mentioned coordinates it is not the most useful of Layout Managers. However you need to be aware
of it for the exam and you need to be aware of the way it defaults to placing all components in the center.
The GridLayout Manager
The GridLayout manager does approximately what you might expect. It divides the surface area up into a grid and when
you add components it places them one after the other from left to right, top to bottom. Unlike the BorderLayout and
FlowLayout it ignores any preferred size of the component. For example the preferred size of a button will be wide
enough to show its text. The FlowLayout manager attempts to ensure that a button is this preferred size. The GridLayout
has a more bondage and discipline approach. The only thing it cares about is making sure the component fits into the
grid. The following code lays out a set of buttons within a Frame using a GridLayout that has been set up to have 2 rows
and 5 columns.

import java.awt.*;
public class GridAp extends Frame{
public static void main(String argv[]){
GridAp fa=new GridAp();
//Setup GridLayout with 2 rows and 5 columns
fa.setLayout(new GridLayout(2,5));
fa.setSize(400,300);
fa.setVisible(true);
}
GridAp(){
add(new Button(One));
add(new Button(Two));
add(new Button(Three));
add(new Button(Four));
add(new Button(Five));
add(new Button(Six));
add(new Button(Seven));
add(new Button(Eight));
add(new Button(Nine));
add(new Button(Ten));
}//End of constructor
}//End of Application

Note how the buttons are enlarged to fill all of the available space.
HANDLING EVENTS
Button Events
Some shapes you can draw with the Graphics class are more complex than others. For example, the drawArc() method
requires six arguments in order to draw a simple curved line. To see how drawing other shapes works, youll now create
the ShapeApplet applet, which enables you to switch from one shape to another in the applets display.
An Applet That Draws Various Shapes. (JDK1.4)
import java.awt.*;
import java.applet.*;
public class ShapeApplet extends Applet
{
int shape;
Button button;
public void init()

{
shape = 0;
button = new Button(Next Shape);
add(button);
}
public void paint(Graphics g)
{
int x[] = {35, 150, 60, 140, 60, 150, 35};
int y[] = {50, 80, 110, 140, 170, 200, 230};
int numPts = 7;
switch(shape)
{
case 0: g.drawLine(35, 50, 160, 230);
break;
case 1: g.drawRect(35, 50, 125, 180);
break;
case 2: g.drawRoundRect(35, 50, 125, 180, 15, 15);
break;
MSIT 13 Oops with Java 195
PDF created with pdfFactory Pro trial version www.pdffactory.com
case 3: g.drawOval(35, 50, 125, 180);
break;
case 4: g.drawArc(35, 50, 125, 180, 90, 180);
break;
case 5: g.drawPolygon(x, y, numPts);
break;
case 6: g.fillPolygon(x, y, numPts);
break;
}
}
public boolean action (Event event,Object whatAction)
{
++shape;
if (shape == 7)
shape = 0;
repaint();
return true;
}
}
To run ShapeApplet, use the HTML document shown above except change all occurrences of RectApplet to
ShapeApplet. When you run the applet with Appletviewer, you see the window. To change the shape displayed in the
applets canvas, click the Next Shape button.
Understanding the ShapeApplet Applet
You dont need to concern yourself at this point with the button control that ShapeApplet uses to switch shapes, except
to know that just like the TextField controls youve been using, clicking the button causes Java to call the applets
action() method. The action() method increments the shape counter, shape, and tells the applet to redraw itself. In the
paint() method, the value of shape is used in a switch statement to determine which shape gets drawn. The output of the
ShapeApplet is as shown figure 11.7

Example: Drawing Arcs in an Applet (JDK1.2.2, JDK1.3)


Because understanding the angles involved in drawing arcs can be a little confusing, in this example youll create an
applet called ArcApplet that enables you to enter different values for drawArc()s fifth and sixth arguments and
immediately see the results.
An Arc-Drawing Applet.
import java.awt.*;
import java.applet.*;
public class ArcApplet extends Applet implements ActionListener
{
TextField textField1, textField2;
public void init()
MSIT 13 Oops with Java 197
PDF created with pdfFactory Pro trial version www.pdffactory.com
{
textField1 = new TextField(10);
textField2 = new TextField(10);
add(textField1);
add(textField2);
textField1.setText(0);
textField2.setText(360);
addActionListener(this);
}
public void paint(Graphics g)
{
String s = textField1.getText();
int start = Integer.parseInt(s);
s = textField2.getText();
int sweep = Integer.parseInt(s);
g.drawArc(35, 50, 125, 180, start, sweep);
}
public boolean actionPerformed(ActionEvent event)
{
repaint();
return true;
}
}
When you run ArcApplet using Appletviewer, you see the window. Because the starting angle (in the first text box) is 0
and the drawing degrees (the second box) is 360, the arc is actually a full oval. By changing the values in the two boxes

and pressing Enter, you can cause the applet to display different arcs. This program cal.java implements ActionListener
interface to simulate a simple calculator that performs basic operations like addition and subtraction. (JDK1.2.2 or
JDK1.3)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code=cal width=400 height=400></applet>
public class cal extends Applet implements ActionListener{
TextField t1,t2,t3;Button b1,b2;
public void init(){
t1=new TextField(20);
t2=new TextField(20);
t3=new TextField(20);
b1=new Button(+);
b2=new Button(-);
b1.addActionListener(this);
b2.addActionListener(this);
add(t1);add(t2);add(t3);add(b1);add(b2);
}
public void actionPerformed(ActionEvent e){
int a=Integer.parseInt(t1.getText());
int b=Integer.parseInt(t2.getText());
MSIT 13 Oops with Java 199
PDF created with pdfFactory Pro trial version www.pdffactory.com
int c;
if(e.getSource()==b1){
c=a+b;
t3.setText(String.valueOf(c));
}
if(e.getSource()==b2){
c=a-b;
t3.setText(String.valueOf(c));
}
}
}
Same program when it is required to run in latest version of JAVA. i.e., JDK1.4 it should be rewritten as follows:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code=cal width=400 height=400></applet>
public class cal extends Applet {
TextField t1,t2,t3;Button b1,b2;
public void init(){
t1=new TextField(20);
Chapter 11 - JAVA Components 200 and Event Handling
PDF created with pdfFactory Pro trial version www.pdffactory.com
t2=new TextField(20);
t3=new TextField(20);
b1=new Button(+);
b2=new Button(-);
add(t1);add(t2);add(t3);add(b1);add(b2);
}
public boolean action(Event e,Object o){
int a=Integer.parseInt(t1.getText());
int b=Integer.parseInt(t2.getText());

int c;
String str=(String)o;
if(str==+){
c=a+b;
t3.setText(String.valueOf(c));
}
if(str==-){
c=a-b;
t3.setText(String.valueOf(c));
}
return true;
}
}
Output is as shown below:

Mouse Events
The program img1 implements MouseListener to move an image.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=img1" width=300 height=300>
</applet>
*/
public class img1 extends Applet implements MouseListener {
Image i;
int w,h;
Point start,end;
boolean flag=false;
public void init()
{
i=getImage(getDocumentBase(),balloon.jpg);
addMouseListener(this);
}
public void mousePressed(MouseEvent e){
flag=false;
start=new Point(e.getX(),e.getY());
}
public void mouseReleased(MouseEvent e){
flag=true;
end=new Point(Math.max(e.getX(),start.x),Math.max(e.getY(),start.y));
start=new Point(Math.min(e.getX(),start.x),Math.min(e.getY(),start.y));
repaint();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void paint(Graphics g) {
if(flag)
{

MSIT 13 Oops with Java 203


PDF created with pdfFactory Pro trial version www.pdffactory.com
w=end.x-start.x;
h=end.y-start.y;
g.drawImage(i,start.x,start.y,w,h,this);
}
}
}
This program mouse.java creates an applet that displays the X,Y co-ordinates when we press the mouse button. It makes
use MouseListener interface. (JDK1.2.2 , JDK1.3)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
//<applet code=mouse width=400 height=400></applet>
public class mouse extends Applet implements MouseListener{
int x=10,y=10;
String msg=;
boolean flag=false;
public void init(){
addMouseListener(this);
}
public void mouseClicked(MouseEvent me){}
public void mousePressed(MouseEvent me){
Chapter 11 - JAVA Components 204 and Event Handling
PDF created with pdfFactory Pro trial version www.pdffactory.com
x=me.getX();
y=me.getY();
flag=true;
msg=(X,Y) : (+x+ , +y+ );
repaint();
}
public void mouseReleased(MouseEvent me){
flag=false;
}
public void mouseEntered(MouseEvent me){}
public void mouseExited(MouseEvent me){}
public void paint(Graphics g){
if(flag==true)
g.drawString(msg,x,y);
}
}
Keyboard Event
The program key.java displays an applet that implements the KeyListener interface. You can move the text Hello
displayed on the screen with the help of arrow keys.
(JDK1.2.2 , JDK1.3)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
MSIT 13 Oops with Java 205
PDF created with pdfFactory Pro trial version www.pdffactory.com
//<applet code=key width=400 height=400></applet>
public class key extends Applet implements KeyListener{
String msg=Hello;
int x=10,y=10;
public void init(){

addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent e){
switch(e.getKeyCode())
{
case e.VK_LEFT : x;break;
case e.VK_RIGHT : x++;break;
case e.VK_UP : y;break;
case e.VK_DOWN : y++;break;
}
repaint();
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
public void paint(Graphics g){
g.drawString(msg,x,y);
Chapter 11 - JAVA Components 206 and Event Handling
PDF created with pdfFactory Pro trial version www.pdffactory.com
}
}
Checkbox Events
This program changeFont.java creates an applet to change the Font style using Check Box. It makes use of ItemListener
interface. (JDK1.2.2 , JDK1.3)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=changeFont width=300 height=300>
</applet>
*/
public class changeFont extends Applet implements ItemListener{
TextField t1;
Checkbox c;Font f;
public void init() {
t1=new TextField(20);
c=new Checkbox(Bold);
add(t1);add(c);
c.addItemListener(this);
}
public void itemStateChanged(ItemEvent e) {
if(c.getState()==true)
f=new Font(Courier,Font.BOLD,15);
else
f=new Font(Courier,Font.PLAIN,15);
setFont(f);
repaint();
}
public void paint(Graphics g) {
g.drawString(Hello World,50,100);
}
}

Potrebbero piacerti anche