You are on page 1of 87

Teacher

of Computer Science and Software Technology


1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

INTRODUCTION TO OBJECT ORIENTED


PROGRAMMING The term Object Oriented
Programming is a relatively new concept in the world
of programming languages. Earlier the only style of
programming was known as Sequential or Linear or
Procedural Programming. Every program has two
parts: Code and Data. The code part consists of the
statements that are executed to perform the job. The
data part consists of the variables which hold the
necessary values to perform the job. In Sequential
programming style more emphasis is placed on the
code part and less on the data part. The code
statements are executed one by one, sequentially,
meaning that you can execute statement number n if
you have already executed statement number n-1, and
the next statement to execute is statement number n+1.
In Object Oriented Programming the style is
changed. Basically, more emphasis is placed on the
data part and emphasis placed on the code part is
secondary. Everything you have to consider must be
viewed as an object. The definition of an object is like
the following.
An object is a collection of a set of data and a set of
code. The data part is called attributes (formed as

variables) and the code part is called methods


(formed as executable statements). The relationship
between the attributes and the methods is such that
if a method is executed, the values of some attribute
can be accessed or changed. In other words, to
access or change the value of some attribute, we
must execute the proper method.
Let us explain with an example. Consider chair to be
an object. We can say that any chair in the world must
have a set of attributes like height, width, breadth,
colour, material, weight, price and location. To
validate our case we illustrate three different chairs of
different types.
Chair1 Chair2 Chair3 Height 3 ft 2.5 ft 3.5 ft Width
2 ft 2.5 ft 3 ft Breadth 3 ft 2.25 ft 3.5 ft Colour Red
Green Blue Material Wood Plastic Iron Weight 5 kg
2 kg 10 kg Price 500/250/1000/Location Centre West
North East
The attribute set described above defines the data part
of the three chair objects. You can see that all the three
chairs have the identical attribute set. It may happen
that the value within the individual attribute could be
different for the three objects. For example the three
objects have different values for the material attribute,
but all of them have the material attribute in their set
of attributes.

But as they are objects, the chairs must also have a set
of methods (meaning what we can do with these
chairs). The set of methods could be like the
following.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

Buy ( );
Sell ( );
Repair ( ); Paint ( ); Move ( );
As you can understand, if we execute these methods,
then one or some of the attribute values will be
accessed or changed. For example, to Buy ( ) or Sell (
) the chair, its price attribute will be changed. To
Repair ( ) a chair, we may change its dimensions,
weight or material. To Paint ( ) a chair its color
property will be changed. To Move ( ) a chair, we
change its location.
THE CONCEPT OF CLASS
If some objects are found to have a similar set of
attributes and a similar set of methods, then these
objects can be grouped together into a class. A class
is a collection of declaration of the attribute
variables and the definition of the methods. Once
the class has been defined, we can create as many

objects of a class as we need just as we declare


variables of a data type. In the light of a class, an
object can also be defined as an instance or
occurrence of a class.
We may declare the CHAIR class as having declared
variables like height, width, breadth, colour, material,
weight, price and location and defined the methods
like Buy ( ), Sell ( ), Repair ( ), Paint ( ) and Move ( ).
Now, in order to declare a new object Chair4, all we
need to do is write the following statement
CHAIR Chair4; (Equivalent to int n;)
And the job is done.
Each object has its own space in memory where it can
store its own attribute set, because each object is
expected to have a unique attribute set of its own.
However, there is no need to store separate copies of
the methods for each individual objects, as the coding
for the methods need not be changed for each object.
Writing the actual program in an object oriented
system is fairly easy. All we have to do is to execute
the appropriate methods with the appropriate object.
For example, if we want to sell Chair2, then we may
write
Chair2.Sell ( );
And if we want to move Chair3 then we may write

Chair3.Move ( );
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

THE THREE IMPORTANT FEATURES OF


OBJECT ORIENTED PROGRAMMING
Below we briefly mention some of the important
features of the object oriented programming. We shall
discuss then in detail in the later chapters.
Encapsulation
Encapsulation is the technique of putting together the
data part (attributes) and the code part (methods) that
can operate on the data part into the same single
container called a class.
Data Abstraction or Data hiding
This is the technique of making some part of the class
accessible to the outside world while keeping some
sensitive part inaccessible. Generally the attributes of
a class are defined with a keyword called private,
which means that these attributes cannot be accessed
from outside the class by any means. The methods of
the class are generally declared with a keyword called
public, which means that they can be accessed from
outside the class if called using an object of the same
class. In Java, the default accessibility scope is public.

Polymorphism
This means the quality of the same thing to exist in
different forms. This is an integral feature of object
oriented programming that is not found in sequential
programming.
Inheritance
This is also another unique feature of object oriented
programming. This means the creation of a new class
out of an existing class. Inheritance supports the
concept of code reuse and saves a lot of time and
effort to create a new class.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

PROGRAMMING IN JAVA
Now it is the time to write the first program in Java.
The following is the code for a program for adding
two numbers. We are assuming that you have some
knowledge of the C and C++ language.
import java.io.*;
class Ayan {
public static void main(String args[]) throws IOException {
int a, b, c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter first number : ); a = Integer.parseInt(br.readLine());
System.out.print(\n\tEnter second number : ); b = Integer.parseInt(br.readLine());
c = a + b; System.out.print(\n\tThe sum of +a+ and +b+ is : +c); }
}

Let us explain this program line by line.


===================================

import java.io.*;

This statement imports all the classes from the java.io


package. A package is a collection of related classes,
and java has six system defined packages.
One can perhaps guess that this statement is equivalent
to the include statement in C or C++ language. The
difference between include and import statement is
that include statement includes the necessary methods
directly from the header files, while import statement
imports the classes of a package. Because Java is a
strictly object oriented programming language, there is
no way a method can exist independently. We have to
import all or some of the classes from the package
using the import statement. Then we have to declare
an object of the classes, and using the object we can
access the methods of the class.
The packages found in Core Java language are:
1. java.io: contains all the classes for input output
management.
2. java.lang: contains all the classes for Java language
support. This package is imported automatically.
3. java.applet: contains classes for applet
programming (will be explained later)
4. java.awt: contains classes for Abstract Window
Toolkit needed for applet programming (will be
explained later)

5. java.net: contains classes for network


programming.
6. java.util: contains utility classes
The * in the statement import java.io.*; means we are
importing all the classes in the java.io package.
Importing so many classes can cause more time for the
program to compile. For simplicity, instead of
importing all the classes we can import the classes
selectively.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

===================================
class Ayan
{
: :
}

All the statements in the program are included in some


class. No method, not even the main ( ) method can
exist independently; it has to be the member method of
some class. In case of a program that contains multiple
classes, the name of the program should be exactly the
same as the name of the class that contains the main ( )
method.
===================================
public static void main(String args[]) throws IOException
{:
:
}

This is the well familiar main ( ) method. The main ( )


method is the first method that is executed in a
program.
The throws IOException statement is used in two
cases:
A. if a method want to read a value from the keyboard,
then this statement should be written while defining
the method.
B. In case a method does not read a value from the
keyboard directly, but as a parent method, calls
another child method that reads from keyboard (and
throws IOException) then the parent method must also
throw IOException.
===================================
int a, b, c;

This is the normal variable declaration statement.


===================================
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Any statement that reads from the keyboard must have


this statement within it. It is explained part by part.
A. System.in: The system is being told to take an
input. It is an object of a class called InputStream.
B. new InputStreamReader ( ) : The input must be
read as an incoming stream of bytes. It converts the
bytes into readable characters.

C. BufferedReader br = new BufferedReader ( ):


The input which has been taken will have to be read
into a memory buffer. For this reason the br object
of the BufferedReader class has been created.
===================================
System.out.print(\n\tEnter first number : );

This is equivalent to the printf ( ) function used in C


language.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

===================================
a = Integer.parseInt(br.readLine());

This is the standard input statement to read a value


from the keyboard into an integer variable.
A. br.readLine ( ): The readLine ( ) method is a
member method of the BufferedReader class, hence it
is called using the br object of the same class. This
method reads a string from the keyboard.
B. Integer.parseInt ( ): The string read by readLine ( )
is converted into an integer value using this method. If
the user input 1234, it is treated as a string of
characters (same as ABCD). The string should have
to be converted into integer value using this method.
HOW TO SAVE THIS PROGRAM
Because the program contains the main ( ) method in a

class called Ayan, the program should be named as


Ayan.java (.java is the extension for Java source
code).
HOW TO COMPILE THIS PROGRAM
Exit to the Command Prompt and type the following
command:
javac Ayan.java

The compilation process creates a new file called


Ayan.class, which is the byte code of the program
(equivalent to the executable code in C / C++).
HOW TO EXECUTE THIS PROGRAM
Staying within the Command Prompt, type the
following command:
java Ayan

No extension is needed to execute the program.


PROGRAMMING USING THE OBJECT
ORIENTED PRINCIPLE The previous program that
we have seen can be modified to reflect the object
oriented paradigm.
import java.io.*;
class Add
{
int a, b, c; // ATTRIBUTE void input() throws IOException // METHOD {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter first number : ); a = Integer.parseInt(br.readLine());
System.out.print(\n\tEnter second number : ); b = Integer.parseInt(br.readLine());
}
void add() // METHOD
{

c = a + b;
}
void output() // METHOD {
System.out.print(\n\tThe sum of +a+ and +b+ is : +c); }
}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com
class Ayan {
public static void main(String args[]) throws IOException {
Add obj = new Add(); // CREATING AN OBJECT OF THE Add CLASS
obj.input(); obj.add(); obj.output();
}
}

NAMING CONVENTION IN JAVA


