Vous êtes sur la page 1sur 85

MCS-024

Qst.1 (a)

What is Object Oriented Programming? Explain features of Object Oriented

Programming .
Ans: Object Oriented Programming : The world and its applications are not organized as functions and
values separate
from one another. The problem solvers do not think about the world in this manner.
They always deal with their problems by concentrating on the objects, their
characteristics and behavior.
The world is Object Oriented, and Object Oriented programming expresses programs
in the ways that model how people perceive the world. Figure 2 shows different real
world objects around us which we often use for performing different functions. This
shows that problem solving using the objects oriented approach is very close to our
real life problem solving techniques.

Figure 2: Real world objects

The basic difference in Object Oriented programming (OOP) is that the program is
organized around the data being operated upon rather than the operations performed.
The basic idea behind OOP is to combine both, data and its functions that operate on
the data into a single unit called object. Now in our next section, we will learn about

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 1

MCS-024
the basic concepts used extensively in the Object Oriented approach.
Object Oriented methods are favored because many experts agree that Object
Oriented techniques are more disciplined than conventional structured techniques.
(Martin and Odell 1992)
The main components of Object Oriented technology are objects and classes, data
abstraction and encapsulation, inheritance and polymorphism. It is very
important for you to understand these concepts. Further, in this unit you can find the
details of these concepts.

Features of Object Oriented Programming (OOP)

FEATURES OF OOP:
1.
2.
3.
4.
5.
6.
7.

Object
Class
Data Hiding and Encapsulation
Dynamic Binding
Message Passing
Inheritance
Polymorphism

Brief Explanation of Points:


OBJECT: Object is a collection of number of entities. Objects take up space in the memory. Objects are
instances of classes. When a program is executed , the objects interact by sending messages to one another.
Each object contain data and code to manipulate the data. Objects can interact without having know details of
each others data or code.
Lets start with Object. The first thing that we should do in the Object Oriented
approach is to start thinking in terms of Objects. The problem to be solved is divided
into objects. Start analyzing the problem in terms of objects and the nature of
communication between them. Program object should be chosen such that they match

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 2

MCS-024
closely with real-world objects. Lets start creating objects using real-life things, for
example, the dog. You can create an object representing a dog, It would have data
like How hungry is it? How happy is it? Where is it? Now think what are the
different functions you can perform on a dog, like eat, bark, run and dig. Similarly,
the following can be treated as objects in different programming problems:
Fig. 3: Dog object
and its behavior

! Employees in a payroll system


! Customers and accounts in a banking system
! Salesman, products, customers in a sales tracking system
! Data structures like linked lists, stacks, etc.
! Hardware devices like magnetic tape drive, keyboard, printer etc.
! GUI elements like windows, menus, events, etc. in any window-based
application.

CLASS: Class is a collection of objects of similar type. Objects are variables of the type class. Once a class has
been defined, we can create any number of objects belonging to that class. Eg: grapes bannans and orange are
the member of class fruit.
Objects of the similar type can be grouped together to form a class. Can you tell to
which class dog belongs? Yes, of course, it belongs to the animal class. Now, let us
concentrate on the creation of objects. This can be easily answered if we look at the
way of creating any variable in common programming languages. Almost all
computer languages have built-in data types, for example integer, character, real,
boolean, etc. One can declare as many variables of any built-in type as needed in any problem solution. In the similar way one
can define many objects of the same class.
You can take a class as a type created by a programmer.
A class serves as a plan or template. The programmer has to specify the entire set of
data and functions for various operations on the data for an object as a user-defined
type in the form of a class. In other words, the programmer defines the object
format and behavior by defining a class. The compiler of that language does not
know about this user-defined data type. The programmer has to define the data and
functionality associated with it by designing a class.
Finally, defining the class doesnt create an object just as the existence of a built-in

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 3

MCS-024
type integer doesnt create any variable. Once the class has been defined, you can
create any number of objects belonging to that class.
A class is thus a collection of objects of similar type. For example, in a collection of
potatoes each individual potato is an object and belongs to the class potato.
Similarly, each individual car running on the road is an object, Collectively these cars
are known as cars.

Example:
Fruit orange;
In the above statement object mango is created which belong to the class fruit.
NOTE: Classes are user define data types.
DATA ENCAPSULATION:
Combining data and functions into a single unit called class and the process is known as Encapsulation.Data
encapsulation is important feature of a class.
The wrapping up of data and functions into a single unit is known as encapsulation.
This is one of the strong features of the object oriented approach. The data is not
directly accessible to the outside world and only the functions, which are wrapped in
the class, can access it. Functions are accessible to the outside world. These
functions provide the interface to access data. If one wants to modify the data of an
object, s/he should know exactly what functions are available to interact with it. This
insulation of the data from direct access by the program is known as data hiding.

DATA ABSTRACTION: Class contains both data and functions. Data is not accessible from the outside world
and only those function which are present in the class can access the data. The insulation of the data from direct
access by the program is called data hiding or information hiding. Hiding the complexity of proram is called
Abstraction and only essential features are represented.In short we can say that internal working is hidden.
Abstraction refers to the act of representing essential features without including the
background details to distinguish objects/ functions from other objects/functions. In
case of structured programming, functional abstraction was provided by telling,
which task is performed by function and hiding how that task is performed. A step
further, in the Object Oriented approach, classes use the concept of data abstraction.
With data abstraction, data structures can be used without having to be concerned
about the exact details of implementation. As in case of built-in data types like
integer, floating point, etc. The programmer only knows about the various operations
which can be performed on these data types, but how these operations are carried out
by the hardware or software is hidden from the programmer. Similarly in Object
Oriented approach, classes act as abstract data types. Classes are defined as a set of
attributes and functions to operate on these attributes. They encapsulate all the
essential properties of the objects that are to be created.

DYNAMIC BINDING: Refers to linking of function call with function defination is called binding and when it
is take place at run time called dynamic binding.
MESSAGE PASSING: The process by which one object can interact with other object is called message
passing.
For example, in the banking system, customer object may send a message
named as check balance to the account object to get the response, i.e. bank balance.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 4

MCS-024
An Object Oriented system can be considered as network of cooperating objects
which interact by sending messages to each other. Lets see in the Figure 4, how
objects interact by sending messages to one another.

INHERITANCE: it is the process by which object of one class aquire the properties or features of objects of
another class. The concept of inheritance provide the idea of reusability means we can add additional features to
an existing class without Modifying it. This is possible by driving a new class from the existing one. The new
class
will
have
the
combined
features
of
both
the
classes.
Inheritance is the process by which objects of one class acquire the properties of
objects of another class in the hierarchy. For example, the scooter is a type of the
class two-wheelers, which is again a type of (or kind of) the class motor vehicles. As
shown in the Figure 5 the principle behind it is that the derived class shares common
characteristics with the class from which it is derived.
New classes can be built from the existing classes. It means that we can add
additional features to an existing class without modifying it. The new class is referred
as derived class or sub class and the original class is known as base class or super
class. Therefore, the concept of inheritance provides the idea of reusability. This
inheritance mechanism allows the programmer to reuse a class that is made almost,
but not exactly, similar to the required one by adding a few more features to it.
As shown in Figure 5, three classes have been derived from one base class. Feature A
and Feature B of the base class are inherited in all the three derived classes. Also,
each derived class has added its own features according to the requirement.
Therefore, new classes use the concept of reusability and extend their functionality.

Example: Robine is a part of the class flying bird which is again a part of the class bird.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 5

MCS-024

POLYMORPHISM: A greek term means ability to take more than one form. An operation may exhibite
different behaviours in different instances. The behaviour depends upon the types of data used in the operation.
Polymorphism means the ability to take more than one form of the same
property. For example, consider an addition operation. It shows a different behavior
in different types of data. For two numbers, it will generate a sum. The numbers may
integers or float. Thus the addition for integers is different from the addition to
floats.
An example is shown in Figure 6, where single function name, i.e. draw can be used
to draw different shapes. The name is the same in all the classes but the functionality
differs. This is known as function overriding, which is a type of polymorphism. We
will discuss it in detail in our next unit.
In our example, we also used a function area which was inherited by all the three
derived classes, i.e. triangle, circle and rectangle. But in the cases of the circle and
the triangle, we override the function area because the data types and number of
parameters varies.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 6

MCS-024

Qst.1 (b) What is platform independence? Explain why java is platform independent.
Ans:
latform independence: Java was developed by SUN Microsystems in 1991 under
the guidance of James Gosling. Its an Object Oriented, general-purpose programming
language. After its birth it became popular because of many reasons like security,
robustness and multithreadedness but mainly because of its characteristic of
Architecture Neutral and platform independent. The logic and magic behind its
platform independence is BYTECODE. Java offers two flavors of programming,
Java application and Java applet. Application can be executed independently while
applet cannot be executed independently. When we compile a Java program we get
Java bytecode (.class file) that can be executed on any other computer system,
equipped with Java interpreter. To execute applets you can use applet viewer or
explorer to run Java embedded HTML code.
You learnt the meaning of different Java keywords which have special meaning for
compiler and cannot be used as a user defined identifier. Java supports eight primitive
data types which can be classified into four categories. Each data type has its memory
size and range of values it can store. Before using the Java variables in your program
you should declare them and assign them some value. You learnt how to declare a
variable dynamically with the help of an example. You have learnt different types of
operators in the last section of this unit which are similar to C++ so you must be
familiar with some of them. You must be tired after reading a long unit so now you
can go and have a cup of coffee. In the next unit we will discuss about the classes and
objects in Java.

Platform independence is a term that describes a technology (usually a ProgrammingLanguage or a FrameWork)


that you can use to implement things on one machine and use them on another machine without (or with minimal)
changes. Java is Platform independent. The meaning of platform here may be confusing for
you but actually this word is poorly defined. In the computer industry it typically
means some combination of hardware and system software but here you can
understand it as your operating system.
Java is compiled to an intermediate form called Java byte-code or simply byte code.
A Java program never really executes immediately after compilation on the host
machine. Rather, this special program called the Java interpreter or Java Virtual
Machine reads the byte code, translates it into the corresponding host machine

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 7

MCS-024
instructions and then executes the machine instruction. A Java program can run on
any computer system for which a JVM (Java Virtual Machine) and some library
routines have been installed. The second important part which makes Java portable is
the elimination of hardware architecture dependent constructs. For example, Integers
are always four bytes long and floating-point variables follow the IEEE 754.You dont
need to worry that the interpretation of your integer is going to change if you move
from one hardware to another hardware like Pentium to a PowerPC. You can develop
the Java program on any computer system and the execution of that program is
possible on any other computer system loaded with JVM. For example, you can write
and compile the Java program on Windows 98 and execute the compiled program on
JVM of the Macintosh operating system. The same concept is explained in Figure 1
given below.

