Vinton Cerf Internet: Section I Internet Architecture Board
Vinton Cerf Internet: Section I Internet Architecture Board
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.
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
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.
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()
{
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:
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.
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
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;
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 {
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{
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
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
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
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
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)
{
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);
}
}