There is a very simple naming convention in Java
which is described and illustrated below:
1. All multi-word names have their initials capitalized.
2. All class names begin with capital letter.
3. The names of variables, objects and methods begin
with small letter.
As for example:
AyanKumarChatterjee is the name of a class.
ayanKumarChatterjee is the name of a variable or
object. ayanKumarChatterjee ( ) is the name of a
method.
DATA TYPES IN JAVA
The basic data types are similar in concept to the data
types in C / C++. There are many sub types associated
with the basic data types.

1. Integer Data Type


A. long: 64 bit signed integer.
B. int: 32 bit signed integer (this is used as the default
integer type) C. short: 16 bit signed integer
D. byte: 8 bit signed integer
2. Floating Point Data Type
A. float: 32 bit floating point data type
B. double: 64 bit floating point data type (this is used
by default for greater
precision)
3. Character Data Type
char: The char data type in C / C++ is 8 bit, that
represents the range 0 to 255, which is defined as the
ASCII code. The char data type in Java is of 16 bits
that represent the range 0 to 65535. This range is so
large that we can accommodate all the characters of all
the known language in the world and still have more
characters to allot. This all inclusive character set is
called Unicode.
4. Boolean Data Type
This data type is used to contain logical true or false
values.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

HOW TO TAKE INPUTS INTO VARIABLES OF


DIFFERENT DATA TYPES
Integer :
int i;
i = Integer.parseInt(br.readLine())
Float :
float f;
f = new Float(br.readLine()).floatValue();
Double :
double d;
d = new Double(br.readLine()).doubleValue();
Character :
char c;
c = (char)br.read();
String :
String s;
s = br.readLine(); // NO CONVERSION NEEDED

WRAPPER CLASSES
Because Java is a strictly object oriented programming
language, the data type themselves are created as
objects. We have to consider that all the data types that
we have mentioned here are themselves the objects of
some class. The classes from which the data type
themselves are declared as objects are called Wrapper
classes. All such classes are part of the java.lang
package.
The Number wrapper class is the super class for six
other wrapper classes that deals with all the numeric
data types. These classes are Double, Float, Byte,
Short, Integer and Long. In the previous example
where we have shown that the integer value is taken

using the Integer.parseInt ( ) method, we can say that


the parseInt ( ) method is a member method of the
Integer wrapper class. Similarly, the new Float ( ) and
new Double ( ) expression are calling the constructors
of the Float and Double wrapper classes respectively,
where the floatValue ( ) and doubleValue ( ) methods
are the member methods of these classes.
ARRAYS IN JAVA
Only the declaration procedure is different in
comparison to C / C++
Single dimensional array:
int arr[] = new int[5];

Two dimensional matrix


int m[][] = new int[2][3];

The use of the single or multi dimensional array is


exactly the same. Any array has a built in attribute
called length, that returns the size (that is the number
of elements) in that array.
USE OF OPERATORS
This is exactly the same as in C / C++.
USE OF DECISION STATEMENTS (if / if else /
if else if else / switch case) This is exactly the same
as in C / C++.
USE OF ITERATIVE STATEMENTS (while / do
while / for) This is exactly the same as in C / C++.

Teacher of Computer Science and Software Technology


1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

CONSTRUCTORS
A constructor is a member method of any class whose
objective is to initialize the attributes of an object of
that class. A constructor has the following special
properties:
1. The name of the constructor is exactly the same as
the name of the class
2. Although it is a method, a constructor does not have
any return type. Not even the void type.
3. A constructor method need not be called separately
using an object of that class. The constructor is called
automatically whenever an object of that class is
created.
4. Depending upon its use, a constructor may or may
not receive any argument.
The following program demonstrates the use of
different types of constructors:
import java.io.*;
class ABC {
char a;
int b;
double c;
ABC() // DEFAULT CONSTRUCTOR, TAKES NO ARGUMENT {
a = F;
b = 10;

c = 3.1248;
}
ABC(char a1, int b1, double c1) // PARAMETERIZED CONSTRUCTOR, TAKES
ARGUMENTS {
a = a1; b = b1; c = c1;
}
ABC(ABC obj) // COPY CONSTRUCTOR, TAKES AN ENTIRE OBJECT AS
ARGUMENT {
a = obj.a; b = obj.b; c = obj.c;
}
void output() {
System.out.print(\n\n\tCHAR : +a); System.out.print(\n\tINT : +b);
System.out.print(\n\tDOUBLE : +c);
}
}
class Ayan {
public static void main(String args[]) {
ABC obj1 = new ABC(); // CALLING DEFAULT CONSTRUCTOR
ABC obj2 = new ABC(D, 25, 36.997); // CALLING PARAMETERIZED
CONSTRUCTOR ABC obj3 = new ABC(obj2); // CALLING COPY CONSTRUCTOR
obj1.output(); obj2.output(); obj3.output();
}
}

The first constructor takes no argument, and it is called


the default constructor. It initializes the values of the
attributes of the object obj1 to a user defined default
value (F, 10, 3.1248).
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

The second constructor takes some arguments of basic


data types, and it is called the parameterized
constructor. It initializes the values of the attributes
of the object obj2 to a user provided value (D, 25,
36.997).

The third constructor takes an object of the same class


as the argument, and it is called the copy constructor.
It initializes the object to be created with the same set
of values as obj1, therefore creates the new object as
an exact copy of an existing object.
Looking at the use of constructor we can see that a
statement like
ABC obj1 = new ABC();

creates the object obj1 of class ABC. The right hand


side of the = operator, that is where new ABC ( ) is
written, is actually calling the constructor. Calling the
constructor makes the object refer to its class.
this KEYWORD
If you have done some programming in C++, you
must have a idea about the this pointer. The this
pointer is such a pointer that is by default present in
any member function of any class. The objective of
this pointer is to refer to the object which calls that
member function. Java does not support the use of
pointers, so the same thing is done here using the this
keyword.
When an object calls a member method of its class, a
vital issue that needs to be addressed is how the
member method understands which object is calling it.
For example, a class having a set of three attributes

may have created a number of objects, and each of


them is calling a output ( ) member method of that
class. We know that each object may have different set
of values in their attributes. Within the display method
no special code is written about which objects value is
needed to be shown. Yet the method accurately
displays the attribute set of that object which calls it at
a particular moment.
It happens because whenever the object calls the
member method, this keyword keeps a reference to the
calling object. The member method always looks up to
this keyword to provide the name of the object whose
attribute set needs to be displayed. So the member
method is never confused regarding which objects
attribute set it needs to display.
import java.io.*; class ABC {
int a, b, c;
ABC(int a1, int b1, int c1) // PARAMETERIZED CONSTRUCTOR, TAKES
ARGUMENTS {
a = a1; b = b1; c = c1;
}
void output() {
System.out.print(\n\n\tA : +this.a); System.out.print(\n\tB : +this.b);
System.out.print(\n\tC : +this.c);
}
}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com
class Ayan {
public static void main(String args[]) {
ABC obj1 = new ABC(10, 20, 30); ABC obj2 = new ABC(100, 200, 300);

obj1.output(); obj2.output(); }
}

You may or may not mention this keyword while


coding the member method, but this keyword will be
there by default.
GARBAGE COLLECTION IN JAVA
The garbage collector is a utility used in the Java
Runtime System. It is a tool that wakes up time to time
at a pre specified interval. The objective of the
garbage collector is to scan the memory to find out
any object for which the program that created them
has expired. Such orphan objects have no reference to
the class from which they were created. Objects like
these are called garbage. Since the garbage objects
needlessly occupy the memory, there is a need to
remove them. The garbage collector does that job
automatically at a regular interval.
THE finalize ( ) METHOD
It is clear that the garbage collection is not done as
soon as the program is terminated and the objects lose
their reference. They would not be removed from the
memory until the next garbage collection sweep is
done. Between the time the program has terminated
and the next garbage collection, the object remain in
an unsafe state, since anybody making a memory scan
can theoretically read the values stored in the
attributes of the object. As an alternative measure, the

finalize ( ) method can be used. It achieves the


opposite objective of a constructor. The finalize ( )
method is called once for each and every object at the
moment when the last statement of the program which
created these objects have been executed. Within the
body of the finalize ( ) method we can write the code
for de-initializing the attributes of the object.
import java.io.*;
class ABC {
char a;
int b;
double c;
ABC() // DEFAULT CONSTRUCTOR, TAKES NO ARGUMENT {
a = F;
b = 10;
c = 3.1248;
}
ABC(char a1, int b1, double c1) // PARAMETERIZED CONSTRUCTOR, TAKES
ARGUMENTS {
a = a1; b = b1; c = c1;
}
ABC(ABC obj) // COPY CONSTRUCTOR, TAKES AN ENTIRE OBJECT AS
ARGUMENT {
a = obj.a; b = obj.b; c = obj.c;
}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com
public void finalize() // DE-INITIALIZING THE ATTRIBUTES OF THE OBJECTS {
a = \0; b = \0; c = \0;
}
void output() {
System.out.print(\n\n\tCHAR : +a); System.out.print(\n\tINT : +b);
System.out.print(\n\tDOUBLE : +c);
}
}
class Ayan {

public static void main(String args[]) {


ABC obj1 = new ABC(); // CALLING DEFAULT CONSTRUCTOR
ABC obj2 = new ABC(D, 25, 36.997); // CALLING PARAMETERIZED
CONSTRUCTOR ABC obj3 = new ABC(obj2); // CALLING COPY CONSTRUCTOR
obj1.output(); obj2.output(); obj3.output();
}
}

The finalize ( ) method must be declared specifically


as public. It is always executed in the background.
WHAT IF NO CONSTRUCTOR IS PROVIDED
FOR A CLASS If we do not provide any constructor,
not even the default constructor, and run the program
in the following way, a curious output will be
generated.
import java.io.*;
class ABC {
char a;
int b;
double c;
void output() {
System.out.print(\n\n\tCHAR : +a); System.out.print(\n\tINT : +b);
System.out.print(\n\tDOUBLE : +c);
}
}
class Ayan
{ public static void main(String args[]) {
ABC obj1 = new ABC(); // CALLING DEFAULT CONSTRUCTOR obj1.output();
}
}