So, the byte code is platform independent but the interpreted code is machine-specific and will execute on the
environment the JVM is installed on. JAVA programs are platform-independant means that JAVA is platform
independant. Sun MicroSystems slogan was WORA: Write Once Run Anywhere.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 8

MCS-024

Qst.1 (b) Write a program to explain how array of objects may be created in java.

Ans:

Array of Objects

As we have already said, arrays are capable of storing objects also. For example, we can create an array of Strings which
is a reference type variable. However, using a String as a reference type to illustrate the concept of array of objects isn't
too appropriate due to the immutability of String objects. Therefore, for this purpose, we will use a class Student
containing a single instance variable marks. Following is the definition of this class.
class Student {
int marks;
}
An array of objects is created just like an array of primitive type data items in the following way.
Student[] studentArray = new Student[7];
The above statement creates the array which can hold references to seven Student objects. It doesn't create the Student
objects themselves. They have to be created separately using the constructor of the Student class. The studentArray
contains seven memory spaces in which the address of seven Student objects may be stored. If we try to access the
Student objects even before creating them, run time errors would occur. For instance, the following statement throws a
NullPointerException during runtime which indicates that studentArray[0] isn't yet pointing to a Student object.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 9

MCS-024
studentArray[0].marks = 100;
The Student objects have to be instantiated using the constructor of the Student class and their references should be
assigned to the array elements in the following way.
studentArray[0] = new Student();
In this way, we create the other Student objects also. If each of the Student objects have to be created using a different
constructor, we use a statement similar to the above several times. However, in this particular case, we may use a for
loop since all Student objects are created with the same default constructor.
for ( int i=0; i<studentArray.length; i++) {
studentArray[i]=new Student();
}
The above for loop creates seven Student objects and assigns their reference to the array elements. Now, a statement
like the following would be valid.
studentArray[0].marks=100;
Enhanced for loops find a better application here as we not only get the Student object but also we are capable of
modifying it. This is because of the fact that Student is a reference type. Therefore the variable in the header of the
enhanced for loop would be storing a reference to the Student object and not a copy of the Student object which was
the case when primitive type variables like int were used as array elements.
for ( Student x : studentArray ) {
x.marks = s.nextInt(); // s is a Scanner object
}
Recall that we were not able to assign to the array elements in a similar way when the array was of type int.
Moreover, in the case of array of objects, when we pass an array element to a method, the object is susceptible to
changes. This is because the element being passed is also a reference type item. This differs from the situation when we
have an int array. Following illustrates this concept.
public static void main(String[] args) {
Student[] studentArray = new Student[7];
studentArray[0] = new Student();
studentArray[0].marks = 99;
System.out.println(studentArray[0].marks); // prints 99
modify(studentArray[0]);
System.out.println(studentArray[0].marks); // prints 100 and not 99

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 10

MCS-024
// code
}
public static void modify(Student s) {
s.marks = 100;
}
Compare the output with the one when the array was of type int[].
Processing an array of objects is much similar to the processing of an array of primitive type. the only thing to be kept in
mind is the possibility of NullPointerException being thrown during run time and also remembering that the array
elements themselves are reference types, which brings subtle differences from the case when they are passed as
parameters. Moreover, an enhanced for loop may be used to initialise the array elements.
Pograam Is :

public

class

public

static

//

Weekend

void

Set

up

Film

main(String

Watch[0]

Watch[2]

=
=

Film
int

null,

longtime

0,

Shortest

null;

shorttime

0;

i=0;

//
//

shorttime

Cats

and

To
To

avoid
avoid

grumpy

compiler

grumpy

compiler

i++)

Longest
=

longtime

Watch[i].getminutes();

==
=

Dogs",93);

Film("Enigma",114);

(i
Shortest

Perdition",117);

i<Watch.length;

mins

if

to

new

(int
int

Film[4];
Film("Shrek",133);

about

Longest

for

Truth

objects

new

Film("Road

Film("The

Watch[3]

film

new
new

new

args)

of

=
=

Watch[1]

[]

series

Watch[]

0)
=

{
Watch[i];

mins;

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 11

MCS-024
}

else
if

(mins

<

shorttime)

shorttime=mins;
Shortest

Watch[i];

}
if

(mins

>

longtime)

longtime=mins;
Longest

Watch[i];

}
}
}
System.out.println("Longest

film

is

"

Longest.getcalled()
"

+
at

System.out.println("Shortest

"+longtime+"
film

is

minutes");
"

Shortest.getcalled()
"

+
+

at

"+shorttime+"

minutes");

}
}

Qst.2

(a)

Ans: Java programming language is a statically typed language. It means that every variable and every
expression has a type that is known at compile time. Java language is also a strongly typed language, because
types limit the values that a variable can hold or that an expression can produce, limit the operations supported
on those values, and determine the meaning of the operations. Strong static typing helps detect errors at compile
time. Variables in dynamically typed languages like Ruby or Python can receive different data types over the
time. In Java, once a variable is declared to be of a certain data type, it cannot hold values of other data types.
There are two fundamental data types in Java: primitive types and reference types. Primitive types are:

boolean
char
byte
short

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 12

MCS-024
int
long
float
double

To Represent use of Boolean Variable


package com.zetcode;
import java.util.Random;
public class BooleanType {
public static void main(String[] args) {
String name = "";
Random r = new Random();
boolean male = r.nextBoolean();
if (male == true) {
name = "Robert";
}
if (male == false) {
name = "Victoria";
}
System.out.format("We will use name %s%n", name);
System.out.println(9 > 8);
}
}

Qst.2 (b) Explain followings in context of java, with the help of examples.
Ans:
(i) Class and objects : OBJECT: Object is a collection of number of entities. Objects take up space in the
memory. Objects are instances of classes. When a program is executed , the objects interact by sending
messages to one another. Each object contain data and code to manipulate the data. Objects can interact without
having know details of each others data or code.
Lets start with Object. The first thing that we should do in the Object Oriented
approach is to start thinking in terms of Objects. The problem to be solved is divided
into objects. Start analyzing the problem in terms of objects and the nature of
communication between them. Program object should be chosen such that they match
closely with real-world objects. Lets start creating objects using real-life things, for
example, the dog. You can create an object representing a dog, It would have data
like How hungry is it? How happy is it? Where is it? Now think what are the
different functions you can perform on a dog, like eat, bark, run and dig. Similarly,
the following can be treated as objects in different programming problems:
Fig. 3: Dog object

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 13

MCS-024
and its behavior

! Employees in a payroll system


! Customers and accounts in a banking system
! Salesman, products, customers in a sales tracking system
! Data structures like linked lists, stacks, etc.
! Hardware devices like magnetic tape drive, keyboard, printer etc.
! GUI elements like windows, menus, events, etc. in any window-based
application.

CLASS: Class is a collection of objects of similar type. Objects are variables of the type class. Once a class has
been defined, we can create any number of objects belonging to that class. Eg: grapes bannans and orange are
the member of class fruit.
Objects of the similar type can be grouped together to form a class. Can you tell to
which class dog belongs? Yes, of course, it belongs to the animal class. Now, let us
concentrate on the creation of objects. This can be easily answered if we look at the
way of creating any variable in common programming languages. Almost all
computer languages have built-in data types, for example integer, character, real,
boolean, etc. One can declare as many variables of any built-in type as needed in any problem solution. In the similar way one
can define many objects of the same class.
You can take a class as a type created by a programmer.
A class serves as a plan or template. The programmer has to specify the entire set of
data and functions for various operations on the data for an object as a user-defined
type in the form of a class. In other words, the programmer defines the object
format and behavior by defining a class. The compiler of that language does not
know about this user-defined data type. The programmer has to define the data and
functionality associated with it by designing a class.
Finally, defining the class doesnt create an object just as the existence of a built-in
type integer doesnt create any variable. Once the class has been defined, you can
create any number of objects belonging to that class.
A class is thus a collection of objects of similar type. For example, in a collection of
potatoes each individual potato is an object and belongs to the class potato.
Similarly, each individual car running on the road is an object, Collectively these cars
are known as cars.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 14

MCS-024
Example:
Fruit orange;
In the above statement object mango is created which belong to the class fruit.
NOTE: Classes are user define data types.
(ii) Abstraction and encapsulation : Data abstraction and encapsulation
The wrapping up of data and functions into a single unit is known as encapsulation.
This is one of the strong features of the object oriented approach. The data is not
directly accessible to the outside world and only the functions, which are wrapped in
the class, can access it. Functions are accessible to the outside world. These
functions provide the interface to access data. If one wants to modify the data of an
object, s/he should know exactly what functions are available to interact with it. This
insulation of the data from direct access by the program is known as data hiding.
Abstraction refers to the act of representing essential features without including the
background details to distinguish objects/ functions from other objects/functions. In
case of structured programming, functional abstraction was provided by telling,
which task is performed by function and hiding how that task is performed. A step
further, in the Object Oriented approach, classes use the concept of data abstraction.
With data abstraction, data structures can be used without having to be concerned
about the exact details of implementation. As in case of built-in data types like
integer, floating point, etc. The programmer only knows about the various operations
which can be performed on these data types, but how these operations are carried out
by the hardware or software is hidden from the programmer. Similarly in Object
Oriented approach, classes act as abstract data types. Classes are defined as a set of
attributes and functions to operate on these attributes. They encapsulate all the
essential properties of the objects that are to be created.

(iii) Application program and applet program : All Java programs can be classified as Applications and
Applets. The striking differences are that applications contain main() method where as applets do not. One
more is, applications can be executed at DOS prompt and applets in a browser. We can say, an applet is an
Internet application. Come on, read further.

Definition Importance
Applet is a Java program executed by a browser. The position of applets in software world is they occupy the
client-side position in Web communication. On the server-side, you guess, another Java program comes,
Servlets. Applets on client-side and servlets on server-side makes Java a truly "Internet-based language". To
execute applets, the browsers come with JRE (Java Runtime Environment). The browsers with Java Runtime
Environment (or to say, JVM) loaded are known as Java enabled browsers.
Note: Browser do not have a Java compiler as a compiled applet file (.class file) is given to browser to execute.
Applications Vs. Applets
You have seen two main differences between applications and applets. Let us summarize them.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 15

MCS-024
Feature

Application

Applet

main()
method

Present

Not present

Execution

Requires JRE

Requires a browser like Chrome

Nature

Called as stand-alone application as application can be Requires some third party tool help like a
executed from command prompt
browser to execute

Restrictions

Can access any data or software available on the system

cannot access any thing on the system


except browsers services

Security

Does not require any security

Requires highest security for the system as


they are untrusted

Advantages of Applets
1. Execution of applets is easy in a Web browser and does not require any installation or deployment procedure in
realtime programming (where as servlets require).
2. Writing and displaying (just opening in a browser) graphics and animations is easier than applications.
3. In GUI development, constructor, size of frame, window closing code etc. are not required (but are required in
applications).