If no constructor is provided, Java still manages to


initialize the attributes of a class to some system
defined default value. This default value depends on
the data type of the attribute. For example: int

attributes are initialized to 0, float and double are


initialized to 0.0, and char and strings are initialized to
NULL.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

METHOD OVERLOADING AND STATIC


METHODS Java allows the programmers to use the
concept of polymorphism, that is, the ability of a thing
to exist in multiple forms. Out of that we have the
concept of method overloading and constructor
overloading. In the chapter of Inheritance, we shall
learn another two forms of polymorphism, namely
method overriding and dynamic method dispatch.
METHOD OVERLOADING
Method overloading is the property of a method that
helps to create multiple versions of the same method.
We can change the return type, the argument set or
the body of a method several times, without
changing the name of the method. If method
overloading is used, the issue of linking a function call
to its appropriate function definition is determined by
the compiler by matching the argument set passed to
the called method and the argument set of the method
definition.
Why Do We Use Method Overloading?
If we need to perform the same kind of job several

times with different number and different data types of


arguments, we may have to define several different
methods having different names, different argument
sets and different bodies. It becomes difficult to
remember so many method names and when to use
them. With method overloading, this tragedy is over.
Whatever be the need, we call the same method with
appropriate set of arguments.
As for example, we may need to add two integers, add
three float values, and also add an array. Instead of
defining three different functions, we may overload
the same function with different meanings. Consider
the following example to prove this point.
import java.io.*;
class Add
{
void add(int a, int b) // VERSION 1 {
int c;
c = a + b;
System.out.print(\n\tThe sum is : +c); }
double add(double x, double y, double z) // VERSION 2
{
return (x+y+z);
}
int add(int arr[]) // VERSION 3 {
int i, sum = 0;
for(i = 0 ; i < arr.length ; i++) sum = sum + arr[i];
return sum;
}
}
class Ayan {
public static void main(String args[]) {
Add obj = new Add();

int arr[] = {10, 20, 30, 40, 50};


obj.add(10, 20);
System.out.print(\n\tThe sum is : +obj.add(10.1, 20.2, 30.3)); System.out.print(\n\tThe
sum is : +obj.add(arr));
}
}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

There are three versions of add ( ) method in this


program. First version is for adding two integers,
second version is for adding three double values, and
third version is for adding an array of five integers.
The name of the method for all three versions is the
same, but note how the return type, argument set and
the body of the methods have been changed.
While calling these methods from main ( ), the
compiler simply looks at the argument set being
passed into the method. If the method is being called
with two integer arguments, then the compiler links
the method call to that version of the program which
accepts two integers (that is, version 1). The rest of the
method calls are also resolved in this way.
It is therefore important that every version of the
overloaded method must have a uniquely identifiable
set of arguments. The uniqueness of the argument set
is sometimes called Method Signature, and can be
considered as a means to identify the version of the
method being called.

CONSTRUCTOR OVERLOADING
If we look at the program in the previous chapter
where we had used default constructor, parameterized
constructor and copy constructor in the same program,
we can say that this is an example of constructor
overloading. The only exception between constructor
overloading and method overloading is that
constructors do not have any return type and methods
have return type. Otherwise, constructor overloading
involves the creation of multiple versions of the same
constructor with different argument set and body.
STATIC ATTRIBUTES AND STATIC METHODS
The static attributes of a class are based on the same
concept of the static storage class as we find in C /
C++. The most important feature of a variable of static
storage class is that they contain a default initialized
value of zero and they can remember their value
between different method calls.
The static methods of a class are unique in the sense
because with static methods we can intentionally
override one of the most fundamental concepts of
object oriented programming language. So far we have
seen that in order to call a member method of a class,
first an object of that class is created and the methods
can be called using that object. However, if a member
method of a class is declared as static, it can be called

without declaring an object of that class. However, we


have to ensure that the attributes that the static
methods are accessing must also be declared as static.
Consider the following program.
import java.io.*;
class Add
{
static int a, b, c; // STATIC ATTRIBUTES static void input() throws IOException //
STATIC METHOD {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter first number : ); a = Integer.parseInt(br.readLine());
System.out.print(\n\tEnter second number : ); b = Integer.parseInt(br.readLine());
}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com static void add() // STATIC METHOD
{
c = a + b;
}
static void output() // STATIC METHOD {
System.out.print(\n\tThe sum is : +c); }
}
class Ayan {
public static void main(String args[]) throws IOException {
// NO OBJECT OD Add CLASS IS DECLARED // METHODS ARE CALLED ONLY
WITH THE CLASS NAME
Add.input(); Add.add(); Add.output();
}
}

The annotation says it all. The methods are called only


using the class name, not using any object of that
class. Instantly we can understand the theory behind
the integer conversion method Integer.parseInt ( ). The
capitalI in Integer tells us that it is the name of a
class, and the method of this class is being called

directly. This proves that the parseInt ( ) method is a


static method.
If it is asked why it is necessary to use the static
methods when the same thing can be done using the
normal methods, the answer is that in some cases it
becomes an absolute necessity to declare a method as
static.
Why is main ( ) public as well as static?
Consider the case of the main ( ) method. It is always
declared as static. We have to call the main ( ) method
from outside the scope of the Java system, i.e. from
the command prompt. If the rule, that we have to call
the member method of a class using an object of that
class cannot be overridden, then we have to create
another program in the command prompt itself in
order to declare an object of the class to which the
main ( ) itself is a member, and then execute the
program. Obviously this cannot be done. So main ( )
method is always declared as static.
We can also see why the main ( ) method has to be
declared as public too. The default visibility of a
member method of a class is public, if it is called from
within the body of a method that remains in the same
program. However, main ( ) is such a method that is
called from outside the system, from the command
prompt. For the same reason as explained above, the

concept of a method being public by nature cannot


hold. So main ( ) should specifically be declared as
public.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

INHERITANCE
Inheritance is an integral feature of any object oriented
programming language. Inheritance is the process of
creating a new class out of an existing class. In Java
terminology, the existing class is called the super
class and the newly created class is called sub class.
Due to inheritance the subclass may inherit some or all
the features of the base class.
Whenever there is a need to create a new class, the
programmer has two choices. Either he/she can create
the class, its attributes and the methods out of scratch,
that may take a lot of labour, time (and thereby,
money). Another option is to look out in the collection
of already created classed and trying to find out a class
that most closely matches the attribute set and the
method set of the class that is required to be created. If
such a class can be found, then all that is needed to be
done is to create the new class (sub class) out of the
already created class (super class) and directly inherit
the common attributes and the methods, and add only
those attributes and methods which are needed

specifically for the derived class. This may save a lot


of labour, time and money.
In a sense, inheritance encourages the concept of code
reuse, that is, to reuse the existing code to create new
code units.
Inheritance also gives birth to another pair of terms
called generalization and specialization. In a class
hierarchy, where a set of super class gives birth to a set
of sub classes in a top down manner, the more we
climb upwards this inheritance tree, the fewer amounts
of details would be visible. The top levels of the class
hierarchy always present those features which are
common to all the underlying classes. This is called
generalization. On the other if we descend the
inheritance tree, we would reach the sub classes that
keeps adding newer features. So, more specific
features will be visible in the bottom levels of the class
hierarchy. This is called specialization.
TYPES OF INHERITANCE SUPPORTED IN
JAVA Java supports the three types of inheritance
depicted here.
Single Inheritance
Only one sub class is created out of only one super
class.
A
B

Teacher of Computer Science and Software Technology


1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

Multilayer or Multilevel Inheritance


One class creates another class, that class creates
another class. The ultimate derived class inherits from
the father as well as the grandfather.
A
B
C
Hierarchical Inheritance
One class creates more than one class. Essentially, this
is single inheritance done more than once.
A
B C
If you have any previous experience of using
inheritance in C++, you might wonder why we have
not mentioned two other types of inheritance here, the
multiple inheritance and the hybrid inheritance. It is
because Java does not allow the creation of a sub
class by inheriting from more than super class.
THE ACCESS SPECIFIERS
Java has three access specifiers, namely private, public
and protected. Let us discuss them from the point of
view of how they can be used in inheritance.

private : a private member as we already know,


cannot be accessed outside the class and can never be
inherited.
protected: a protected member is by nature private,
meaning that they cannot be accessed outside the
class. However they can be inherited by a derived
class. Using protected mode, we can make private
members inheritable. public: a public member can be
accessed outside the class as well as can be inherited
by a derived class.
In Java, the mode of inheritance can only be of a
public nature. The effect of these three modes of
inheritance on the three types of members can be
summarized in the following diagram.
class Super
{
private members; // CAN NEVER BE INHERITED protected members;
public members;
};
class Sub extends Super {
protected members; public members;
};
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

In other words, for a public mode inheritance, the


protected members of the super class become the
protected members of the sub class and public
members of the super class become the public
members of the sub class.

SINGLE INHERITANCE
Let us now explain using some real program. The
following program describes a single inheritance. The
name of the program is InheritanceTest.java
import java.io.*; // SINGLE INHERITANCE
class A {
int a;
void inputA() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter first number : );
a = Integer.parseInt(br.readLine());
}void outputA()
{
} System.out.print(\n\tFirst number : +a);
}
class B extends A
{
int b;
void inputB() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter second number : );
b = Integer.parseInt(br.readLine());
}void outputB()
{
} System.out.print(\n\tSecond number : +b);
}
class InheritanceTest
{
public static void main(String args[]) throws IOException {
B obj = new B();
obj.inputA(); obj.inputB(); obj.outputA(); obj.outputB(); }}

Watch this program carefully. The class A is the super


class that has one integer attribute and methods to
perform input output operations on it. When we have
been asked to create a class that has two integer
attributes and input output methods, instead of

creating the class out of scratch, we are inheriting the


sub class B from class A. This is a public mode
inheritance, so the public methods of class A, namely
inputA( ) and outputA( ) have become the public
methods of class B. We may say that class B has four
public methods. As a result, in the main ( ) method,
the object of class B is calling all the four methods,
two of them have been inherited from the parent class,
and the rest are the member methods of its own.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

HOW DO THE CONSTRUCTORS WORK IN


INHERITANCE? The use of the super ( ) Method
We know that the constructors are called whenever the
object of a class is created, in order to initialize the
attributes of the class. In the above example we have
seen that we are declaring the object of the sub class
only, which may result in the sub class constructor
getting executed. But since the super class has
attribute of its own, it is necessary to execute the
constructor of the super class also, though we are not
declaring any object of the super class. So, there is a
need to link the sub class constructor and the super
class constructor so that when the sub class
constructor will be executed, the super class
constructor will also be called. The following code
shows how this can be done. This is a continuation of

the single inheritance program.


import java.io.*;
// USE OF CONSTRUCTORS IN SINGLE INHERITANCE
class A
{
int a;
A(int a1) {
a = a1;
}
void outputA() {
System.out.print(\n\tFirst number : +a); }
}
class B extends A {
int b;
B(int a1, int b1) {
super(a1); // THE super() METHOD CALLS THE CONSTRUCTOR OF THE
IMMEDIATE // SUPERCLASS
b = b1;
}void outputB()
{
System.out.print(\n\tSecond number : +b);
}
}
class InheritanceTest
{
public static void main(String args[]) {
B obj = new B(10, 20);
obj.outputA(); obj.outputB(); }
}

The object created for class B calls the parameterized


constructor of class B, because it passed two integer
constants (10 and 20) to the constructor of the class B.
The constructor of class B keeps one of these two
values (20) for itself and passes the other value to the
parameterized constructor of the super class A. The
method call super ( ) inside the body of the

constructor of any subclass is responsible to


execute the parameterized constructor of the
immediate super class. We do not need to know the
name of the immediate super class.
A Secondary use of super, as a Keyword
In the previous example we have used super as a
method call inside the body of the sub classs
constructor. There is another way the super can be
used, as a keyword. Using this technique, the
constructor of the sub class can directly access or
initialize the attributes of the super class, without
using any constructor in the super class.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com
import java.io.*; // USE OF super AS A KEYWORD RATHER THAN A METHOD
class A {
int a;
// NO CONSTRUCTOR IS NEEDED IN THE SUPERCLASS void outputA()
{
System.out.print(\n\tFirst number : +a); }
}
class B extends A {
int b;
B(int a1, int b1) {
super.a = a1; // THE super KEYWORD DIRECTLY ACCESSES THE ATTRIBUTE OF
THE // IMMERDIATE SUPERCLASS
b = b1;
}void outputB()
{
System.out.print(\n\tSecond number : +b);
}
}
class InheritanceTest

{
public static void main(String args[]) {
B obj = new B(10, 20);
obj.outputA(); obj.outputB(); }
}

Multilayer or Multilevel Inheritance


The following program shows how we can create a
new class using multilayer or multilevel inheritance.
import java.io.*;
// MULTILEVEL OR MULTILAYER INHERITANCE
class A {
int a;
A(int a1) {
a = a1;
}
void outputA() {
System.out.print(\n\tFirst number : +a); }
}
class B extends A {
int b;
B(int a1, int b1) {
super(a1); // THE super KEYWORD DIRECTLY ACCESSES THE ATTRIBUTE OF
THE // IMMERDIATE SUPERCLASS
b = b1;
}
void outputB() {
System.out.print(\n\tSecond number : +b); }
}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com
class C extends B {
int c;
C(int a1, int b1, int c1) {
super(a1, b1); c = c1;
}void outputC()
{
}
}
class InheritanceTest {
System.out.print(\n\tThird number : +c);

public static void main(String args[]) {


C obj = new C(100, 200, 300);
obj.outputA(); obj.outputB(); obj.outputC();
}
}

Hierarchical Inheritance
The following program shows how we can create a
new class using hierarchical inheritance.
import java.io.*;
class A
{
int a;
A(int a1) {
} a = a1;
void outputA()
{ System.out.print(\n\tFirst number : +a); }
}
class B extends A
{ int b;

B(int a1, int b1)


{ super(a1);
b = b1;
}void outputB()
{
} System.out.print(\n\tSecond number : +b); }
class C extends A
{
int c;
C(int a1, int c1) {
super(a1); c = c1;
}
void outputC() {
System.out.print(\n\tThird number : +c);
}}
class InheritanceTest {
public static void main(String args[]) { B obj1 = new B(10, 20);
C obj2 = new C(100, 200);
obj1.outputA(); obj1.outputB();
Teacher of Computer Science and Software Technology

1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com obj2.outputA(); obj2.outputC(); }
}

ORDER OF CALLING THE CONSTRUCTOR


In case we are calling the constructors of a class
hierarchy, the constructors are always called in the
order of the derivation. This means that the super class
constructor will be called first and the sub class
constructor will be called later. Run the following
program to see the result.
import java.io.*;
// CONSTRUCTORS ARE CALLED IN THE ORDER OF DERIVATION
// THE SUPERCLASS CONSTRUCTOR IS CALLED BEFORE THE SUBCLASS
CONSTRUCTOR
class A
{
A() {
System.out.print(\n\tClass As constructor.); }
}
class B extends A {
B() {
System.out.print(\n\tClass Bs constructor.); }
}
class C extends B {
C() {
System.out.print(\n\tClass Cs constructor.); }
}
class InheritanceTest {
public static void main(String args[]) {
C obj = new C(); }
}

METHOD OVERRIDING
This program also stands as an example of what is
called method overriding. We have already discussed
method overloading in the earlier chapter, which

means redefining the same method having the same


name with different signature and different body.
Method overriding is the technique of redefining a
method of the super class in the body of a sub class
derived from that super class.
import java.io.*;
// METHOD OVERRIDING
class A
{
void greetings() {
System.out.print(\n\tHi!!); }
}
class B extends A
{
void greetings() // ONLY THE BODY IS DIFFERENT {
System.out.print(\n\tHello!!); }
}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com
class InheritanceTest {
public static void main(String args[]) {
A obj1 = new A(); B obj2 = new B();
obj1.greetings(); // CALLING THE METHOD OF CLASS A obj2.greetings(); //
CALLING THE METHOD OF CLASS B }
}

In this example, we can see that the greetings ( )


member method of the super class A has been
redefined in the sub class B. This is also a case of
polymorphism, where two different versions of the
same method have been created in super class and
sub class. Therefore an ambiguity problem may be
generated, where the compiler is unable to understand
which of the two versions of the same method will

have to be executed. The issue of calling the particular


version of the overridden method is resolved by the
type of the object that calls this overridden method. If
an object of the super class calls the greetings ( )
method, then the version of the method in the super
class will be executed. If an object of the sub class
calls the greetings ( ) method, then the version of the
method in the sub class will be executed.
Differences between Method Overloading and
Method Overriding There are three differences
between method overloading and method overriding.
First, in method overloading, the return type, argument
set and the body of the methods are changed, but in
method overriding, only the bodies of the methods are
changed. Secondly, method overloading takes place
with methods of the same class, but method overriding
takes place between methods of the super class and the
sub class. Finally, in method overloading, the
argument set provided to the method determines the
version of the method to be called, but in method
overriding, the calling object determines the version of
the method to be called.
DYNAMIC METHOD DISPATCH
This is equivalent to the Dynamic Linking or Runtime
Polymorphism as seen in C++. It may occur in a case
where we create an object of the base class but do not

refer it to any class by calling the constructor of the


base class. By dynamically making this object refer to
the objects of different classes, we call the methods of
different classes using the same object. Consider the
following program.
import java.io.*;
class A
{
void greetings() {
System.out.print(\n\tHi!!);
}}
class B extends A {
void greetings() // OVERRIDING THE METHOD OF THE SUPER CLASS {
System.out.print(\n\tHello!!);
}
}class InheritanceTest
{
public static void main(String args[]) {
A obj1 = new A(); B obj2 = new B(); A obj; // AN OBJECT OF THE SUPER CLASS IS
CREATED WITH NO REFERENCE TO ANY
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com // CLASS obj = obj1; // obj REFERES TO AN
OBJECT OF THE SUPER CLASS obj.greetings(); // CALLING THE METHOD OF
CLASS A obj = obj2; // obj REFERES TO AN OBJECT OF THE SUB CLASS
obj.greetings(); // CALLING THE METHOD OF CLASS B }
}

ABSTRACT METHOD AND ABSTRACT CLASS


An abstract method is such a method which is declared
within a class but whose body is not defined within
that class. The body of the abstract method is defined
using the technique of method overriding inside any
class that inherits from the class containing the
abstract method.

An abstract class is such a class in which at least one


method is an abstract method. Other methods could be
defined inside the abstract class. Because an abstract
class has some undefined methods, we cannot create
an object of the abstract class.
import java.io.*;
// ABSTRACT METHOD AND ABSTRACT CLASS
abstract class A
{
abstract void greetings1(); // DECLARED BUT NOT DEFINED void greetings2() //
DECLARED AS WELL AS DEFINED {
System.out.print(\n\tHello!!); }
}
class B extends A {
void greetings1() // THE ABSTRACT METHOD IS OVERRIDEN HERE TO DEFINE
ITS BODY {
System.out.print(\n\tHi!!); }
}
class InheritanceTest {
public static void main(String args[]) {
B obj = new B();
obj.greetings1(); obj.greetings2(); }
}

THE final KEYWORD


There are three uses for the final keyword in Java. At
least two of them have a direct relevance with
inheritance.
A. If a variable is declared as final, the value it stores
cannot be changed during the scope of the program.
i.e.
final double pi = 3.1428;

B. If a method is declared as final, that method cannot

be overridden in any subclass.


i.e.final void greetings( )
{
:
}

C. If a class is declared as final, it cannot be inherited


from.
i.e.final class A
{
:
}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

PACKAGE AND INTERFACE


USER DEFINED PACKAGE
As we have seen previously, a package is a collection
of related classes, and Java has six built in packages. If
the users want then they can create a package
according to their own requirement. The following are
the steps to create and use such user defined packages.
Step 1: Within the bin subdirectory, create another
subdirectory. The name of this new subdirectory
should be the same as the name of the user defined
package.
Suppose we want to create a package called mypack.
We begin with the following statement.
md mypack

Step 2: Change to the newly created subdirectory.


cd mypack

Step 3: Within this subdirectory, create a new file with


.java extension.
edit IO.java

Step 4: The very first statement inside this new file


would be
package mypack;

This statement identifies that this class belongs to a


user defined package named mypack. This statement
should precede even the import statement.
Step 5: Create the new program. Keep in mind that
the class and the methods within this class must
explicitly be defined as public. This is because the
class and the methods should be used in another
program in another path.
package mypack;
import java.io.*;
public class IO
{
public int input() throws IOException {
int n;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); n =
Integer.parseInt(br.readLine());
return n;
}
public void output(String s) {
System.out.print(\n\t+s); }
}