Restrictions of Applets
1. Applets are required separate compilation before opening in a browser.
2. In realtime environment, the bytecode of applet is to be downloaded from the server to the client machine.
3. Applets are treated as untrusted (as they were developed by unknown people and placed on unknown servers
whose trustworthiness is not guaranteed) and for this reason they are not allowed, as a security measure, to
access any system resources like file system etc. available on the client system.
4. Extra Code is required to communicate between applets using AppletContext.

What Applet can't do Security Limitations


Applets are treated as untrusted because they are developed by somebody and placed on some unknown Web
server. When downloaded, they may harm the system resources or steal passwords and valuable information
available on the system. As applets are untrusted, the browsers come with many security restrictions. Security
policies are browser dependent. Browser does not allow the applet to access any of the system resources (applet
is permitted to use browser resources, infact, applet execution goes within the browser only).

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 16

MCS-024

Applets are not permitted to use any system resources like file system as they are untrusted and can inject virus
into the system.
Applets cannot read from or write to hard disk files.
Applet methods cannot be native.
Applets should not attempt to create socket connections
Applets cannot read system properties
Applets cannot use any software available on the system (except browser execution area)
Cannot create objects of applications available on the system by composition

The JRE throws SecurityException if the applet violates the browser restrictions.
Applet Architecture
Applets permit GUI and handling events. Infact, an applet will be in waiting mode forever expecting some
event (input) to occur from the user. Applets are event driven and window-based. The event is forwarded by
the AWT GUI environment (graphics environment) to the applet. The applet takes the event, do some action
and return the control back to AWT. Applet does not keep the execution control with it for a long time. If the
programmer would like to listen the music continuously or use some banner to display, he must create a
separated thread and assign the job to it.
Note: Do not try to take input from keyboard with applets as applets are window-based and instead you can
create some GUI text field and take input.
Qst3. (a) What is static variable and static method? Explain why main method in java is always static.
Ans:

1) Java static variable

If you declare any variable as static, it is known static variable.

The static variable can be used to refer the common property of all objects (that is not unique for each object)
e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable


1. class Student{
2.
int rollno;
3.
String name;
4.
String college="ITS";
5. }

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 17

MCS-024
Suppose there are 500 students in my college, now all instance data members will get memory each time when
object is created.All student have its unique rollno and name so instance data member is good.Here, college
refers to the common property of all objects.If we make it static,this field will get memory only once.

Java static property is shared to all objects.


Example of static variable
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.

//Program of static variable


class Student8{
int rollno;
String name;
static String college ="ITS";
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}
}

Test it Now
Output:111 Karan ITS
222 Aryan ITS

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 18

MCS-024

Program of counter without static variable

In this example, we have created an instance variable named count which is incremented in the constructor.
Since instance variable gets the memory at the time of object creation, each object will have the copy of the
instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in
the count variable.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 19

MCS-024
12.
13.
14.
15.
16.

Counter c2=new Counter();


Counter c3=new Counter();
}
}

Test it Now
Output:1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static
variable, it will retain its value.

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}

Test it Now
Output:1
2
3

2) Java static method


If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than object of a class.


A static method can be invoked without the need for creating an instance of a class.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 20

MCS-024

static method can access static data member and can change the value of it.

Example of static method


1. //Program of changing the common property of all objects(static field).
2.
3. class Student9{
4.
int rollno;
5.
String name;
6.
static String college = "ITS";
7.
8.
static void change(){
9.
college = "BBDIT";
10. }
11.
12. Student9(int r, String n){
13. rollno = r;
14. name = n;
15. }
16.
17. void display (){System.out.println(rollno+" "+name+" "+college);}
18.
19. public static void main(String args[]){
20. Student9.change();
21.
22. Student9 s1 = new Student9 (111,"Karan");
23. Student9 s2 = new Student9 (222,"Aryan");
24. Student9 s3 = new Student9 (333,"Sonoo");
25.
26. s1.display();
27. s2.display();
28. s3.display();
29. }
30. }
Test it Now
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Another example of static method that performs normal calculation


1. //Program to get cube of a given number by static method
2.
3. class Calculate{

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 21

MCS-024
4.
5.
6.
7.
8.
9.
10.
11.
12.

static int cube(int x){


return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}

Test it Now
Output:125

Restrictions for static method


There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.

1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Test it Now
Output:Compile Time Error
Main method in Java is entry point for any core Java program. Remember we are not talking about Servlet, MIDlet or
any other container managed Java program where life cycle methods are provided to control the execution. In core
Java program, execution starts from main method when you type java main-class-name, JVM search for public static
void main(String args[]) method in that class and if it doesn't find that method it throws error
NoSuchMethodError:main and terminates.

Signature of main method in Java

Main method has to strictly follow its syntax; other wise JVM will not be able to locate it and your program will not
run. Here is the exact signature of main method

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 22

MCS-024

public static void main(String args[])

This signature is classic signature and there from start of Java but with introduction of variable argument or varargs
in Java5 you can also declare main method in Java using varargs syntax as shown in below example:

public static void main(String... args)

Remember varargs version of java main method will only work in Java 1.5 or later version. Apart from public, static
and void there are certain keywords like final, synchronized and strictfp which are permitted in signature of java main
method.
(b)
What is inheritance? Explain the advantage of inheritance with an example program. What are
different types of inheritance supported by java?

Qst.3

Ans: Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When
you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new
methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java

For Method Overriding (so runtime polymorphism can be achieved).


For Code Reusability.

Syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3.
//methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 23

MCS-024
Advantages:One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by
sharing common code amongst several subclasses. Where equivalent code exists in two related
classes, the hierarchy can usually be refactored to move the common code up to a mutual
superclass. This also tends to result in a better organization of code and smaller, simpler compilation
units.
Inheritance can also make application code more flexible to change because classes that inherit from
a common superclass can be used interchangeably. If the return type of a method is superclass
Reusability -- facility to use public methods of base class without rewriting the same
Extensibility -- extending the base class logic as per business logic of the derived class
Data hiding -- base class can decide to keep some data private so that it cannot be altered by the
derived
class
Overriding--With inheritance, we will be able to override the methods of the base class so that
meaningful implementation of the base class method can be designed in the derived class.
Disadvantages:1.One of the main disadvantages of inheritance in Java (the same in other object-oriented languages)
is the increased time/effort it takes the program to jump through all the levels of overloaded classes.
If a given class has ten levels of abstraction above it, then it will essentially take ten jumps to run
through
a
function
defined
in
each
of
those
classes
2.Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly
coupled.
This
means
one
cannot
be
used
independent
of
each
other.
3. Also with time, during maintenance adding new features both base as well as derived classes are
required to be changed. If a method signature is changed then we will be affected in both cases
(inheritance
&
composition)
4. If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case of
using that method.Here things can get a bit complicated in case of inheritance because our programs
will still compile, but the methods of the subclass will no longer be overriding superclass methods.
These methods will become independent methods in their own right.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 24

MCS-024
Understanding the simple example of inheritance

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship
between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e.
code reusability.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 25

MCS-024
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about
interfaces later.

Note: Multiple inheritance is not supported in java through class.


When a class extends multiple classes i.e. known as multiple inheritance. For Example:

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 26

MCS-024

1) Single Inheritance

Single inheritance is damn easy to understand. When a class extends another one class only then we call it a
single inheritance. The below flow diagram shows that class B extends only one class which is A. Here A is a
parent class of B and B would be a child class of A.

Single Inheritance example program in Java


Class A
{
public void methodA()

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 27

MCS-024
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

2) Multiple Inheritance

Multiple Inheritance refers to the concept of one class extending (Or inherits) more than one base class. The
inheritance we learnt earlier had the concept of one base class or parent. The problem with multiple
inheritance is that the derived class will have to manage the dependency on two base classes.

Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance often leads to
problems in the hierarchy. This results in unwanted complexity when further extending the class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple inheritance.
Multiple Inheritance is supported in C++.
3) Multilevel Inheritance

Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived class,
thereby making this derived class the base class for the new class. As you can see in below flow diagram C is
subclass or child class of B and B is a child class of A. For more details and example refer Multilevel
inheritance in Java.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 28

MCS-024

Multilevel Inheritance example program in Java


Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}

4) Hierarchical Inheritance

In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and D
inherits the same class A. A is parent class (or base class) of B,C & D. Read More at Hierarchical
Inheritance in java with example program.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 29

MCS-024

5) Hybrid Inheritance

In simple terms you can say that Hybrid inheritance is a combination of Single and Multiple inheritance. A
typical flow diagram would look like below. A hybrid inheritance can be achieved in the java in a same way as
multiple inheritance can be!! Using interfaces. yes you heard it right. By using interfaces you can have multiple
as well as hybrid inheritance in Java.
Read the full article here hybrid inheritance in java with example program.

Qst.3 (c) Explain the steps involved in creating a distributed application using Remote Method Invocation
(RMI).
Ans: The Java Remote Method Invocation (RMI) mechanism and the Common Object Request Broker
Architecture (CORBA) are the two most important and widely used distributed object systems. Each system has
its own features and shortcomings. Both are being used in the industry for various applications ranging from ecommerce to health care. Selecting which of these two distribution mechanisms to use for a project is a tough
task. This article presents an overview of RMI and CORBA, and more importantly it shows how to develop a
useful application for downloading files from remote hosts. It then:

Presents a brief overview of distributed object systems

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 30

MCS-024

Provides a brief overview of RMI and CORBA


Gives you a flavor of the effort involved in developing applications in RMI and CORBA
Shows how to transfer files from remote machines using RMI and CORBA
Provides a brief comparison of RMI and CORBA

The Client/Server Model

The client/server model is a form of distributed computing in which one program (the client) communicates
with another program (the server) for the purpose of exchanging information. In this model, both the client and
server usually speak the same language -- a protocol that both the client and server understand -- so they are
able to communicate.
While the client/server model can be implemented in various ways, it is typically done using low-level sockets.
Using sockets to develop client/server systems means that we must design a protocol, which is a set of
commands agreed upon by the client and server through which they will be able to communicate. As an
example, consider the HTTP protocol that provides a method called GET, which must be implemented by all
web servers and used by web clients (browsers) in order to retrieve documents.
The Distributed Objects Model

A distributed object-based system is a collection of objects that isolates the requesters of services (clients) from
the providers of services (servers) by a well-defined encapsulating interface. In other words, clients are isolated
from the implementation of services as data representations and executable code. This is one of the main
differences that distinguishes the distributed object-based model from the pure client/server model.
In the distributed object-based model, a client sends a message to an object, which in turns interprets the
message to decide what service to perform. This service, or method, selection could be performed by either the
object or a broker. The Java Remote Method Invocation (RMI) and the Common Object Request Broker
Architecture (CORBA) are examples of this model.
RMI