This program contains a class named as IO, and


defines two methods, one for taking integer input, the
other for making a string output.
Step 6: Save the file and exit the editor to come out

into the command prompt.


Step 7: Change to the bin subdirectory.
cd..

Step 8: Compile the IO.java program while staying


within bin subdirectory.
Javac mypack\IO.java
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

Step 9: Create another new file with .java extension


inside the bin subdirectory. Suppose the name of this
file is Ayan.java. Import the class from the user
defined package. Create an object if that class co that
the method of that class can be executed.
import java.io.*;
import mypack.IO; // IMPORTING THE IO CLASS FROM THE USER DEFINED
PACKAGE mypack
class Ayan {
public static void main(String args[]) throws IOException {
int a, b, c;
IO obj = new IO();
obj.output(Enter first number : ); a = obj.input();
obj.output(Enter second number : ); b = obj.input();
c = a + b; obj.output(The sum is : +c); }
}

The advantage of using the user defined package can


be understood from this example. If we are to perform
some complex jobs many, many times, it is better to
put that job into a user defined package and use that
package accordingly whenever we need to do that job
again. In any normal Java program, we have to write
lengthy statements to declare the object for

BufferedReader class, the Sysetm.out.print ( ) method


for making output, and the
Integer.parseInt(br.readLine ( )) method for taking
integer input from keyboard. In the example that we
have explained, these jobs have been put inside the
methods of the class in the user defined package. For
any future programs, we can use the package to skip
the burden of writing these statements.
INTERFACE
An interface is similar to a class, but it also has some
major differences. Differences between a Class and
an Interface
1. A class is declared with the keyword class, but an
interface is declared withthe keyword interface.
2. A class can have attributes and methods, but an
interface generally has methods. Attributes within an
interface are not relevant.
3. The methods inside a class are declared and defined,
but the methods within an interface are declared only,
their bodies are not defined. The bodies of the
undefined methods of the interface are defined inside
any class that uses the interface.
4. If a new class is created from a class, we have to use
the keyword extends. If a new class is created from
an interface, we have to use the keyword
implements.

5. The most important difference is that while creating


a new class we can extend from only one super class,
but there is no restriction in the number of interfaces
that can be implemented while creating a new class.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com import java.io.*;
class Super {
public void classMethod() {
System.out.print(\n\tThis is the class method.); // DECLARED AND DEFINED
WITHIN THE CLASS }
}
interface Inter1 {
public void inter1Method();
// DECLARED WITHIN THE INTERFACE BUT NOT DEFINED
}
interface Inter2 {
public void inter2Method();
// DECLARED WITHIN THE INTERFACE BUT NOT DEFINED
}
class Sub extends Super implements Inter1, Inter2 {
// THE INTERFACE METHODS ARE DEFINED WITHIN THE CLASS THAT HAS //
IMPLEMENTED THE INTERFACE
public void inter1Method() {
System.out.print(\n\tThis is first interfaces method.); }
public void inter2Method() {
System.out.print(\n\tThis is second interfaces method.); }
}
class InterfaceTest {
public static void main(String args[]) {
Sub obj = new Sub();
obj.classMethod(); obj.inter1Method(); obj.inter2Method();
}
}

Look at the statement where we are creating the new


class Sub.
class Sub extends Super implements Inter1, Inter2

This class implements two interfaces, which proves


that a new class can implement as many interfaces as
it may like.
The class Super has a method which is declared and
defined within itself, and this method is available
readymade in the Sub class. The two interfaces Inter1
and Inter2 have one method each which is available to
the Sub class. The Sub class overrides these two
methods and defined them accordingly. In the main ( )
method an object of the Sub class can execute all three
methods.
Comparison of Abstract Class and Interface
In some respect, an interface can be compared to the
abstract class, which also has some methods declared
but not defined. However there are two important
differences between an abstract class and an interface.
1. In an abstract class, some methods may be defined
and some may not be defined. In an interface each and
every method should remain undefined.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

2. We cannot create a new class by extending more


than one abstract class, but we can create a new class
by implementing as many interfaces as we like.

Creating Interface from another Interface


An interface can be extended to create another
interface.
import java.io.*;
interface A
{
void methodA();
}
interface B extends A
{
void methodB(); // INTERFACE B INHERITS THE METHOD OF INTERFACE A,
ALSO DECLARES
} // A METHOD OF ITS OWN.
class C implements B // CLASS C HAS BOTH THE METHODS AVAILABLE {
public void methodA() // METHOD OF INTERFACE A OVERRIDEN HERE {
System.out.print(\n\tInterface As method.); }
public void methodB() // METHOD OF INTERFACE B OVERRIDEN HERE {
System.out.print(\n\tInterface Bs method.); }
public void methodC() // THIS IS CLASS CS OWN METHOD {
System.out.print(\n\tClass Cs method.); }
}
class Ayan {
public static void main(String args[]) {
C obj = new C();
obj.methodA(); obj.methodB(); obj.methodC();
}
}

If a new class is created from an interface, the


implements keyword is used. If a new interface is
created from another interface, the extends keyword
is used.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

EXCEPTION HANDLING

The term exception is a short form for any runtime


error that is caused during the execution of the
program and that disturbs the normal flow of
execution. When an error occurs in a Java method, it is
handled by the Java Runtime Environment in the
following manner.
Every time a runtime error occurs in a Java method, it
becomes the responsibility of the method to detect the
type of exception that has occurred. To help this job,
the java.lang package contains a group of classes that
are known as the exception classes. Each one of these
classes defines one particular type of exceptional
situation. When the Java method determines what type
of exception has occurred (by consulting the library of
the exception classes) it creates an object of the
particular type of exception class and delivers that
object to the runtime system. This process is called
throwing the exception. After the exception object
has been thrown, the Java method stops the execution
of the program at the statement where the exception
has occurred.
The runtime system, as a response to the throwing of
the exception object, begins to search the same
program to find out an exception handler. A piece of
code is termed an exception handler if it receives, as
its argument, an object of the same exception class as

was thrown to the runtime system. If such an


exception handler is found, the control is transferred to
the exception handler. The exception handler contains
some simple, user friendly error messages that tell the
user what error has occurred and how to deal with it so
that it does not occur the next time.
If the runtime system does not find an appropriate
exception handler, then the runtime system displays a
default error message. In both the cases, the program
that has encountered the exception is prevented to
continue beyond the point where the exception has
been encountered.
HOW TO IMPLEMENT EXCEPTION
HANDLING IN JAVA
There are three blocks of code that are used in Java to
implement the concept of exception handling.
try block: This is a block of code where we include
all those statements that we expect to cause some
exception.
try {
Java statements; }

The operation of the try block can be compared to that


of an antivirus. It monitors all those statements that are
included in it. If the try block detects that a statement
has caused some exception, it detects the type of

exception by consulting the library of the exception


classes and creates an object of the specific exception
class whose definition matches with the exceptional
event. After that the exception object is thrown by the
try block to the runtime system. The try block prevents
the execution of the program to go on beyond the
statement where the exception has occurred.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

catch block: The catch block serves as the exception


handler. It takes as its argument an object of some
exception class. One or more catch blocks can be
associated with a try block.
try {
Java statements;
}catch(argument)
{
Error handling statements; }

The catch block contains some error messages that are


easy to understand.
finally block: The finally block contains some
finalizing statement. Many times it is required that a
particular statement must be executed in any situation.
For example, consider a program where we have
opened a file in the try block, and we need that the file
should be closed properly before the program is
terminated. If there is an exception in any statement
inside the try block, there is every possibility that the

file closing statement will never be executed. It is


better to put such a statement in the finally block, that
follows the set of the catch blocks. The speciality of
the finally block is that the statement inside this block
are executed no matter whether an exception occurs or
not.
try {
Java statements;
}catch(argument)
{
Error handling statements; }
finally
{
Cleanup code; }

The next program ExceptionTest.java illustrates this


concept. We are accepting one integer value and
printing it.
import java.io.*;
class ExceptionTest {
public static void main(String args[]) {
int n;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print(\n\tEnter a number : ); n = Integer.parseInt(br.readLine());
System.out.print(\n\tYou entered : +n);
}
catch(IOException e)
{
System.out.print(\n\tThis is an Input Output Exception.);
}
catch(NumberFormatException e)
{
System.out.print(\n\tThis is a Number Format Exception.);
}finally
{
System.out.print(\n\tFinally block, will be executed anyway.); }
}

}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

There are some aspects of this program that need


explanation. The three lines of code that asks the user
input, takes the input and prints the value, are put
inside a try block, as we expect some exception to
occur in this portion of code. There are two catch
blocks associated with this try block, one of
IOException, the other one for
NumberFormatException. In the previous examples,
we used a technique whereby the method that takes the
input is written with the statement throws
IOException. It meant that the method itself is
responsible to create an object of the IOException
class and throw the object to the runtime system if an
error occurs. In this program the alternative and more
methodical way of exception handling has been
shown, using the try and catch block.
If we run this program, and no error is made while
inputting an integer value, the number will be printed
and the content of the finally block will be printed. If
there is any error (such as inputting a string instead f
an integer), the output of the catch blok for
NumberFormatException will be printed, along with
the content of the finally block.

The next program uses the concept of nested try catch


construct, in which an entire try
- catch block is nested inside another try - catch.
import java.io.*;
class ExceptionTest
{
public static void main(String args[]) {
int a, b, c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print(\n\tEnter first number : ); a = Integer.parseInt(br.readLine());
System.out.print(\n\tEnter second number : ); b = Integer.parseInt(br.readLine());
try {
c = a / b;
System.out.print(\n\tThe result of division : +c);
}
catch(ArithmeticException e)
{
System.out.print(\n\tCannot divide a number by zero.);
}
}
catch(IOException e)
{
System.out.print(\n\tThis is an Input Output Exception.); }
catch(NumberFormatException e)
{
System.out.print(\n\tThis is a Number Format Exception.);
}finally
{
System.out.print(\n\tFinally block, will be executed anyway.); }
}
}

CREATING USER DEFINED EXCEPTION


All the exception classes that we have seen so far are
system defined exception classes. If we want, we can
create our own type of exception classes too. The next

Teacher of Computer Science and Software Technology


1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

program creates a user defined exception class that


defines an exception when a positive integer is not
input through the keyboard.
import java.io.*; class MyException extends Exception {
int detail; MyException(int d)
{
detail = d;
}
}
class ExceptionTest {
static void evaluate(int n) throws MyException {
if(n <= 0)
throw new MyException(n); else
System.out.print(\n\tThank you.); }
public static void main(String args[]) throws IOException {
int n;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print(\n\tPlease enter a positive number : ); n =
Integer.parseInt(br.readLine());
evaluate(n); }
catch(MyException e) {
System.out.print(\n\tYou have entered : +e.detail); System.out.print(\n\tThis is not a
positive number.);}
}
}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

MULTITHREADING
A thread can be considered as a part of a process that
can be executed independently by the CPU. Any
running program is called a process. Normally, a CPU
can execute one process at a time. In case of

multiprogramming, the CPU divides its execution time


into several time slots and executes one process in one
time slot. A process may have to be executed for many
time slots before it completes its execution.
The concept of multithreading goes one step further
and divides the CPU time slots in such a way that the
CPU can execute different threads of the programs in
different time slots. A process can be broken down
into several threads. In Java terminology, such a
process is called a multithreaded process. Otherwise
the process is called a single threaded process.
An example of multithreading is the ability of a
program like the Internet Explorer to allow the user to
view a webpage, print that webpage on the printer and
download a file, all seemingly at the same time. These
tasks of the same process appear to be running
concurrently, because each task has been assigned to a
new thread. The main advantage of multithreading is
the speed of execution of the program.
DIFFERENCE BETWEEN THREAD AND
PROCESS
The main difference between a thread and a process is
that a thread cannot exist on its own. A thread can only
exist by being part of a process. The end user cannot
execute the thread directly without running the process
in which this thread is a part. On the other hand, a

process may consist of one or more threads, depending


upon which the process is termed as single threaded or
multithreaded process, respectively.
HOW IS MULTITHREADING IMPLEMENTED
There are two different ways to implement
multithreading in a Java program. The first one is to
create the class by extending it form the Thread class.
class MyThread extends Thread {
: :
}

The other one is to create the class by implementing


the Runnable interface.
class MyThread implements Runnable {
: :}

Both the Thread class and the Runnable interface are


part of the java.lang package, therefore imported
automatically in the program. Whatever way we
follow, the main technique to create the threads is to
override a particular method called the run ( ) method,
which is available in both the Thread class and the
Runnable interface. The body of the overridden run ( )
method generally contains some kind of a loop, and it
defines the activity of the thread.
To define the activity of the thread, Java language uses
the three following aspects of all the threads.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:

ayankumarchatterjee@yahoo.com

Thread Body : All activity of the thread is done inside


the thread body. The threads body, as already
mentioned, is defined by overriding the run ( ) method,
that contains some kind of a loop.
Thread Status: During the life cycle of the thread, it
may enter any one of the four following states.
Time slot gained Running stop ( ) called or run ( ) expired
Time slot expired start ( ) Not Running Newstop ( ) Dead
stop ( )
The thread is in the New state whenever an object of
the MyThread class is created. It means the thread is
placed in the memory. But it takes a little more time in
order to prepare the CPU to accept the thread so that
the thread could be executed. By calling the start ( )
member method of the Thread class, the thread is
loaded in the CPU. It then comes in the Running
state. The thread is switched alternatively between the
Running and Not Running state depending on the
expiry of the time slots. After the execution of the
thread is over due to the expiry of the loop in the run (
) method, the thread comes naturally to the Dead state.
However, just like the opposite of calling the start ( )
member method of the Thread class, the stop ( )
member method of the Thread class can be called to
stop the execution of the thread.

Thread Priority : The priority of the thread


determines the order in which the threads are
executed. Threads with higher priority get more CPU
time slots than threads with lower priority. This results
in a faster execution of the higher priority thread over
the lower priority threads. If nothing is mentioned, all
threads have a default equal priority, and get more or
less the same amount of CPU time. The default
priority can be changed using the setPriority ( )
member method of the Thread class. The priority of
the threads is measured on a scale of integers between
1 and 10. The default priority is 5. To simplify the use
of the priorities, Java defines the following constants:
Constant
MIN_PRIORITY NORM_PRIORITY
MAX_PRIORITY
Priority Value 1
5 (Default) 10
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

The first program to show the concept of


multithreading is called ThreadDemo.java.
import java.io.*; class NewThread implements Runnable {
Thread t;
NewThread() // DEFAULT CONSTRUCTOR TO INITIALIZE THE NEW THREAD {
t = new Thread(this, DEMO THREAD);
System.out.print(\n\tChild Thread : +t); t.start(); // STARTING THE EXECUTION OF
THIS THREAD
}

public void run() // THIS FUNCTION MAKES THE THREAD RUN {


try {
for(int i = 5 ; i > 0 ; i) {
System.out.print(\n\t\tChild Thread : +i); Thread.sleep(500); // SLEEPING FOR 0.5
SECOND }
}catch(InterruptedException e)
{
System.out.print(\n\tChild interrupted.); }
System.out.print(\n\tExiting Child Thread.);
}
}
class ThreadDemo
{
public static void main(String args[]) {
new NewThread(); // CREATING A NEW MAIN THREAD
try {
for(int i = 5 ; i > 0 ; i) {
System.out.print(\n\tMain Thread : +i); Thread.sleep(1000); // SLEEPING FOR 1
SECOND }
}
catch(InterruptedException e)
{
System.out.print(\n\tMain interrupted.);
}
System.out.print(\n\tExiting Main Thread.); }
}

Explanation for the above program is like this. The


class that has to run the thread is named as
NewThread, which implements the Runnable
interface. An object of the Thread class t has been
created, that serves as the sole attribute of the
NewThread class. The default constructor of the
NewThread class is responsible to initialize the thread
with the name DEMO THREAD. After printing the
name of the thread, the t object of the Thread class
is used to call the start ( ) member method, that

ultimately results in the calling of the run ( ) method.


The run ( ) method contains a loop that goes from 5 to
1, after sleeping for half a second after each iteration.
The main ( ) method also contains a loop that too goes
from 5 to 1, after sleeping for one second at each
iteration. The program therefore contains two loops,
one in the main ( ) method, another in the run ( )
method. Because the two loops have been assigned to
different threads, the CPU can execute them side by
side. Run the program and see the output.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

The next program is called ThreadTest.java. This


program goes one step further by introducing multiple
children threads along with the main ( ) thread.
Additionally, it ensures that the parent thread can
remain alive longer than the children threads. In any
kind of parent child relationship, the parent must
remain alive until the time the child has finished
execution. In the earlier program we had used timers
with the loop in such a way that the child thread is
executed for 2.5 seconds and the parent thread is
executed for 5 seconds. But it had been done
manually. In the next program, we shall do it
automatically by using the join ( ) member method of
the Thread class. This method can be used in the body

of any parent thread. This method automatically


prompts the main thread to remain alive until all the
threads created from that main thread are terminated.
import java.io.*;
class NewThread implements Runnable {
String name; Thread t;
NewThread(String threadName) // CONSTRUCTOR {
name = threadName;
t = new Thread(this, name);
System.out.print(\n\tNew child thread : +t);
t.start(); // THIS METHOD IS USED TO MAKE THE THREAD RUNNING
}
public void run() {
try {
for(int i = 5 ; i > 0 ; i) {
System.out.print(\n\t\tThread +t+ : +i); Thread.sleep(1000);
}
}catch(InterruptedException e)
{
System.out.print(\n\tThread +t+ interrupted.); }
System.out.print(\n\t\tExiting child thread +t);
}
}
class ThreadTest
{
public static void main(String args[]) {
NewThread t1 = new NewThread(One); // HERE WE ARE CREATING THREE
OBJECTS // OF THE NEW THREAD CLASS NewThread t2 = new NewThread(Two);
NewThread t3 = new NewThread(Three);
try {
System.out.print(\n\tMain Thread waiting for children to finish.); t1.t.join();
t2.t.join();
t3.t.join();
}
catch(InterruptedException e)
{
System.out.print(\n\tMain interrupted.);
}
System.out.print(\n\tExiting main thread.); }
}

The next program illustrates the use of threads with