RMI is a distributed object system that enables you to easily develop distributed Java applications. Developing
distributed applications in RMI is simpler than developing with sockets since there is no need to design a
protocol, which is an error-prone task. In RMI, the developer has the illusion of calling a local method from a
local class file, when in fact the arguments are shipped to the remote target and interpreted, and the results are
sent back to the callers.

The Genesis of an RMI Application


Developing a distributed application using RMI involves the following steps:
1. Define a remote interface
2. Implement the remote interface

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 31

MCS-024
3. Develop the server
4. Develop a client
5. Generate Stubs and Skeletons, start the RMI registry, server, and client

We will now examine these steps through the development of a file transfer application.

Example: File Transfer Application


This application allows a client to transfer (or download) any type of file (plain text or binary) from a remote
machine. The first step is to define a remote interface that specifies the signatures of the methods to be provided
by the server and invoked by clients.
Define a remote interface
The remote interface for the file download application is shown in Code Sample 1. The interface
FileInterface provides one method downloadFile that takes a String argument (the name of the file) and
returns the data of the file as an array of bytes.
Code Sample 1: FileInterface.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface FileInterface extends Remote {
public byte[] downloadFile(String fileName) throws
RemoteException;
}

Note the following characteristics about the FileInterface:

It must be declared public, in order for clients to be able to load remote objects which implement the remote
interface.
It must extend the Remote interface, to fulfill the requirement for making the object a remote one.
Each method in the interface must throw a java.rmi.RemoteException.

Implement the remote interface


The next step is to implement the interface FileInterface. A sample implementation is shown in Code
Sample 2. Note that in addition to implementing the FileInterface, the FileImpl class is extending the
UnicastRemoteObject. This indicates that the FileImpl class is used to create a single, non-replicated, remote
object that uses RMI's default TCP-based transport for communication.
Code Sample 2: FileImpl.java

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 32

MCS-024
import java.io.*;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class FileImpl extends UnicastRemoteObject
implements FileInterface {
private String name;
public FileImpl(String s) throws RemoteException{
super();
name = s;
}
public byte[] downloadFile(String fileName){
try {
File file = new File(fileName);
byte buffer[] = new byte[(int)file.length()];
BufferedInputStream input = new
BufferedInputStream(new FileInputStream(fileName));
input.read(buffer,0,buffer.length);
input.close();
return(buffer);
} catch(Exception e){
System.out.println("FileImpl: "+e.getMessage());
e.printStackTrace();
return(null);
}
}
}

Develop the server


The third step is to develop a server. There are three things that the server needs to do:
1. Create an instance of the RMISecurityManager and install it
2. Create an instance of the remote object ( FileImpl in this case)
3. Register the object created with the RMI registry. A sample implementation is shown in Code Sample 3.

Code Sample 3: FileServer.java


import java.io.*;
import java.rmi.*;
public class FileServer {
public static void main(String argv[]) {
if(System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 33

MCS-024
}
try {
FileInterface fi = new FileImpl("FileServer");
Naming.rebind("//127.0.0.1/FileServer", fi);
} catch(Exception e) {
System.out.println("FileServer: "+e.getMessage());
e.printStackTrace();
}
}
}

The statement Naming.rebind("//127.0.0.1/FileServer", fi) assumes that the RMI registry is running
on the default port number, which is 1099. However, if you run the RMI registry on a different port number it
must be specified in that statement. For example, if the RMI registry is running on port 4500, then the statement
becomes:
Naming.rebind("//127.0.0.1:4500/FileServer", fi)

Also, it is important to note here that we assume the rmi registry and the server will be running on the same
machine. If they are not, then simply change the address in the rebind method.
Develop a client
The next step is to develop a client. The client remotely invokes any methods specified in the remote interface (
FileInterface). To do so however, the client must first obtain a reference to the remote object from the RMI
registry. Once a reference is obtained, the downloadFile method is invoked. A client implementation is shown
in Code Sample 4. In this implementation, the client accepts two arguments at the command line: the first one is
the name of the file to be downloaded and the second one is the address of the machine from which the file is to
be downloaded, which is the machine that is running the file server.
Code Sample 4: FileClient.java
import java.io.*;
import java.rmi.*;
public class FileClient{
public static void main(String argv[]) {
if(argv.length != 2) {
System.out.println("Usage: java FileClient fileName machineName");
System.exit(0);
}
try {
String name = "//" + argv[1] + "/FileServer";
FileInterface fi = (FileInterface) Naming.lookup(name);
byte[] filedata = fi.downloadFile(argv[0]);
File file = new File(argv[0]);

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 34

MCS-024
BufferedOutputStream output = new
BufferedOutputStream(new FileOutputStream(file.getName()));
output.write(filedata,0,filedata.length);
output.flush();
output.close();
} catch(Exception e) {
System.err.println("FileServer exception: "+ e.getMessage());
e.printStackTrace();
}
}
}

Qst.4 (a)
What is polymorphism? Is Interfaces in Java, a kind of polymorphism? Justify your answer with the
help of an example.
Ans: Polymorphism is the capability of a method to do different things based on the object
through which it is invoked or object it is acting upon. For example method
find _area will work definitely for Circle object and Triangle object In Java, the type
of actual object always determines method calls; object reference type doesnt play
any role in it. You have already used two types of polymorphism (overloading and
overriding) in the previous unit and in the current unit of this block. Now we will look
at the third: dynamic method binding. Java uses Dynamic Method Dispatch
mechanism to decide at run time which overridden function will be invoked. Dynamic
Method Dispatch mechanism is important because it is used to implement runtime
polymorphism in Java. Java uses the principle: a super class object can refer to a
subclass object to resolve calls to overridden methods at run time.
If a superclass has method that is overridden by its subclasses, then the different
versions of the overridden methods are invoked or executed with the help of a
superclass reference variable.
Assume that three subclasses (Cricket_Player Hockey_Player and Football_Player)
that derive from Player abstract class are defined with each subclass having its own
Play() method.
abstract class Player // class is abstract
{
private String name;
public Player(String nm)
{
name=nm;
}
public String getName() // regular method
{
return (name);
}
public abstract void Play();
// abstract method: no implementation
}
class Cricket_Player extends Player
{

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 35

MCS-024
Cricket_Player( String var)
{
}
public void Play()
{
System.out.println("Play Cricket:"+getName());
}
}
class Hockey_Player extends Player
{
Hockey_Player( String var)
{
}
public void Play()
{
System.out.println("Play Hockey:"+getName());
}
}
class Football_Player extends Player
{
Football_Player( String var)
{
}
public void Play()
{
System.out.println("Play Football:"+getName());
}
}
public class PolyDemo
{
public static void main(String[] args)
{
Player ref; // set up var for an Playerl
Cricket_Player aCplayer = new Cricket_Player("Sachin"); // makes specific objects
Hockey_Player aHplayer = new Hockey_Player("Dhanaraj");
Football_Player aFplayer = new Football_Player("Bhutia");
// now reference each as an Animal
ref = aCplayer;
ref.Play();
ref = aHplayer;
ref.Play();
ref = aFplayer;
ref.Play();
}
}
Output:
Play Cricket:Sachin
Play Hockey:Dhanaraj
Play Football:Bhutia
Notice that although each method is invoked through ref, which is a reference to

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 36

MCS-024
player class (but no player objects exist), the program is able to resolve the correct method related to the subclass object at
runtime. This is known as dynamic (or late)
method binding.

Interfaces
As illustrated in the previous chapter, one of the most important benefits of class extension is that you can take
advantage of polymorphism. In an inheritance hierarchy, if class CoffeeCup extends class Cup, you can treat a
CoffeeCup object as if it were a Cup object. Sometimes, however, it is difficult to get the polymorphism you
want from the singly-inherited hierarchies you can build with class extension. To help you get more
polymorphism than you can easily get with single- inheritance, Java supports a restricted form of multiple
inheritance through a construct called the "interface." This chapter will discuss the motivation and the
mechanics of the Java interface.

The Limitations of Single Inheritance


To reap the benefits of polymorphism through class extension, you must build a family of classes. In Java
terminology, both classes and interfaces are "types." When you declare an interface, as when you declare a
class, you establish a new type. In the remainder of this book, "type" will be used to refer to either classes or
interfaces. Here, a "family of classes" is simply a family of types in which all the types are classes (none are
interfaces). Thus, a family of classes is a group of related classes with a single base class from which all other
classes in the family descend. Since every class in Java descends from Object, all Java classes are members of
the Object family; however, you can still look at individual areas of an inheritance hierarchy as individual
"families of classes." For example, class Cup and all its subclasses, as shown in Figure 4-1, form the Cup family.
[bv: I believe I covered this already in a previous chapter.]

Figure 4-1. The Cup family

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 37

MCS-024
Given a family of classes, polymorphism allows you to treat a subclass object as if it were a superclass object.
For example, imagine you wanted to create a single method that could wash any kind of cup in your virtual
cafe. You could declare a public method named wash() in the base class of the Cup family:
// In Source Packet in file interface/ex1/Cup.java
class Cup {
public void wash() {
System.out.println("Washing a Cup.");
// ...
}
//...
}
// In Source Packet in file interface/ex1/CoffeeCup.java
class CoffeeCup extends Cup {
public void wash() {
System.out.println("Washing a CoffeeCup.");
// ...
}
//...
}
// In Source Packet in file interface/ex1/CoffeeMug.java
class CoffeeMug extends CoffeeCup {
public void wash() {
System.out.println("Washing a CoffeeMug.");
// ...
}
//...
}
// In Source Packet in file interface/ex1/EspressoCup.java
class EspressoCup extends CoffeeCup {
public void wash() {
System.out.println("Washing an EspressoCup.");
// ...
}
//...
}

Given this family of types, you could define a method that takes a Cup reference as follows:
// In Source Packet in file interface/ex1/VirtualCafe.java
class VirtualCafe {
public static void prepareACup(Cup cup) {
//...
cup.wash();
//...
}
//...
}

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 38

MCS-024
Using polymorphism, you could pass to the method a reference to any object that is-a Cup:
// In Source Packet in file interface/ex1/Example1.java
class Example1 {
public static void main(String[] args) {
Cup c = new Cup();
CoffeeCup cc = new CoffeeCup();
CoffeeMug cm = new CoffeeMug();
EspressoCup ec = new EspressoCup();
VirtualCafe.prepareACup(c);
VirtualCafe.prepareACup(cc);
VirtualCafe.prepareACup(cm);
VirtualCafe.prepareACup(ec);
}
}

Here you have all the benefits of polymorphism. The prepareACup() method can invoke wash() on many
different objects, but it doesn't need to use instanceof. As a consequence, the code is easier to read and
change. If later, you wanted to add class TeaCup to your program and wash TeaCup objects with
prepareACup(), you only need to make TeaCup a subclass of Cup. You don't need to change the
prepareACup() method itself.
Qst.4 (b) Explain the need of package in Java. Write a java program to show how package is created.
Ans Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub packages. Many
implementations of Java use a hierarchical file system to manage source and class files. It is easy to organize
class files into packages. All we need to do is put related class files in the same directory, give the directory a
name that relates to the purpose of the classes, and add a line to the top of each class file that declares the
package name, which is the same as the directory name where they reside.
In java there are already many predefined packages that we use while programming.
For
example:
java.lang, java.io, java.util
However one of the most useful feature of java is that we can define our own packages

etc.

Advantages of using a package


Before discussing how to use them Let see why we should use packages.

Reusability: Reusability of code is one of the most important requirements in the software industry.
Reusability saves time, effort and also ensures consistency. A class once developed can be reused by any
number of programs wishing to incorporate the class in that particular program.
Easy to locate the files.
In real life situation there may arise scenarios where we need to define files of the same name. This may
lead to name-space collisions. Packages are a way of avoiding name-space collisions.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 39

MCS-024
Types
of
package:
1) User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in packages.
Defining
a
Package:
This statement should be used in the beginning of the program to include that program in that particular
package.
package

<package name>;

Example:
package tools;
public class Hammer {
public void id ()
{
System.out.println ("Hammer");
}
}

Process to create package in Java:


armstrong.java
public class armstrong
{
int x=407;
int r,temp,a=0;
public void test()
{
temp=x;
while(x>0)
{
r=x%10;
a=a+(r*r*r);
x=x/10;
}
if(temp==a)
{
System.out.println("This is Armstrong no..");
}
else
{
System.out.println("This is not Armstrong no..");
}
}
}

After the creation of the program then compile this program with following syntax:
javac

armstrong.java

If compile this part with successfully then write down this program.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 40

MCS-024
Listing 2: Sample showing Example calling package
cal.java
import cei.*;
public class cal{
public static void main(String args[]){
armstrong ob=new armstrong();
ob.test(); //this part is calling package method
}
}

Then compile the code cal.java


javac

cal.java

After that we interpreting this program cal.java


java

cal

Then this call.java will be interpreted and run this program and show the output
Output:
This is Armstrong no.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 41

MCS-024
Qst.4 (c) What is rule of accessibility? Explain different level of accessibility in java.

Ans: Access Modifiers in java


1.
2.
3.
4.
5.
6.

private access modifier


Role of private constructor
default access modifier
protected access modifier
public access modifier
Applying access modifier with method overriding

There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
1.
2.
3.
4.

private
default
protected
public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here,
we will learn access modifiers.

1) private access modifier


The private access modifier is accessible only within class.

Simple example of private access modifier


In this example, we have created two classes A and Simple. A class contains private data member and private method.
We are accessing these private members from outside the class, so there is compile time error.

1.
2.
3.
4.
5.
6.
7.
8.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 42

MCS-024
9.
System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside the class. For
example:

1.
2.
3.
4.
5.
6.
7.
8.
9.

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

Note: A class cannot be private or protected except nested class.


2) default access modifier
If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.

Example of default access modifier


In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package,
since A class is not public, so it cannot be accessed from outside the package.

1.
2.
3.
4.
5.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}

1.
2.
3.
4.
5.
6.

//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 43

MCS-024
7.
obj.msg();//Compile Time Error
8. }
9. }

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside
the package.

3) protected access modifier

The protected access modifier is accessible within package and outside the package but through inheritance
only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on
the class.
Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack package is public, so
can be accessed from outside the package. But msg method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.
1.
2.
3.
4.
5.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}

Output:Hello

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 44

MCS-024
4) public access modifier
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example of public access modifier


1.
2.
3.
4.
5.
6.

//save by A.java

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

//save by B.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Output:Hello

Understanding all java access modifiers

Let's understand the access modifiers by a simple table.


Access Modifier within class within package outside package by subclass only outside package
Private

Default

Protected

Public

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 45

MCS-024
Java access modifiers with method overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}

The default modifier is more restrictive than protected. That is why there is compile time error.

Qst.5 (a) What is abstract class? Explain need of abstract class with the help of an example.
Ans: Abstract class: when we extending an existing class, we have a
choice whether to redefine the methods of the superclass. Basically a superclass has
common features that are shared by subclasses. In some cases you will find that
superclass cannot have any instance (object) and such of classes are called abstract
classes. Abstract classes usually contain abstract methods. Abstract method is a
method signature (declaration) without implementation. Basically these abstract
methods provide a common interface to different derived classes. Abstract classes are
generally used to provide common interface derived classes. You know a superclass
is more general than its subclass(es). The superclass contains elements and properties
common to all of the subclasses. Often, the superclass will be set up as an abstract
class, which does not allow objects of its prototype to be created. In this case only
objects of the subclass are created. To do this the reserved word abstract is included
(prefixed) in the class definition.
For example, the class given below is an abstract class.
public abstract class Player // class is abstract
{
private String name;
public Player(String vname)
{
name=vname;
}
public String getName() // regular method
{
return (name);
}
public abstract void Play();
// abstract method: no implementation
}
Subclasses must provide the method implementation for their particular meaning. If

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 46

MCS-024
the method statements is one provided by the superclass, it would require overriding
in each subclass. In case you forget to override, the applied method statements may be
inappropriate. Now can you think what to do if you have to force that derived classes must redefine
the methods of superclass?
The answer is very simple Make those methods abstract.
In case attempts are made to create objects of abstract classes, the compiler doesnt
allow and generates an error message. If you are inheriting in a new class from an
abstract class and you want to create objects of this new class, you must provide
definitions to all the abstract methods in the superclass. If all the abstract methods of
super class are not defined in this new class this class also will become abstract.
Is it possible to have an abstract class without abstract method? Yes, you can have.
Can you think about the use of such abstract classes? These types of classes are
defined in case it doesnt make any sense to have any abstract methods, in the class
and yet you want to prevent an instance of that class.
Inheritance represent, isa relationship between a subclass and a superclass. In other
words, you can say that every object of a subclass is also a superclass object with
some additional properties. Therefore, the possibility of using a subclass object in
place of a superclass object is always there. This concept is very helpful in
implementing polymorphism.

Qst.5 (b) What is an exception? Explain haw an exception is handled in Java. Explain hierarchy of different
exception classes in java. Also explain why is it not necessary to handle runtime exception?
Ans: Exception: An exceptional condition is considered as a problem, which stops program execution
from continuation from the point of occurrence of it. Exception stops you from
continuing because of lack of information to deal with the exception condition. In
other words it is not known what to do in specific conditions.
If the system does not provide it you would have to write your own routine to test for
possible errors. You need to write a special code to catch exceptions before they
cause an error.
If you attempt in a Java program to carry out an illegal operation, it does not
necessarily halt processing at that point. In most cases, the JVM sees for the
possibility of catching the problem and recovering from it.
If the problems are such which can be caught and recovery can be provided, then we
say the problems are not fatal, and for this the term exception is used rather than
error.
Exception arises at runtime due to some abnormal condition in program for example
when a method. For division encounters an abnormal condition that it can't handle
itself, i.e. divide by zero, then this method may throw an exception.
Exception
is an
abnormal
condition
If a program written in Java does not follow the rule of Java language or violates the
Java execution environment, constraints exception may occur. There may be a
manually generated exception to pass on some error reports to some calling certain
methods.
If an exception is caught, there are several things that can be done:
i. Fix the problem and try again.
ii. Do something else instead to avoid the problem.
iii. Exit the application with System.exit()

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 47

MCS-024
iv. Rethrow the exception to some other method or portion of code.
v. Throw a new exception to replace it.
vi. Return a default value (a non-void method: traditional way of handling
exceptions).
vii. Eat the exception and return from the method (in a void method). In other
words dont give importance to the exception .
viii. Eat the exception and continue in the same method (Rare and dangerous. Be
very careful if you do this).
You should give due care to exceptions in program. Programmers new to
programming almost always try to ignore exceptions. Do not simply avoid dealing
with the exceptions. Generally you should only do this if you can logically guarantee
that the exception will never be thrown or if the statements inside exception checking
block do not need to be executed correctly in order for the following program
statements to run).

HANDLING OF EXCEPTION
Exceptions in Java are handled by the use of these five keywords: try, catch, throw,
throws, and finally. You have to put those statements of program on which you want
to monitor for exceptions, in try block. If any exceptions occur that will be catched
using catch. Java runtime system automatically throws system-generated exceptions.

Using try catch


Now let us see how to write programs in Java, which take care of exceptions
handling.
See the program given below:
//program
public class Excep_Test The throw keyword is used to throw exceptions manually.
{
public static void main(String[] args)
{
int data[] = {2,3,4,5};
System.out.println("Value at : " + data[4]);
}
}
Output:
java.lang.ArrayIndexOutOfBoundsException
at Excep_Test.main(Excep_Test.java:6)
Exception in thread "main"
To catch an exception in Java, you write a try block with one or more catch clauses.
Each catch clause specifies one exception type that it is prepared to handle. The try
block places a fence around the code that is under the watchful eye of the associated
catchers. If the bit of code delimited by the try block throws an exception, the
associated catch clauses will be examined by the Java virtual machine. If the virtual
machine finds a catch clause that is prepared to handle the thrown exception, the
program continues execution starting with the first statement of that catch clause, and
the catch block is used for executing code to handle exception and graceful
termination of the program.
public class Excep_Test

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 48

MCS-024
{
public static void main(String[] args)
{
try
{
int data[] = {2,3,4,5};
System.out.println("Value at : " + data[4]);
}
catch( ArrayIndexOutOfBoundsException e)
{
System.out.println("Sorry you are trying to print beyond the size of data[]");
}
}
}
Output:
Sorry you are trying to print beyond the size of data[]
Catching Multiple Exceptions
Sometimes there may be a chance to have multiple exceptions in a program. You can
use multiple catch clauses to catch the different kinds of exceptions that code can
throw. If more than one exception is raised by a block of code, then to handle these
exceptions more than one catch clauses are used. When an exception is thrown,
different catch blocks associated with try block inspect in order and the first one
whose type (the exception type passed as argument in catch clause) matches with the
exception type is executed This code snippet will give you an idea how to catch
multiple exceptions.
//code snippet
try
{
// some code
}
catch (NumberFormatException e)
{
//Code to handle NumberFormatException
}
catch (IOException e)
{
// Code to handle IOException
}
catch (Exception e)
{
// Code to handle exceptions than NumberFormatException and IOException
}
finally // optional
{
//Code in this block always executed even if no exceptions
}
Now let us see the program given below :
//program
public class MultiCatch

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 49