different priorities. The previous programs mentioned
nothing about the priority of the threads, therefore it
can be assumed that the threads have an equal priority
of 5 (the default NORM_PRIORITY). In such a case
the CPU assigns almost equal number of time slots for
all the threads.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

In the next program, named as HiLoPri.java we should


be intentionally violating the default priority, in order
to create two threads with two different priorities. The
end result would give us two threads that run for the
same time (10 seconds), but the CPU would assign
more time slots for the higher priority thread and less
time slots for the lower priority thread.
import java.io.*; // DEMONSTRATE THREAD PRIORITIES.
class Clicker implements Runnable {
int click = 0;
Thread t;
private volatile boolean running = true; public Clicker(int p)
{
t = new Thread(this); t.setPriority(p);
}public void run()
{
while (running) {
click++; }
}
public void stopping() {
running = false; }
public void starting() {

t.start(); }
}
class HiLoPri {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY); Clicker hi = new
Clicker(Thread.NORM_PRIORITY + 2); // PRIORITY 7 Clicker lo = new
Clicker(Thread.NORM_PRIORITY - 2); // PRIORITY 3
lo.starting(); hi.starting(); try {
Thread.sleep(10000); }
catch (InterruptedException e) {
System.out.println(Main thread interrupted.); }
lo.stopping(); hi.stopping();
// Wait for children threads to terminate. try
{
hi.t.join();
lo.t.join();
}
catch (InterruptedException e)
{
System.out.println(InterruptedException caught);
}System.out.println(Low-priority thread : + lo.click);
System.out.println(High-priority thread : + hi.click); }
}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

STRING HANDLING
In C or C++ programming languages, a character array
is called a string. There are some fundamental
difference between an array of any other data type and
that of a character data type.A null character (\0) is
automatically appended at the end of the character
string, which does not happen in the case of an array
of any other data type. Additionally, while trying to
make input or output with a character array, the entire

array can be manipulated at once, but to do the same


with an array of any other data type, we must have to
use loops.
In Java, there is absolutely no difference between an
array of any other data type and an array of character
data type. In order to deal with strings in the same way
as done in C or C++, Java provides a class called
String (S is capital) which is part of the java.lang
system package.
There are several different ways to declare and
initialize an object of the string class.
1. As a normal object of the String class, using the
parameterized constructor of the class.
String s = new String(ABCD);

2. Directly initializing the string to the object.


String s = ABCD;

3. Using copy constructor.


String s1 = new String(ABCD);
String s2 = new String(s1);

4. Assigning a declared object directly to another


String object.
String s1 = new String(ABCD);
String s2 = s1;

5. Creating the object from a character array.


char arr[] = {A, B, C, D, E, F};
String s1 = new String(arr); => The object is initialized as ABCDEF String s2 = new
String(arr, 2, 3); => The object is initialized as CDE

Because the objects that we have declared are the

objects of the String class, the objects can call all the
member methods available in the String class. Here we
should be seeing how to call the member methods of
the String class to perform different types of activities.
The first method is the length ( ) method of the String
class, that returns the number of characters in the
string.
// LENGTH OF A STRING
class StringTest
{
public static void main(String args[]) throws IOException {
String s;
int l;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter a string : ); s = br.readLine();
l = s.length(); System.out.print(\n\tThe string contains +l+ characters.); }
}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

The charAt ( ) method takes an integer as its argument


and returns the character at that index of the string.
// charAt() METHOD
class StringTest
{
public static void main(String args[]) throws IOException {
String s;
int i;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter a string : ); s = br.readLine();
for(i = 0 ; i < s.length() ; i++)
System.out.print(\n\t+s.charAt(i)); }
}

Two strings can be concatenated using the normal +

operator. If we try to concatenate a string with a non


string value, the non string value is first converted into
a string, and then the two strings are converted into a
third string.
// CONCATENATION OF TWO STRINGS USING + OPERATOR OR concat()
MEMBER METHOD class StringTest
{
public static void main(String args[]) throws IOException {
String firstName, surName, fullName;
int l;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter your first name : ); firstName = br.readLine();
System.out.print(\n\tEnter your sur name : ); surName = br.readLine();
fullName = firstName+ +surName; // THIS COULD ALSO BE WRITTEN AS =>
fullName = firstName.concat(surName);
System.out.print(\n\tHello, +fullName); }
}

The equals ( ) method returns a Boolean true or false


value depending upon whether the content of two
string objects are equal or not. The first string object
serves as the calling object and the second object is
passed to the method as an argument. However the
equals ( ) method returns false if the two string to be
compared do not match in their case. For that reason
we need the equalsIgnoreCase ( ) method.
// STRING COMPARISON WITH equals() and equalsIgnoreCase()
class StringTest
{
public static void main(String args[]) throws IOException {
String s1, s2;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter first string : ); s1 = br.readLine();
System.out.print(\n\tEnter second string : ); s2 = br.readLine();
if(s1.equals(s2))

System.out.print(\n\tThe strings are equal.);


elseSystem.out.print(\n\tThe strings are not equal.);
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com if(s1.equalsIgnoreCase(s2))
System.out.print(\n\tThe strings are equal.); else
System.out.print(\n\tThe strings are not equal.); }
}

The compareTo ( ) method compares two strings and


returns an integer value. If the first string is greater the
method returns a positive integer. If the second string
is greater the method returns a negative integer. If the
strings are equal, the method returns zero.
// compareTo() METHOD
class StringTest
{
public static void main(String args[]) throws IOException {
String s1, s2;
int c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter first string : ); s1 = br.readLine();
System.out.print(\n\tEnter second string : ); s2 = br.readLine();
c = s1.compareTo(s2); if(c > 0)
System.out.print(\n\tFirst string is greater.); else if(c < 0)
System.out.print(\n\tSecond string is greater.); else
System.out.print(\n\tThe strings are equal.); }
}

The substring ( ) method returns part of a string. We


need to provide two integer arguments to this method,
the first integer value represents the starting index of
the string and the second integer represents the
number of characters to be extracted from the starting
index.
// substring() METHOD
class StringTest

{ public static void main(String args[]) throws IOException

{
String s;
int i;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter a string : ); s = br.readLine();
for(i = 0 ; i <= s.length() ; i++)
System.out.print(\n\t+s.substring(0, i));
// STARTING FROM THE 0 INDEX, EXTRACTING i NUMBER OF CHARACTERS
}}

Another very important method is the toString ( )


method, which is not a member method of the String
class, but closely associated with how strings are used
in Java. The toString ( ) method can be a public
member method of any class. The objective of this
method is to create and return a string that contains the
values of all the attributes of an object of that class.
The specialty of this method is that it need not be
called using an object of the class to which it is a
member. The toString ( ) method is called
automatically whenever we try to directly print an
object of that class using a System.out.print ( )
method.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com // toString() METHOD
class ABC {
char a;
int b;
double c;
ABC(char a1, int b1, double c1) {
a = a1; b = b1; c = c1;
}

public String toString() {


String s;
s = a+, +b+, +c; return s;
}
}
class StringTest {
public static void main(String args[]) {
ABC obj = new ABC(D, 12, 39.974);
System.out.print(\n\tThe attributes is this object are : +obj); }
}

The next program discusses how we can create an


array of strings and sort it. The array of strings can be
created much like an array of any other data type. In
order to sort the strings in the array we can compare
them using the compareTo ( ) method, and swap them
if necessary.
import java.io.*;
class StringTest
{
public static void main(String args[]) throws IOException {
String name[] = new String[5];
int i, j;
String temp;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(i = 0 ; i < name.length ; i++) {
System.out.print(\n\tEnter a name : ); name[i] = br.readLine();
}
for(i = 0 ; i < name.length-1 ; i++) {
for(j = i+1 ; j < name.length ; j++) {
if(name[i].compareTo(name[j]) > 0) {
temp = name[i]; name[i] = name[j]; name[j] = temp; }
}
}
System.out.print(\n\tThe sorted names are : ); for(i = 0 ; i < name.length ; i++)
System.out.print(\n\t\t+name[i]); }
}

The following program that we are going to discuss

here is one about the command line argument.


Whenever we have used the main ( ) method, we have
put an argument to it, namely String args[]. Now
you can understand that it is an array of Strings. This
array of Strings is used for programming with
command line arguments.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com
import java.io.*; // COMMAND LINE ARGUMENT
class StringTest {
public static void main(String args[]) {
int i;
System.out.print(\n\tNumber of arguments : +args.length ); System.out.print(\n\tThe
arguments are : );
for(i = 0 ; i < args.length ; i++)
System.out.print(\n\t\tArgument +i+ is : +args[i]); }
}

After the program is compiled, it will have to be


executed in a little differently. We can provide as
many strings as we may need into the program using a
statement at the command prompt that looks like
java StringTest ABC PQR XYZ

The three strings like ABC, PQR, and XYZ are


provided into the program, that are accepted into the
array of strings named as args[]. Using the args[], we
can find out the number of strings provided to the
program as command line argument, and the
individual string arguments too.
StringBuffer Class

The StringBuffer class is a peer class of the String


class. The String class contains objects where the
length of the string becomes fixed once the object has
been initialized. The StringBuffer class contains all the
facilities of the String class. Additionally it also
contains a buffer, that is, some additional spaces are
allocated in every object of the StringBuffer class
using which the object containing the string can
dynamically grow in size if there is the need to do so.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

APPLET PROGRAMMING AND AWT


WHAT IS AN APPLICATION?
A normal program in Java is called a Java Application.
An application resides on the hard disk of the same
machine where it is executed. All the library classes
needed to execute the application is available on the
same machine as well. When the application is needed
to be executed, the program is fetched from the hard
disk of the same machine into the memory of the same
machine. The applications can be called a standalone
program that can be executed without any outside
help.
WHAT IS AN APPLET?
An applet, as opposed to the application, resides on
one machine but runs in another machine. The

machine which executes the program is called the