MCS-024
{
public static void main(String[] args)
{
int repeat ;
try
{
repeat = Integer.parseInt(args[0]);
}
catch (ArrayIndexOutOfBoundsException e)
{
// pick a default value for repeat
repeat = 1;
}
catch (NumberFormatException e)
{
// print an error message
System.err.println("Usage: repeat as count" );
System.err.println("where repeat is the number of times to say Hello Java" );
System.err.println("and given as an integer like 2 or 5" );
return;
}
for (int i = 0; i < repeat; i++)
{
System.out.println("Hello");
}
}
}
Output:
Hello
Using Finally Clause:
A finally clause is included in a program in the last after all the possible code to be
executed. Basically finally block should be the last block of execution in the program.
//program
public class Finally_Test
{
public static void main(String[] args)
{
try
{
System.out.println("Hello " + args[0]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Hello, You are here after ArrayIndexOutOfBoundsException");
}
finally
{
System.out.println("Finally you have to reach here");

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 50

MCS-024
}
}
}
Output:
Hello, You are here after ArrayIndexOutOfBoundsException
Finally you have to reach here

TYPES OF EXCEPTIONS
Exceptions in Java are of two kinds, checked and unchecked. Checked exceptions
are so called because both the Java compiler and the JVM check to make sure that
the rules of Java are obeyed. Problems causes to checked exceptions are:
Environmental error that cannot necessarily be detected by testing; e.g, disk full,
broken socket, database unavailable, etc. Checked exceptions must be handled at
compile time. Only checked exceptions need appear in throws clauses. Problems such
as Class not found, out of memory, no such method, illegal access to private field,
etc, comes under virtual machine error.
Unchecked exceptions
Basically, an unchecked exception is a type of exception for that you option that
handle it, or ignore it. If you elect to ignore the possibility of an unchecked
exception, then, as a result of that your program will terminate. If you elect to handle
an unchecked exception that occur then the result will depend on the code that you
have written to handle the exception. Exceptions instantiated from
RuntimeException and its subclasses are considered as unchecked exceptions.

Checked exceptions
Checked exceptions are those that cannot be ignored when you write the code in your
methods. According to Flanagan, the exception classes in this category represent
routine abnormal conditions that should be anticipated and caught to prevent program
termination.
All exceptions instantiated from the Exception class, or from subclasses, of
Exception other than RuntimeException and its subclasses, must either be:
(i) Handled with a try block followed by a catch block, or
(ii) Declared in a throws clause of any method that can throw them
The conceptual difference between checked and unchecked exceptions is that
checked exceptions signal abnormal conditions that you have to deal with. When
you place an exception in a throws clause, it forces to invoke your method to deal
with the exception, either by catching it or by declaring it in their own throws clause.
If you don't deal with the exception in one of these two ways, your class will not
Compile

Throwable class Hierarchy


All exceptions that occur in Java programs are a subclass of builtin class
Throwable. Throwable class is top of the exception class hierarchy. Two classes
Exception and Error are subclass of Throwable class. Exception class is used to
handle exceptional conditions. Error class defines those exceptions which are not
expected by the programmer to handle.
Exception class and its Subclasses in Throwable class Hierarchy
class java.lang.Object
|
+ class java.lang.Throwable

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 51

MCS-024
|
+ class java.lang.Exception
|
+ class java.awt.AWTException
|
+class java.lang.ClassNotFoundException
|
+ class java.lang.CloneNotSupportedException
|
+ class java.io.IOException
|
+ class java.lang.IllegalAccessException
|
+ class java.lang.InstantiationException
|
+ class java.lang.InterruptedException
|
+ class java.lang.NoSuchMethodException
|
+ class java.lang.NoSuchMethodException
|
+ class java.lang.RuntimeException
|
+ class java.lang.ArithmeticException
|
+ class java.lang.ArrayStoreException
|
+ class java.lang.ClassCastException
|
+ class java.util.EmptyStackException
+ class java.lang.IllegalArgumentException
|
+ class java.lang.Error
Figure 1: Throwable Class Partial Hierarchy

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 52

MCS-024
Qst.5

(c) Write

a java program to create two threads with different priority. Ans:

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 53

MCS-024

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 54

MCS-024
Qst.6 (a) What is I/O stream in java? Write a program in java to create a file and copy the content of an
already existing file into it.
Ans: is I/O stream in java : Input Stream and Output Stream hierarchy
There are two different types of Streams found in Java.io package as shown in
Figure 1a OutputStream and InputStream. Figure 1b shows the further classification
of Inputstream.
The following classes are derived from InputStream Class.
InputStream: Basic input stream.
StringBufferInputStream: An input stream whose source is a string.
ByteArrayInputStream: An input stream whose source is a byte array.
FileInputStream: An input stream used for basic file input.
FilterInputStream: An abstract input stream used to add new behaviour to existing
input stream classes.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 55

MCS-024

PipedInputStream: An input stream used for inter-thread communication. Exploring Java I/O
SequenceInputStream: An input stream that combines two other input streams.
BufferedInputStream: A basic buffered input stream.
PushbackInputStream: An input stream that allows a byte to be pushed back onto
the stream after the byte is read.
LineNumberInputStream: An input stream that supports line numbers.
ataInputStream: An input stream for reading primitive data types.
RandomAccessFile: A class that encapsulates a random access disk file.
Output streams are the logical counterparts to input streams and handle writing data to
output sources. In Figure2 the hierarchy of output Stream is given. The following
classes are derived from outputstream.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 56

MCS-024

OutputStream: The basic output stream.


ByteArrayOutputStream: An output stream whose destination is a byte array.
FileOutputStream: Output stream used for basic file output.
PipedOutputStream: An output stream used for inter-thread communication.
BufferedOutputStream: A basic buffered output stream.
PrintStream: An output stream for displaying text.
DataOutputStream: An output stream for writing primitive data types.
FilterOutputStream: An abstract output stream used to add new behaviour to existing
output stream classes.
Layering byte Stream Filter
Some-times you will need to combine the two input streams. in Java. It is known as
filtered streams ( i.e., feeding an existing stream to the constructor of another
stream). You should continue layering stream constructor until you have access to the
functionality you want.
FileInputStream and FileOutputStream give you input and output streams attached to
a disk file. For example giving file name or full path name of the file in a constructor
as given below:
FileInputStream fin = new FileInputStream(Mydat.dat);
Input and output stream classes only support reading and writing on byte level,
DataInputStream has a method that could read numeric. FileInputStream has no
method to read numeric type and the DataInputStream has no method to get data from
the file. If you have to read the numbers from file, first create a FileInputStream and
pass it to DataInputStream, as you can see in the following code:
FileInputStream fin = new FileInputStream (Mydat.dat);
DataInputStream din = new DataInputStream (fin)
doubles = din.readDouble();
If you want buffering, and data input from a file named Mydata.dat then write your
code like:
DataInputStream din = new DataInputStream(new BufferedInputStream

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 57

MCS-024
(new FileInputStream(employee.dat)));
Now let us take one example program in which we open a file with the binary
FileOutputStream class. Then wrap it with DataOutput Stream class. Finally write
some data into this file.
//program
import java.io.*;
public class BinFile_Test
{
public static void main(String args[])
{
//data array
double data [] = {1.3,1.6,2.1,3.3,4.8,5.6,6.1,7.9,8.2,9.9};
File file = null;
if (args.length > 0 ) file = new File(args[0]);
if ((file == null) || !(file.exists()))
{
// new file created
file = new File("numerical.txt");
}
try
{
// Wrap the FileOutput Stream with DataOutputStream to obtain its writeInt()
method
FileOutputStream fileOutput = new FileOutputStream(file);
DataOutputStream dataOut = new DataOutputStream(fileOutput);
for (int i=0; i < data.length;i++)
dataOut.writeDouble(data[i]);
}
catch (IOException e)
{
System.out.println("IO error is there " + e);
}
}
}
Output:
You can see numeric.txt created in your system you will find something like:
??@
Qst.6 (b) Create an Applet program to display your brief profile with your photograph. Make necessary
assumptions and use appropriate layout in your program.
Ans: The command to insert a picture in an HTML document is as follows:
<img src="File_With_Picture">

For example, suppose you have a digital version of a picture in the subdirectory (subfolder)
pictures. To be concrete, suppose the picture file sunset.gif is in the directory
(subfolder) pictures, and pictures is a subdirectory (subfolder) of the directory
<html>
<head>
<title>
Liars Club Home Page
</title>

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 58

MCS-024
</head>
<body>
<h1>
<center>
Liars Club
</center>
</h1>
<h2>
Club Goals
</h2>
<p>
The goal of the club is to take over the world.
We already have members in key government positions.
</p>
<p>
Another goal is to improve the image of liars.
To this end, we have infiltrated many advertising agencies.
</p>
<img src="smiley.gif">
<h2>
Meeting Times
</h2>
The first Saturday of each month at 5 AM.
<h2>
Other Liar Organizations
</h2>
<a href="http://liars.org/">
Click here for another kind of liar.
</a>
<p> <!--To add some space.-->
</p>
</body>
<address>
<hr>
webmaster@epimenides.org
<br>
June 1, 1888\
</address>
</html>

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 59

MCS-024

(folder) where the HTML page is located. You could add the picture to your HTML
document by inserting the following:
<img src="pictures/sunset.gif">

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 60

MCS-024
You can use either a full path name or a relative path name to the file with the
encoded picture (that is, relative to the directory containing the HTML document).
So, if the picture file is in the same directory (same folder) as the HTML document,
then you simply use the picture file name. Most commonly used picture-encoding formats
are accepted. In particular, .gif, .tiff, and .jpg files are accepted.
Displays 20.4 and 20.5 show an example of an HTML document with a picture of
a smiley face inserted.
(c) Differentiate between String and StringBuffer classes. Also write a program to find the length of a
given string.
Ans: String: In computer programming, a string is traditionally a sequence of characters, either as a literal
constant or as some kind of variable. The latter may allow its elements to be mutated and the length changed, or
it may be fixed (after creation).
Example: ?
Qst.6

1
2 package com.myjava.string;
3
4 public class MyStrSplit {
5
public static void main(String a[]){
6
7
String str = "This program splits a string based on space";
8
String[] tokens = str.split(" ");
9
for(String s:tokens){
System.out.println(s);
10
}
11
str = "This
program splits a string based on space";
12
tokens = str.split("\\s+");
13
}
14}
15

StringBuffer : The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters. Following are
the important points about StringBuffer: A string buffer is like a String, but can be modified.
Example :

1. /*
2.
Java StringBuffer Example
3.
This example shows how java StringBuffer can be built and created using
4.
different constructors of Java StringBuffer class.
5. */
6.
7.
8. public class JavaStringBufferExample {
9.
10. public static void main(String[] args) {
11. /*

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 61

MCS-024
12.
Java StringBuffer is a mutable sequence of characters.
13.
Difference between Java String and StringBuffer is that StringBuffer
14.
can be modified while String can not.
15.
16.
Java StringBuffer can buit using one of the following constructors
17. */
18.
19. /*
20. 1. StringBuffer StringBuffer()
21. Construct empty StringBuffer with initial capacity of 16
22. */
23.
24. StringBuffer sbObj1 = new StringBuffer();
25.
26. /*
27. 2. StringBuffer StringBuffer(int length)
28. Constructs empty StringBuffer with initial capacity of length
29. */
30. StringBuffer sbObj2 = new StringBuffer(10);
31.
32. /*
33. 3. StringBuffer StringBuffer(String str)
34. constructs StringBuffer with the contents same as argument String
35. */
36. StringBuffer sbObj3 = new StringBuffer("Hello World");
37. System.out.println(sbObj3);
38.
39. }
40. }
41.
42. /*
43. Output would be
44. Hello World
45. */
Differentiate between String and StringBuffer classes

No. String
1) String class is immutable.
String is slow and consumes more memory when you concat too
2)
many strings because every time it creates new instance.
String class overrides the equals() method of Object class. So
3)
you can compare the contents of two strings by equals() method.

StringBuffer
StringBuffer class is mutable.
StringBuffer is fast and consumes less
memory when you cancat strings.
StringBuffer class doesn't override the
equals() method of Object class.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 62

MCS-024
Performance Test of String and StringBuffer
1. public class ConcatTest{
2.
public static String concatWithString() {
3.
String t = "Java";
4.
for (int i=0; i<10000; i++){
5.
t = t + "Tpoint";
6.
}
7.
return t;
8.
}
9.
public static String concatWithStringBuffer(){
10.
StringBuffer sb = new StringBuffer("Java");
11.
for (int i=0; i<10000; i++){
12.
sb.append("Tpoint");
13.
}
14.
return sb.toString();
15. }
16. public static void main(String[] args){
17.
long startTime = System.currentTimeMillis();
18.
concatWithString();
19.
System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-startTime)+"ms");
20.
startTime = System.currentTimeMillis();
21.
concatWithStringBuffer();
22.
System.out.println("Time taken by Concating with StringBuffer: "+(System.currentTimeMillis()startTime)+"ms");
23. }
24. }

Qst.7 What is need of layout manager? Explain different layouts available in java for GUI programming.
Ans: layout manager : The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout managers.
When you add a component to an applet or a container, the container uses its layout
manager to decide where to put the component. Different LayoutManager classes use
different rules to place components.
java.awt.LayoutManager is an interface. There are following classes that represents the layout managers it:

1.
2.
3.
4.
5.
6.
7.
8.
9.

java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout
javax.swing.GroupLayout
javax.swing.ScrollPaneLayout
javax.swing.SpringLayout etc.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 63

MCS-024
BorderLayout:

The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each
region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout
provides five constants for each region:
1.
2.
3.
4.
5.

public static final int NORTH


public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER

Constructors of BorderLayout class:

BorderLayout(): creates a border layout but with no gaps between the components.
JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between
the components.

Example of BorderLayout class:

1. import java.awt.*;
2. import javax.swing.*;
3.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 64

MCS-024
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.

public class Border {


JFrame f;
Border(){
f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.

Constructors of GridLayout class:


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between
the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns
alongwith given horizontal and vertical gaps.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 65

MCS-024
Example of GridLayout class:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.

import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 66

MCS-024
25.
26.
27.
28.
29.
30.
31.

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}

FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of
applet or panel.

Fields of FlowLayout class:


public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
5. public static final int TRAILING
1.
2.
3.
4.

Constructors of FlowLayout class:


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical
gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given
horizontal and vertical gap.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 67

MCS-024
Example of FlowLayout class:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.

import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 68

MCS-024
25. }
26. }

BoxLayout class:
The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose, BoxLayout provides
four constants. They are as follows:

Note: BoxLayout class is found in javax.swing package.


Fields of BoxLayout class:
1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS

Constructor of BoxLayout class:

1. BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given axis.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 69

MCS-024
Example of BoxLayout class with Y-AXIS:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

import java.awt.*;
import javax.swing.*;
public class BoxLayoutExample1 extends Frame {
Button buttons[];
public BoxLayoutExample1 () {
buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 70

MCS-024
20.
21.
22.
23.

public static void main(String args[]){


BoxLayoutExample1 b=new BoxLayoutExample1();
}
}

CardLayout class
The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats
each component as a card that is why it is known as CardLayout.

Constructors of CardLayout class:


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.

Commonly used methods of CardLayout class:

public void next(Container parent): is used to flip to the next card of the given container.
public void previous(Container parent): is used to flip to the previous card of the given container.
public void first(Container parent): is used to flip to the first card of the given container.
public void last(Container parent): is used to flip to the last card of the given container.
public void show(Container parent, String name): is used to flip to the specified card with the given name.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 71

MCS-024
Example of CardLayout class:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 72

MCS-024
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37. }

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e) {
card.next(c);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

Qst.7 (b)
What is a TCP/IP socket? Write a java program to create socket.
Ans: TCP/IP socket: TCP/IP refers to two of the protocols in the suite: the Transmission Control Protocol
TCP/IP is a set of and the Internet Protocol.protocols used for communication between different
types of computers and networks.
These protocols utilize sockets to exchange data between machines. The TCP protocol
requires that the machines communicate with one another in a reliable, ordered
stream. Therefore, all data sent from one side must be received in correct order and
acknowledged by the other side. This takes care of lost and dropped data by means of
acknowledgement and re-transmission. UDP, however, simply sends out the data
without requiring knowing that the data be received.
In order to do communication over the TCP protocol, a connection must first be
established between the pair of sockets. While one of the sockets listens for a
connection request (server), the other asks for a connection (client). Once two sockets
have been connected, they can be used to transmit data in both (or either one of the)
directions.
UDP is an unreliable protocol; there is no guarantee that the datagrams you have sent
will be put in the same order by the receiving socket. On the other hand, TCP is a
reliable protocol; it is guaranteed that the packets you send will be put in the order in
which they were sent.
In short, TCP is useful for implementing network services: such as remote login
(rlogin, telnet) and file transfer (FTP). These services require data of indefinite length
to be transferred. UDP is less complex and incurs fewer overheads. UDP is often used
in implementing client/server applications in distributed systems, which are built over
local area networks.
We have already discussed about client and server Sockets in section 3.2 of this Unit.
Recall the discussions in section 3.2, two packages java.net.ServerSocket and
java.net.Socket were used to create sockets.
Before we discuss about Socket and ServerSocket class, it is important to know about
InetAddress class. Let us see what is InetAddress claas.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 73

MCS-024
Java TCP Socket Example
A Server (web server) at ohm.uwaterloo.ca
- listens to port 80 for Client Connection Requests
- Establish InputStream for sending data to client
- Establish OutputStream for receiving data from client
TCP connection example: (Server)
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class myserver {
public static void main( String [] s) {
try {
ServerSocket s = new ServerSocket( 80 );
While (true) {
// wait for a connection request from client
Socket clientConn = s.accept();
InputStream in = clientConn.getInputStream();
OutputStream out = clientConn.getOutputStream();
// communicate with client
// ..
clientConn.close(); // close client connection
}
}catch (Exception e) {
System.out.println(Exception!);
// do something about the exception
}
}
}
TCP connection example: (Client)
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class myclient {
public static void main( String [] s) {
try {
InetAddress addr = InetAddress.getByName(
ohm.uwaterloo.ca);
Socket s = new Socket(addr, 80);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
// communicate with remote process
// e.g. GET document /~ece454/index.html
s.close();
} catch(Exception e) {
System.out.println(Exception);
// do something about the Exception
}
}
}

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 74

MCS-024
Qst.7 (c) Explain the need of JDBC? Explain steps involved in connecting a databases using JDBC.
Ans: During programming you may need to interact with database to solve your problem.
Java provides JDBC to connect to databases and work with it. Using standard library
routines, you can open a connection to the database. Basically JDBC allows the
integration of SQL calls into a general programming environment by providing library
routines, which interface with the database. In particular, Javas JDBC has a rich
collection of routines which makes such an interface extremely simple and intuitive.

Establishing A Connection
The first thing to do, of course, is to install Java, JDBC and the DBMS on the working
machines. Since you want to interface with a database, you would need a driver for
this specific database.

Load the vendor specific driver


This is very important because you have to ensure portability and code reuse. The API
should be designed as independent of the version or the vendor of a database as
possible. Since different DBMSs have different behaviour, you need to tell the driver
manager which DBMS you wish to use, so that it can invoke the correct driver.
For example, an Oracle driver is loaded using the following code snippet:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")

Make the connection


Once the driver is loaded and ready for a connection to be made, you may create an
instance of a Connection object using:
Connection con = DriverManager.getConnection(url, username, password);
Let us see what are these parameters passed to get Connection method of
DriverManager class. The first string is the URL for the database including the
protocol, the vendor, the driver, and the server the port number. The username and
password are the name of the user of database and password is user password.
The connection con returned in the last step is an open connection, which will be used
to pass SQL statements to the database.

Creating JDBC Statements


A JDBC Statement object is used to send the SQL statements to the DBMS. It is
entirely different from the SQL statement. A JDBC Statement object is an open
connection, and not any single SQL Statement. You can think of a JDBC Statement
object as a channel sitting on a connection, and passing one or more of the SQL
statements to the DBMS.
An active connection is needed to create a Statement object. The following code is a Advance Java
snippet, using our Connection object con
Statement statmnt = con.createStatement();
At this point, you will notice that a Statement object exists, but it does not have any
SQL statement to pass on to the DBMS.

Creating JDBC PreparedStatement


PreparedStatement object is more convenient and efficient for sending SQL
statements to the DBMS. The main feature, which distinguishes PreparedStatement
object from objects of Statement class, is that it gives an SQL statement right when it
is created. This SQL statement is then sent to the DBMS right away, where it is
compiled. Thus, in effect, a PreparedStatement is associated as a channel with a
connection and a compiled SQL statement.
Another advantage offered by PreparedStatement object is that if you need to use the
same or similar query with different parameters multiple times, the statement can be
compiled and optimized by the DBMS just once. While with a normal Statement, each
use of the same SQL statement requires a compilation all over again.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 75

MCS-024
PreparedStatements are also created with a Connection method. The following code
shows how to create a parameterized SQL statement with three input parameters:
PreparedStatement prepareUpdatePrice
= con.prepareStatement( "UPDATE Employee SET emp_address =? WHERE
emp_code =1001 AND emp_name =?");
You can see two? symbol in the above PreparedStatement prepareUpdatePrice. This
means that you have to provide values for two variables emp_address and emp_name
in PreparedStatement before you execute it. Calling one of the setXXX methods
defined in the class PreparedStatement can provide values. Most often used methods
are setInt, setFloat, setDouble, setString, etc. You can set these values before each
execution of the prepared statement.
You can write something like:
prepareUpdatePrice.setInt(1, 3);
prepareUpdatePrice.setString(2, "Renuka");
prepareUpdatePrice.setString(3, "101, Sector-8,Vasundhara, M.P");

Executing CREATE/INSERT/UPDATE Statements of SQL


Executing SQL statements in JDBC varies depending on the intention of the SQL
statement. DDL (Data Definition Language) statements such as table creation and
table alteration statements, as well as statements to update the table contents, all are
executed using the executeUpdate method. The following snippet has examples of
executeUpdate statements.
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE Employee " +
"(emp_name VARCHAR2(40), emp_address VARCHAR2(40), emp_sal REAL)" );
stmt.executeUpdate("INSERT INTO Employee " +
"VALUES ('Archana', '10,Down California', 30000" );
String sqlString = "CREATE TABLE Employee " +
"(name VARCHAR2(40), address VARCHAR2(80), license INT)" ;
stmt.executeUpdate(sqlString);
Since the SQL statement will not quite fit on one line on the page, you can split it into
two or more strings concatenated by a plus sign(+).
"INSERT INTO Employee" to separate it in the resulting string from "VALUES".
The point to note here is that the same Statement object is reused rather than to create
a new one each time.
When executeUpdate is used to call DDL statements, the return value is always zero,
while data modification statement executions will return a value greater than or equal
to zero, which is the number of tuples affected in the relation by execution of
modification statement.
While working with a PreparedStatement, you should execute such a statement by
first plugging in the values of the parameters (as you can see above), and then
invoking the executeUpdate on it. For example:
int n = prepareUpdateEmployee.executeUpdate() ;

Executing SELECT Statements


A query is expected to return a set of tuples as the result, and not change the state of
the database. Not surprisingly, there is a corresponding method called execute Query,
which returns its results as a ResultSet object. It is a table of data representing a
database result set, which is usually generated by executing a statement that queries
the database.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the
cursor is positioned before the first row. The next method moves the cursor to the next
row, and because it returns false when there are no more rows in the ResultSet object,

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 76

MCS-024
it can be used in a while loop to iterate through the result set. A default ResultSet
object is not updatable and has a cursor that moves forward only
In the program code given below:
String ename,eaddress;
float esal;
ResultSet rs = stmt.executeQuery("SELECT * FROM Employee");
while ( rs.next() ) {
ename = rs.getString("emp_name");
eaddress = rs.getString("emp_address");
esal = rs.getFloat("emp_salary");
System.out.println(ename + " address is" + eaddress + " draws salary " + esal + "
in dollars");
}
The tuples resulting from the query are contained in the variable rs which is an
instance of ResultSet. A set is of not much use to you unless you can access each row
and the attributes in each row. The?
Now you should note that each invocation of the next method causes it to move to the
next row, if one exists and returns true, or returns false if there is no remaining row.
You can use the getXXX method of the appropriate type to retrieve the attributes of a
row. In the above program code getString and getFloat methods are used to access the
column values. One more thing you can observe that the name of the column whose
value is desired is provided as a parameter to the method.
Similarly,while working with a PreparedStatement, you can execute a query by first
plugging in the values of the parameters, and then invoking the executeQuery on it.
1. ename = rs.getString(1);
eaddress = rs.getFloat(3);
esal = rs.getString(2);
2. ResultSet rs = prepareUpdateEmployee.executeQuery() ; Advance Java

Accessing ResultSet
Now to reach each record of the database, JDBC provides methods like getRow,
isFirst, isBeforeFirst, isLast, isAfterLas to access ResultSet.Also there are means to
make scroll-able cursors to allow free access of any row in the ResultSet. By default,
cursors scroll forward only and are read only. When creating a Statement for a
Connection, we can change the type of ResultSet to a more flexible scrolling or
updatable model:
Statement stmt = con.createStatement
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM Sells");
The different options for types are TYPE_FORWARD_ONLY,
TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_SENSITIVE. We can choose
whether the cursor is read-only or updatable using the options
CONCUR_READ_ONLY, and CONCUR_UPDATABLE.
With the default cursor, we can scroll forward using rs.next(). With scroll-able cursors
we have more options:
rs.absolute(3); // moves to the third tuple or row
rs.previous(); // moves back one tuple (tuple 2)
rs.relative(2); // moves forward two tuples (tuple 4)
rs.relative(-3); // moves back three tuples (tuple 1)

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 77

MCS-024
Qst.8 (a) Explain basic networking features of java.

Ans: ava Networking


Java Networking is a concept of connecting two or more computing devices together so that we can share
resources.
Java socket programming provides facility to share data between different computing devices.
Advantage of Java Networking
1. sharing resources
2. centralize software management
Do You Know ?

How to perform connection-oriented Socket Programming in networking ?


How to display the data of any online web page ?
How to get the IP address of any host name e.g. www.google.com ?
How to perform connection-less socket programming in networking ?

Java Networking Terminology


The widely used java networking terminologies are given below:
1.
2.
3.
4.
5.
6.

IP Address
Protocol
Port Number
MAC Address
Connection-oriented and connection-less protocol
Socket

1) IP Address

IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that
range from 0 to 255.
It is a logical address that can be changed.
2) Protocol