local machine (equivalent to a client), and the machine
on which the program is kept is called the remote
machine (equivalent to a server). When the local
machine wants to execute the applet, it fetches the
applet from the hard disk of the remote machine to the
memory of the local machine via some kind of
network.
REMOTE LOCAL
Applet
NetworkApplet Stored Executed Here Here (HDD)
(RAM)
As it is evident that the applet would be run in another
machine rather than the machine of the programs
origin, it is not possible to ensure that the local
machine would contain all the libraries needed to
execute the applet. For this reason a different approach
is taken to execute an applet. The applet is not
executed directly in the same sense as an application is
executed. Rather, the applet is made to execute in an
indirect manner.
After the code for the applet is written and the
program is compiled, the .class file is created. The
remote machine then embeds the .class file into a
HTML page. When the local machine wants to
execute the applet, all it has to do is to use a Java
enabled HTML browser (like Internet Explorer) and

type the url for the HTML page stored in the remote
machine. As a result the HTML page is fetched from
the remote machine to the local machine via the
network. The job of providing the Java library files
rests on the HTML browser.
DIFFERENCE BETWEEN AN APPLICATION
AND AN APPLET There are some important
differences between an application and an applet.
1. Applications resides in the same machine where it is
executed, applet resides in a different machine.
2. Applications are fetched from the local hard disk;
applets are fetched from the network.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

3. Applications are standalone program, as they


contain all the libraries locally. Applets cannot run on
their own, they need the support of a Java enabled
HTML browser.
4. An application begins execution from the main ( )
method, but applets do not contain any main ( )
method.
GENERAL STRUCTURE OF AN APPLET An
applet contains the five following methods.
1. init ( ) : This is a public method that does not take
any argument, nor returns any value. This is equivalent

to the constructor method. The objective of the init ( )


method is to initialize the attributes or variables. This
method is called only once whenever the applet begins
its execution.
2. start ( ) : This method is called many times in the
life cycle of the applet. Whenever the applet receives
focus as a result of scrolling through the browsers
window, the method is called.
3. stop ( ) : This method is also called many times in
the life cycle of the applet. Whenever the applet loses
focusas a result of scrolling through the browsers
window, this method is called.
The start ( ) and stop ( ) methods are needed because
we do not need to keep the CPU busy executing the
applet when the applet is not at all visible. So, when
the applet is not visible, the stop ( ) method is called to
temporarily suspend the execution of the applet. When
the applet becomes visible again, the start ( ) method is
called to resume the execution of the applet.
4. destroy ( ) : This method is called only once when
the execution of the applet is terminated, and the
applet is completely offloaded from the memory of the
local machine.
5. paint ( ): Called every time the applets canvas area
needs to be refreshed.

We should now be doing a program that creates a


simple online calculator using a Java applet. The name
of the program is Calculator.java
import java.io.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*; import java.applet.*;
public class Calculator extends Applet implements ActionListener {
Label l1, l2;
TextField tf1, tf2; Button b1, b2, b3, b4; String msg =;
int n1, n2, result;
public void init() {
l1 = new Label(Enter first number : ); l2 = new Label(Enter second number : );
tf1 = new TextField(4); tf2 = new TextField(4);
b1 = new Button(+); b2 = new Button(-); b3 = new Button(*); b4 = new
Button(/);
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com add(l1); add(tf1); add(l2); add(tf2);
add(b1); add(b2); add(b3); add(b4);
b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
n1 = Integer.parseInt(tf1.getText()); n2 = Integer.parseInt(tf2.getText());
String str = ae.getActionCommand(); if(str.equals(+)) {
result = n1 + n2;
msg = The result is : +result;
}
else if(str.equals(-))
{
result = n1 - n2;
msg = The result is : +result;
}
else if(str.equals(*))
{
result = n1 * n2;
msg = The result is : +result;

}
else
{
if(n2 == 0)
msg = The result is : Undefined; else
{
result = n1 / n2;
msg = The result is : +result; }
}
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 50, 50);
}
}

Let us explain the program now.


CREATING THE CLASS
The first statement
public class Calculator extends Applet implements ActionListener

says that we are declaring a class called Calculator,


which is inherited from the Applet class. The Applet
class is part of the system package java.applet, hence
that package has been imported. The Applet class
serves as the super class for any class that wants to
create an applet.
CREATING THE AWT OBJECTS
The class Calculator uses some objects of the classes
Label, TextField and Button as its attribute. It also
uses three integer variables and a string objects as its
attribute. The classes Label, TextField and Button are
called AWT classes (short form for Abstract Window

Toolkit). These classes enable the applet to use some


windows objects that
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

are commonly found in any graphical user interface


programming. Unlike applications, which uses
character user interface, the applets can always be
executed in a graphical user interface environment. In
order to use these classes, the java.awt package has to
be imported.
import java.awt.*;

Inside the init ( ) method we may define the objects of


the AWT classes one by one the statement
l1 = new Label(Enter first number : );

denotes that the constructor of the Label class is


passed the string Enter first number as its argument,
and accordingly, this string will be printed as the
caption of the first label. In similar way the statement
tf1 = new TextField(4);

says that the first text field will be 4 characters wide,


and the statement
b1 = new Button(+);

says that the caption for the first button will be +. In


all, two labels, two text fields and four buttons are
created.
ADDING THE AWT OBJECTS TO THE APPLET
After these AWT objects have been created, the next

step is to attach them to the canvas area of the applet,


in order to make them visible. To do that the add
statements are used, like
add(l1);

ACTIVATING THE AWT OBJECTS


Out of the 8 AWT objects we have created and added
so far, we need that the four buttons should be
activated, so that if we click any one of them some
kind of calculation will take place. Now it is the time
to use the ActionListener interface which the
Calculator class implements. Java provides a set of
Listener interfaces that are applied in appropriate
scenarios. A listener interface does what its name
suggests. It listens for anyone to call its name. If it is
not called, it does not do anything, but if it is called
the Listener interface is activated. All the Listener
interfaces are part of the event sub package that
remains under the java.awt package. They should have
to be imported separately.
import java.awt.event.*;

The ActionListener interface is responsible to take


care of any activity that may occur if a button is
clicked. Because we want the four buttons to be
activated, the ActionListener is added to the four
buttons individually, as
b1.addActionListener(this);

Up to this point we have created the AWT objects ,


attached them to the applets canvas and activated the
buttons. Next we have to write the code for what to do
in case a button is clicked. To do that we need to
override a method of the ActionListener interface, it is
called the actionPerformed ( ) method. This method
takes on object of the ActionEvent class as its
argument. The ActionEvent class is part of the
java.awt.event package.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com

WRITING THE CODE FOR THE ACTIVATED


AWT OBJECTS Inside the body of the
actionPerformed ( ) method, we can write appropriate
code for the calculation of the results according to the
button clicked. First of all, the variables n1 and n2
would read the values provided by the user from the
text field. To do that we write the code
n1 = Integer.parseInt(tf1.getText());

getText ( ) is a member method of the TextField class,


for which it has been called using an object (tf1) of the
same class. This method reads a string from the text
field. After that the string is converted into a integer
value using the familiar Integer.parseInt( ) method.
After reading the inputs we have to determine which
button has been clicked, because clicking any one of

the four buttons would result in different kind of


calculation. The statement
String str = ae.getActionCommand();

returns a string that contains the caption of the button


which has been clicked. getActionCommand ( ) is a
member method of the ActionEvent class, therefore
has been called using an object (ae) of that class too.
All that is remaining is to performs appropriate kind of
calculation after determining the button which has
been clicked.
SHOWING THE OUTPUT
The last statement in the actionPerformed ( ) method is
the repaint ( ) method, which is called anytime we
need to refresh the canvas of the applet. Calling the
repaint ( ) method results in the calling of the
following paint ( ) method. The paint ( ) method
accepts an object of the Graphics class (part of AWT
package). Using that object we can call the drawString
( ) method of the Graphics class. This method prints a
string (msg) on the canvas of the applet on a specified
pixel position. The (50, 50) values specify the X and Y
coordinates of the pixel position where we want the
message to be printed.
COMPILING THE APPLET
We should now compile the Calculator.java file

normally as
javac Calculator.java

which creates the byte code file named


Calculator.class
CREATING THE HTML PAGE
There is no way the Calculator.class file can be
executed directly. As we have stated before, we need
to have a HTML file in which the Calculator.class
should have to embedded. We now create the HTML
file, and for the sake of simplicity, we name it as
Calculator.html
<html>
<head>
<title>A Simple Calculator Applet</title>
</head>
<body>
<applet code = Calculator.class width = 300 height = 300>
</applet>
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com </body> </html>

The most important tag here is:


<applet code = Calculator.class width = 300 height = 300> </applet>

This is where we embed the .class file into the body of


the HTML page. The width and the height attributes
specify the width and the height of the applets canvas
area when it is displayed inside the HTML page.
RUNNING THE APPLET

Java provides a very useful utility tool called Applet


Viewer, which helps us to quickly view the output of
the applet without having to create a client server
network. After eh HTML page has been created,
execute the following command in the command
prompt to see the execution of the applet
appletviewer Calculator.html

A CHART TO REMEMBER THE POINTS


After seeing the first program, the main concern you
might be having is how to remember so many new
things, such as the name of different Listener
interfaces, methods, argument classes etc. The
following chart would provide a easy to remember
facility regarding this purpose.
Name of AWT Name of Listener class Interface
Button ActionListener Checkbox ItemListener
CheckboxGroup Do
Choice Do
Mouse MouseListener
MouseMotionListener
Name of Method
actionPerformed ( ) itemStateChanged ( )
Do
Do
mouseClicked ( ) mouseEntered ( ) mouseExited ( )

mousePressed ( ) mouseReleased ( ) mouseDragged ( )


mouseMoved ( )
Name of Argument Class ActionEvent
ItemEvent
Do
Do
MouseEvent
There are many other examples of Applet
programming available in your text book. Study as
many of them as you can.

You might also like