A protocol is a set of rules basically that is followed for communication. For example:

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 78

MCS-024

TCP
FTP
Telnet
SMTP
POP etc.

3) Port Number

The port number is used to uniquely identify different applications. It acts as a communication endpoint
between applications.
The port number is associated with the IP address for communication between two applications.
4) MAC Address

MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface Controller). A network
node can have multiple NIC but each with unique MAC.
5) Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The
example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The
example of connection-less protocol is UDP.
6) Socket

A socket is an endpoint between two way communication.


Visit next page for java socket programming.
Qst.8 (a) What are principles of event delegation model? Explain different sources of events and event
listener.
Ans: In the Java Event Delegation Model the publisher (source) notifies registered subscribers (listeners) when certain
events occur.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 79

MCS-024

There are many types of events and listeners in Java:

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 80

MCS-024

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 81

MCS-024

Action Events
Action eventsalso called semantic eventsare fired by GUI controls such as buttons, text fields, and menu items when
they are activated by the user.
For example, in the reactor console constructor, an IncAction listener is added to the list of listeners for the "inc" button
and a DecAction listener is added to the list of listeners for the "dec" button (these are the only listeners):

incButton.addActionListener(new
decButton.addActionListener(new DecAction());

IncAction());

IncAction and DecAction are declared as inner classes of the ReactorConsole class. This is commonly done because these
classes are seldom reusable outside of a particular GUI, but also because inner class instances have access to the private
variables of the outer class instance that creates them. Thus, our listeners can access the myReactor reference of the
reactor console that creates them:

class

IncAction
public
void
myReactor.inc(500);
}

implements
ActionListener
actionPerformed(ActionEvent
a)

{
{

implements
ActionListener
actionPerformed(ActionEvent
a)

{
{

}
class
public

DecAction
void
myReactor.dec(50);

}
}
Notice that this is yet another example of the Publisher-Subscriber pattern. Components are publishers. They publish
events. Listeners are subscribers. They must implement methods prescribed by appropriate listener interfaces and they
must register with the components they listen to. When an event is fired, the appropriate methods of every registered
listener is called.

Property Change Event


Componentsreusable, replaceable modulesare called Java beans.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 82

MCS-024
A bean has four types of properties: simple, indexed, bound, and constrained. Bound and constrained properties fire
property change events when someone attempts to change their values. If an attempt is made to change a constrained
property, an exception is thrown and the change fails if one of the listeners vetoes the change.
Components of an Event: Can be put under the following categories.
1. Event Object: When the user interacts with the application by clicking a mouse
button or pressing a key an event is generated. The Operating System traps this
event and the data associated with it. For example, info about time at which the
event occurred, the event types (like keypress or mouse click etc.). This data is
then passed on to the application to which the event belongs.
You must note that, in Java, objects, which describe the events themselves,
represent events. Java has a number of classes that describe and handle
different categories of events.
2. Event Source: An event source is the object that generated the event, for
example, if you click a button an ActionEvent Object is generated. The object
of the ActionEvent class contains information about the event (button click).
3. Event-Handler: Is a method that understands the event and processes it. The
event-handler method takes the Event object as a parameter. You can specify
the objects that are to be notified when a specific event occurs. If the event is
irrelevant, it is discarded.
Qst.8 (c) What is servlet? Explain various ways of session management in servlet programming.
Ans: servlet: In this section you will be introduced to server side-programming. Java has utility
known as servlets for server side-programming.
A servlet is a class of Java programming language used to extend the capabilities of
servers that host applications accessed via a request-response programming model.
Although servlets can respond to any type of request, they are commonly used to
extend the applications hosted by web servers. Java Servlet technology also defines
HTTP-specific servlet classes. The javax.servlet and java.servlet.http packages
provide interfaces and classes for writing servlets. All servlets must implement the
Servlet interface, which defines life-cycle methods.
When implementing a generic service, you can use or extend the GenericServlet class
provided with the Java Servlet API. The HttpServlet class provides methods, such as
do get and do Post, for handling HTTP-specific services.
In this section we will focus on writing servlets that generate responses to HTTP
requests. Here it is assumed that you are familiar with HTTP protocol.

4.4.1 Servlet Life Cycle


The container in which the servlet has been deployed controls the life cycle of a
servlet. When a request is mapped to a servlet, the container performs the following
steps.
Loads the servlet class.
Creates an instance of the servlet class.
Initializes the servlet instance by calling the init() method.
When servlet is executed it invokes the service method, passing a request and
response object.
If the container needs to remove the servlet, it finalizes the servlet by calling the
servlets destroy method.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 83

MCS-024

Servlets are programs that run on servers, such as a web server. You all do net surfing Advance Java
and well known the data on which the web is submitted and you get the respond
accordingly. On web pages the data is retrieved from the corporate databases, which
should be secure. For these kinds of operations you can use servlets.

GET and POST Methods


The GET methods is a request made by browsers when the user types in a URL on the
address line, follows a link from a Web page, or makes an HTML form that does not
specify a METHOD. Servlets can also very easily handle POST requests, which are
generated when someone creates an HTML form that specifies METHOD="POST".
The program code given below will give you some idea to write a servlet program:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SomeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Use "request" to read incoming HTTP headers (e.g. cookies)
// and HTML form data (e.g. data the user entered and submitted)
// Use "response" to specify the HTTP response line and headers
// (e.g. specifying the content type, setting cookies).
PrintWriter out = response.getWriter();
// Use "out" to send content to browser
}
}
To act as a servlet, a class should extend HttpServlet and override doGet or doPost (or
both), depending on whether the data is being sent by GET or by POST. These
methods take two arguments: an HttpServletRequest and an HttpServletResponse
objects.
The HttpServletRequest has methods for information about incoming information
such as FORM data, HTTP request headers etc.
The httpServletResponse has methods that let you specify the HTTP response line
(200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most
importantly, a PrintWriter used to send output back to the client.

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 84

MCS-024
A Simple Servlet: Generating Plain Text
Here is a simple servlet that just generates plain text:
//Program file name: HelloWorld.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}

For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.
Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850
E_Mail_Id- Lucknowcomputerclasses@gmail.com, FB Page- facebook.com/bilalali0786 85