Anda di halaman 1dari 35

www.ignousolvedassignments.

com
Course Code : MCS-024
Course Title: Object Oriented Technologies and ava
!rogramming "ssignment #umber : MC"
$2%&024&"ssign&'(
"ssignment Mar)s : '00
Ma*imum Mar)s : 2+,
-ast .ates /or Submission : '+th October0 20'( $1or ul2 20'( Session%
www.ignousolvedassignments.com
'+th "3ril0 20'4 $1or anuar2 20'4
Session%
There are eight 4uestions in this assignment which carries 50 mar)s.
6est o/ 20 mar)s are /or viva- voce. "nswer all the 4uestions. 7rite and
e*ecute the 3rogram given in this assignment. "lso in 2our 3rograms
give a33ro3riate comments to increase understandabilit2. !lease go
through the guidelines regarding assignments given in the !rogramme
8uide /or the /ormat o/ 3resentation.
9uestion ' : a% 7hat is Object Oriented !aradigm: ;*3lain /eatures o/
Object Oriented !aradigm. 7h2 Object Oriented !rogramming are
3re/erred over structured 3rogramming :
Solution :
Oops s a process of sovng probems n computers compared to the procedura
anguage programmng such as n C.
Object-oriented 3rogramming s a programmng paradgm
that uses "ob|ects" data structures consstng of data feds and methods
together wth ther nteractons to desgn appcatons and computer programs.
Programmng technques may ncude features such as data abstracton,
www.ignousolvedassignments.com
encapsuaton, moduarty , poymorphsm, and nhertance.
Foowng are the fundamenta features we get:
? Encapsuaton
? Inhertance
? Re-usabty
? Informaton Hdng
;nca3sulation:
The way we make a ogca boundary around behavors (methods) and data
(propertes) they work
on s caed Encapsuaton.
<nheritance:
Ob|ects n OOP reate to each other n one way or another, the reatonshp n
most of the case s parent/chd relationship . The chd ob|ects nherent a the
functonates (methods) and data (propertes) of ther parents.
www.ignousolvedassignments.com
6e-usabilit2
Aong wth inheritance , some other phenomena ke method overoadng and
overrdng, provde code-reuse, whch s known to be a very basc feature of
object oriented programming.
<n/ormation =iding
When we have ways to reuse our code through one way or other, we are aso n
need of some securty regardng our source code. To protect t from unauthorzed
access/ ateraton. In ob|ect orented programmng, ths s caed Informaton
Hdng
Why Object Oriented Programming are preferred over structured programming ?
One of the principal advantages of object-oriented programming techniques over procedural
programming techniques is that they enable programmers to create modules that do not need
to be changed when a new type of object is added. A programmer can simply create a new
object that inherits many of its features from existing objects. This maes object-oriented
programs easier to modify.
www.ignousolvedassignments.com
b% ;*3lain basic /eatures o/ ava
3rogramming language Solution :
Varous features of |ava programmng anguage are as gven
beow :
Simple :
? Java is Easy to write and more readable and eye catching.
? Java has a concise, cohesive set of features that makes it easy to learn and use.
? Most of the concepts are drew from C++ thus making Java learning simpler.
Secure :
? Java program cannot harm other system thus making it secure.
? Java provides a secure means of creating Internet applications.
? Java provides secure way to access web applications.
Portable :
? Java programs can eecute in any environment for which there is a Java run!time
system."J#M$
? Java programs can be run on any platform "%inu,&indow,Mac$
? Java programs can be transferred over world wide web "e.g applets$
Object-oriented :
www.ignousolvedassignments.com
? Java programming is ob'ect!oriented programming language.
? %ike C++ 'ava provides most of the ob'ect oriented features.
? Java is pure ((). %anguage. "while C++ is semi ob'ect oriented$
Robust :
? Java encourages error!free programming by being strictly typed and
performing run!time checks.
Multithreaded :
? Java provides integrated support for multithreaded programming.
Architecture-neutral :
? Java is not tied to a specific machine or operating system architecture.
? Machine Independent i.e Java is independent of hardware .
Interpreted :
www.ignousolvedassignments.com
? Java supports cross!platform code through the use of Java bytecode.
? *ytecode can be interpreted on any platform by J#M.
High performance :
? *ytecodes are highly optimi+ed.
? J#M can eecuted them much faster .
Distributed :
? Java was designed with the distributed environment.
? Java can be transmit,run over internet.
Dnamic :
? Java programs carry with them substantial amounts of run!time type information
that is used to verify and resolve accesses to ob'ects at run time.
9uestion 2 : a% 7hat is static method: ;*3lain wh2 main method in ava
is alwa2s static .
Solution : A Statc method n |ava s one that beongs to a cass rather than an
ob|ect of a cass. Norma methods of a cass can be nvoked ony by usng an
ob|ect of the cass but a Statc method can be nvoked Drecty.
www.ignousolvedassignments.com
Exampe:
pubc cass A {
.....
pubc statc nt getAge(){
....
}
}
pubc cass B {
.....
nt age = A.getAge();
}
In cass B when we wanted the age vaue we drecty caed the method usng
the nstance of the cass nstead of nstantatng an ob|ect of the cass.
A statc method can access ony statc varabes. The reason s obvous.
Somethng that s common to a cass cannot refer to thngs that are specfc to
an ob|ect...
The main method needs to be static so your class does not need to be instantiated in order to
run. When you run your application, the JVM can not create an instance of the class. That can
only be done once the main method is called. Methods of classes that can be called without
the class being instantiated are static.
b! 7hat are di//erent bitwise o3erators available in ava: 7rite a ava
3rogram to e*3lain the use o/ bitwise o3erators.
Solution :
Bitwise Operators
? The Btwse Operators the nteger types, ong, nt, short, char, and byte.
? The Btwse Logca Operators
? Btwse AND (&)
? Btwse OR (|)
www.ignousolvedassignments.com
? Btwse XOR ()
? Left shft (<<)
? Btwse compement (-): nverts ones and zeros n a number
? Demonstrate the btwse ogca operators
? A btwse operators n acton
? Btwse Operator Assgnments
? The Left Shft The Rght Shft
? Use btwse operator to create
hash code Exampe :--
class Main {
public static void main(String[] a) {
System.out.println(9 << 7);
}
}
output: 115
class Main!lass {
www.ignousolvedassignments.com
public static void main(String args[]) {
int a " #;
a " a $$ ;
System.out.println(a);
}
}
output: %
c) What s constructor? Expan constructor overoadng. Wrte a program n |ava
to create Book cass and defne ts constructor(s).
Souton :
Constructor - A constructor s a speca method that s used to ntaze a newy
created ob|ectand s caed |ust after the memory s aocated for the ob|ectIt can
be used to ntaze the ob|ects ,to requred ,or defaut vauesat the tme of ob|ect
creatonIt s not mandatory for the coder to wrte a constructor for the cass
If no user defned constructor s provded for a cass, comper ntazes member
varabes to ts defaut vaues.
www.ignousolvedassignments.com
numerc data types are set to 0
char data types are set to nu
character;_ reference varabes are set
to nu
In order to create a Constructor observe the foowng rues
" - It has the same name as the cass
# - It shoud not return a vaue not even vod
Constructor overloading
Constructor overoadng s a technque n |ava n whch a cass can have any
number of constructors that dffer n parameter sts.The comper dfferentates
these constructors by takng nto account the number of parameters n the st
and ther type.
www.ignousolvedassignments.com
Exampes of vad constructors for cass Account are
Account(nt a);
Account (nt a,nt
b);
Account (Strng a,nt b);
!rogram in java to create >oo) class and de/ine its constructor$s%.
cass BOOK
{
nt name, author;
doube year;
pubc Tme() {
ths.name = 0;
ths.auther = 0;
ths.year = 0.0;
}
www.ignousolvedassignments.com
9uestion ( : a% 7hat is overloading o/ methods: ;*3lain with an
e*am3le how overloading o/ methods is di//erent /rom overriding o/
methods.
Solution :
Method Overloading
Method overloading means havng two or more methods wth the same name but
dfferent sgnatures n the same scope. These two methods may exst n the same
cass or anoter one n base cass and another n derved cass.
class !erson
?
prvate Strng frstName;
prvate Strng astName;
Person()
{
ths.frstName = "";
ths.astName = "";
}
Person(Strng FrstName)
{
ths.frstName = FrstName;
ths.astName = "";
}
Person(Strng FrstName, Strng LastName)
{
ths.frstName = FrstName;
ths.astName = LastName;
www.ignousolvedassignments.com
}
@
Calling Overloaded Methods.
Person(); // as a constructor and ca method wthout parameter
Person(userFrstName); // as a constructor and ca method wth one parameter(ke
User's frst Name)
Person(userFrstName,userLastName); // as a constructor and ca method wth one
parameter(ke User's frst Name)
7hen to use Method Overloading:
Generay, you shoud consder overloading a method when you have requred same
reason that take dfferent sgnatures, but conceptuay do the same thng.
Method Overriding
Method overrdng means havng a di//erent im3lementation o/ the same
method n the inherited class. These two methods woud have the same
signature0 but di//erent
im3lementation. One of these woud exst n the base class and another n the
derived class. These cannot exst n the same cass.
Overrdng methods
Overrdng method defntons
In a derved cass, f you ncude a method defnton that has the same name and
exacty the same number and types of parameters as a method aready defned n
the base cass, ths new defnton repaces the od defnton of the method.
Expanaton
A subcass nherts methods from a supercass. Sometmes, t s necessary for
the subcass to modfy the methods defned n the supercass. Ths s referred to
as method overrdng. The foowng exampe demonstrates method overrdng.
Ste3 '
In ths exampe we w defne a base cass caed Crce
www.ignousolvedassignments.com
class Circle
?
//decarng the nstance varabe
protected doube radus;
pubc Crce(doube radus)
{
ths.radus = radus;
}
// other method defntons here
pubc doube getArea()
{
return Math.PI*radus*radus;
}//ths method returns the area of the crce
@// end of cass crce
When the getArea method s nvoked from an nstance of the Crce cass, the
method returns the area of the crce.
Ste3 2
The next step s to defne a subcass to overrde the getArea() method n the Crce
cass. The derved cass w be the Cynder cass. The getArea() method n the
Crce cass computes the area of a crce, whe the getArea method n the Cynder
cass computes the surface area of a cynder.
The Cynder cass s defned beow.
class C2linder e*tends Circle
?
//decarng the nstance varabe
protected doube ength;
pubc Cynder(doube radus, doube ength)
{
super(radus);
ths.ength = ength;
}
// other method defntons here
www.ignousolvedassignments.com
pubc doube getArea()
{
// method overrden here
return 2*super.getArea()+2*Math.PI*radus*ength;
}//ths method returns the cynder surface area
@// end of cass Cynder
When the overrden method (getArea) s nvoked for an ob|ect of the Cynder cass,
the new defnton of the method s caed and not the od defnton from the
supercass(Crce).
;*am3le code
Ths s the code to nstantate the above two
casses Crce myCrce;
myCrce = new Crce(1.20);
Cynder myCynder;
myCynder = new Cynder(1.20,2.50);
b% 7hat is abstract class: ;*3lain advantages o/ abstract class with the
hel3 o/ an e*am3le. Solution :
Java Abstract classes are used to declare common characteristics of subclasses. An
abstract class cannot be instantiated. It can only be used as a superclass for other
classes that extend the abstract class. Abstract classes are declared with the abstract
keyword. Abstract classes are used to provide a template or design for concrete
subclasses down the inheritance tree.
Like any other class, an abstract class can contain fields that describe the characteristics
and methods thatdescribe the actions that a class can perform. An abstract class can
include methods that contain no implementation. These are called abstract methods.
The abstract method declaration must then end with a semicolon rather than a block. If
a class has any abstract methods, whether declared or inherited, the entire class must
be declared abstract. Abstract methods are used to provide a template for the classes
that inherit the abstract methods.
Abstract classes cannot be instantiated; they must be subclassed, and actual
implementations must be provided for the abstract methods. Any implementation
specified can, of course, be overridden by additional subclasses. An obect must have an
implementation for all of its methods. !ou need to create a subclass that provides an
implementation for the abstract method.
www.ignousolvedassignments.com
A class abstract "ehicle might be specified as abstract to represent the general
abstraction of a vehicle, as creating instances of the class would not be meaningful.
a&stra't 'lass (e)i'le {
int numo*+ears;
String 'olor;
a&stra't &oolean )as,is-.ra-e();
a&stra't int get/oo*+ears();
}
#xample of a shape class as an abstract class
a&stra't 'lass S)ape {
pu&li' String 'olor;
pu&li' S)ape() {
}
pu&li' 0oi1 set!olor(String ') {
'olor " ';
}
pu&li' String get!olor() {
return 'olor;
}
a&stra't pu&li' 1ou&le area();
}
$e can also implement the generic shapes class as an abstract class so that we can
draw lines, circles, trianglesetc. All shapes have some common fields and methods, but
each can, of course, add more fields and methods. The abstract class guarantees that
each shape will have the same set of basic properties. $e declare this class abstract
because there is no such thing as a generic shape. There can only be concrete shapes
such as s%uares, circles, triangles etc.
pu&li' 'lass 2oint e3ten1s S)ape {
stati' int 34 y;
pu&li' 2oint() {
3 " 5;
y " 5;
}
pu&li' 1ou&le area() {
return 5;
www.ignousolvedassignments.com
}
pu&li' 1ou&le perimeter() {
return 5;
}
pu&li' stati' 0oi1 print() {
System.out.println(6point: 6 7 3 7 646 7 y);
}
pu&li' stati' 0oi1 main(String args[]) {
2oint p " ne8 2oint();
p.print();
}
}
&utput
point' (, (
)otice that, in order to create a *oint obect, its class cannot be abstract. This means
that all of the abstractmethods of the +hape class must be implemented by the *oint
class.
The subclass must define an implementation for every abstract method of the abstract
superclass, or the subclass itself will also be abstract. +imilarly other shape obects can
be created using the generic +hape Abstract class.
A big ,isadvantage of using abstract classes is not able to use multiple inheritance. In
the sense, when a class extends an abstract class, it can-t extend any other class.
Question 4 : a) What is polymorphism? Write a java program to show the
advantage of polymorphism
Solution :
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in P
occurs when a parent class reference is used to refer to a child class object.
!ny ja"a object that can pass more than one #$%! test is considered to be polymorphic. #n Ja"a, all ja"a objects
are polymorphic since any object will pass the #$%! test for their own type and for the class bject.
#t is important to know that the only possible way to access an object is through a reference "ariable. ! reference
"ariable can be of only one type. nce declared the type of a reference "ariable cannot be changed.
The reference "ariable can be reassigned to other objects pro"ided that it is not declared final. The type of the
reference "ariable would determine the methods that it can in"oke on the object.
! reference "ariable can refer to any object of its declared type or any subtype of its declared type. ! reference
"ariable can be declared as a class or interface type.
www.ignousolvedassignments.com
Eample:
&et us look at an e'ample.
pu&li' inter*a'e (egetarian{}
pu&li' 'lass 9nimal{}
pu&li' 'lass ,eer e3ten1s 9nimal implements (egetarian{}
(ow the )eer class is considered to be polymorphic since this has multiple inheritance. *ollowing are true for the
abo"e e'ample+
? ! )eer #$%! !nimal
? ! )eer #$%! Vegetarian
? ! )eer #$%! )eer
? ! )eer #$%! bject
When we apply the reference "ariable facts to a )eer object reference, the following declarations are legal+
,eer 1 " ne8 ,eer();
9nimal a " 1;
(egetarian 0 " 1;
:&;e't o " 1;
!ll the reference "ariables d,a,",o refer to the same )eer object in the heap.
!irtual "ethods:
#n this section, # will show you how the beha"ior of o"erridden methods in Ja"a allows you to take ad"antage of
polymorphism when designing your classes.
We already ha"e discussed method o"erriding, where a child class can o"erride a method in its parent. !n
o"erridden method is essentially hidden in the parent class, and is not in"oked unless the child class uses the
super keyword within the o"erriding method.
<= >ile name : ?mployee.;a0a =<
pu&li' 'lass ?mployee
{
pri0ate String name;
pri0ate String a11ress;
pri0ate int num&er;
pu&li' ?mployee(String name4 String a11ress4 int num&er)
{
System.out.println(6!onstru'ting an ?mployee6);
t)is.name " name;
t)is.a11ress " a11ress;
t)is.num&er " num&er;
}
pu&li' 0oi1 mail!)e'-()
{
System.out.println(6Mailing a ')e'- to 6 7 t)is.name
7 6 6 7 t)is.a11ress);
}
pu&li' String toString()
{
return name 7 6 6 7 a11ress 7 6 6 7 num&er;
}
pu&li' String get/ame()
{
www.ignousolvedassignments.com
return name;
}
pu&li' String get911ress()
{
return a11ress;
}
pu&li' 0oi1 set911ress(String ne8911ress)
{
a11ress " ne8911ress;
}
pu&li' int get/um&er()
{
return num&er;
}
}
(ow suppose we e'tend ,mployee class as follows+
<= >ile name : Salary.;a0a =<
pu&li' 'lass Salary e3ten1s ?mployee
{
pri0ate 1ou&le salary; <<9nnual salary
pu&li' Salary(String name4 String a11ress4 int num&er4 1ou&le salary)
{
super(name4 a11ress4 num&er);
setSalary(salary);
}
pu&li' 0oi1 mail!)e'-()
{
System.out.println(6@it)in mail!)e'- o* Salary 'lass 6);
System.out.println(6Mailing ')e'- to 6 7 get/ame()
7 6 8it) salary 6 7 salary);
}
pu&li' 1ou&le getSalary()
{
return salary;
}
pu&li' 0oi1 setSalary(1ou&le ne8Salary)
{
i*(ne8Salary $" 5.5)
{
salary " ne8Salary;
}
}
pu&li' 1ou&le 'ompute2ay()
{
System.out.println(6!omputing salary pay *or 6 7 get/ame()); return
salary<5;
}
}
(ow you study the following program carefully and try to determine its output+
<= >ile name : (irtual,emo.;a0a =< pu&li'
'lass (irtual,emo
{
pu&li' stati' 0oi1 main(String [] args)
{
Salary s " ne8 Salary(6Mo)1 Mo)tas)im64 69m&e)ta4 A264 #4 #B55.55); ?mployee e
" ne8 Salary(6Co)n 91ams64 6.oston4 M964 4 D55.55); System.out.println(6!all
mail!)e'- using Salary re*eren'e EE6); s.mail!)e'-();
System.out.println(6Fn !all mail!)e'- using ?mployee re*eren'eEE6);
e.mail!)e'-();
www.ignousolvedassignments.com
}
}
This would produce following result+
!onstru'ting an ?mployee
!onstru'ting an ?mployee
!all mail!)e'- using Salary re*eren'e EE
@it)in mail!)e'- o* Salary 'lass
Mailing ')e'- to Mo)1 Mo)tas)im 8it) salary #B55.5
!all mail!)e'- using ?mployee re*eren'eEE
@it)in mail!)e'- o* Salary 'lass
Mailing ')e'- to Co)n 91ams 8it) salary D55.5
-ere we instantiate two $alary objects . one using a $alary reference s, and the other using an ,mployee
reference e.
While in"oking s.mail.heck/0 the compiler sees mail.heck/0 in the $alary class at compile time, and the JVM
in"okes mail.heck/0 in the $alary class at run time.
#n"oking mail.heck/0 on e is 1uite different because e is an ,mployee reference. When the compiler
sees e.mail.heck/0, the compiler sees the mail.heck/0 method in the ,mployee class.
-ere, at compile time, the compiler used mail.heck/0 in ,mployee to "alidate this statement. !t run time, howe"er,
the JVM in"okes mail.heck/0 in the $alary class.
This beha"ior is referred to as "irtual method in"ocation, and the methods are referred to as "irtual methods. !ll
methods in Ja"a beha"e in this manner, whereby an o"erridden method is in"oked at run time, no matter what
data type the reference is that was used in the source code at compile time.
b% 7hat is 3ac)age in ava : ;*3lain how to decide the need o/
3ac)age$s% in a s2stem which is to be develo3ed using ava.
Solution :
Packages are used in Ja"a in%order to pre"ent naming conflicts, to control access, to make searching2locating and
usage of classes, interfaces, enumerations and annotations easier etc.
! Package can be defined as a grouping of related types/classes, interfaces, enumerations and annotations 0
pro"iding access protection and name space management.
$ome of the e'isting packages in Ja"a are++
? java#lang % bundles the fundamental classes
? java#io % classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes2interfaces etc. #t is a good practice to
group related classes implemented by you so that a programmers can easily determine that the classes,
interfaces, enumerations, annotations are related.
$ince the package creates a new namespace there won3t be any name conflicts with names in other packages.
4sing packages, it is easier to pro"ide access control and it is also easier to locate the related classes.
www.ignousolvedassignments.com
$reating a pa%&age:
When creating a package, you should choose a name for the package and put a pa%&age statement with that name
at the top of e"ery source file that contains the classes, interfaces, enumerations, and annotation types that you want
to include in the package.
The pa%&age statement should be the first line in the source file. There can be only one package statement in each
source file, and it applies to all types in the file.
#f a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an
unnamed package.
Eample:
&et us look at an e'ample that creates a package called animals. #t is common practice to use lowercased names of
packages to a"oid any conflicts with the names of classes, interfaces.
Put an interface in the package animals+
<= >ile name : 9nimal.;a0a =< pa'-age
animals;
inter*a'e 9nimal { pu&li'
0oi1 eat(); pu&li' 0oi1
tra0el();
}
(ow put an implementation in the same package animals+
pa'-age animals;
<= >ile name : MammalGnt.;a0a =<
pu&li' 'lass MammalGnt implements 9nimal{
pu&li' 0oi1 eat(){
System.out.println(6Mammal eats6);
}
pu&li' 0oi1 tra0el(){
System.out.println(6Mammal tra0els6);
}
pu&li' int no:*Hegs(){ return
5;
}
pu&li' stati' 0oi1 main(String args[]){
MammalGnt m " ne8 MammalGnt(); m.eat();
m.tra0el();
}
}
(ow you compile these two files and put them in a sub%directory called animals and try to run as follows+
I m-1ir animals
I 'p 9nimal.'lass MammalGnt.'lass animals
I ;a0a animals<MammalGnt
Mammal eats
Mammal tra0els
www.ignousolvedassignments.com
9uestion +: a% 7hat is an e*ce3tion: ;*3lain haw an e*ce3tion is handled in
ava. "lso e*3lain hierarch2 o/ di//erent e*ce3tion classes in ava.
Solution :
An exception s an event, whch occurs durng the executon of a program that
dsrupts the norma fow of the program's nstructons
When an error occurs wthn a method, the method creates an ob|ect and hands t
off to the runtme system. The ob|ect, caed an exception object, contans
nformaton about the error, ncudng ts type and the state of the program when
the error occurred. Creatng an excepton ob|ect and handng t to the runtme
system s caed throwing an exception.
$ava exception handling covers the basics of $ava%s exception throwing and catching mechanism&
and exception hierarchies. These texts are'
? Basc Try Catch Fnay
? Excepton Herarches
pu&li' 0oi1 open>ile(){
>ileJea1er rea1er " null; try
{
rea1er " ne8 >ileJea1er(6some>ile6); int
i"5;
8)ile(i K" E1){
i " rea1er.rea1();
System.out.println((')ar) i );
}
} 'at') (G:?3'eption e) {
<<1o somet)ing 'le0er 8it) t)e e3'eption
} *inally {
i*(rea1er K" null){ try {
rea1er.'lose();
} 'at') (G:?3'eption e) {
<<1o somet)ing 'le0er 8it) t)e e3'eption
}
}
System.out.println(6EEE >ile ?n1 EEE6);
}
}
www.ignousolvedassignments.com
b% 7hat is String class in java: ;*3lain how it is di//erent /rom String
>u//er class. "lso write a java 3rogram to /ind whether a given string is a
3alindrome or not.
Solution :
|ava Strng Cass s mmutabe, .e. Strngs n |ava, once created and ntazed,
cannot be changed on the same reference. A |ava.ang.Strng cass s fna whch
mpes no cass and extend t. The |ava.ang.Strng cass dffers from other casses,
one dfference beng that the Strng ob|ects can be used wth the += and +
operators for concatenaton.
Two usefu methods for Strng ob|ects are equas( ) and substrng( ). The equas( )
method s used for testng whether two Strngs contan the same vaue. The
substrng( ) method s used to obtan a seected porton of a Strng.
Ja"a pro"ides the String.u**er and String classes, and the String class is used to manipulate character
strings that cannot be changed. $imply stated, objects of type String are read only and immutable.
The String.u**er class is used to represent characters that can be modified.
The significant performance difference between these two classes is that String.u**er is
faster than String when performing simple concatenations. #n String manipulation code,
character strings are routinely concatenated. 4sing the String class, concatenations are typically
performed as follows+
String str " ne8 String (6Stan*or1 6);
str 7" 6HostKK6;
#f you were to use String.u**er to perform the same concatenation, you would need code that
looks like this+
String.u**er str " ne8 String.u**er (6Stan*or1 6); str.appen1(6HostKK6);
3rogram to /ind whether a given string is a 3alindrome or not.
mport |ava.ang.*;
mport |ava.o.*;
mport |ava.ut.*;
cass Pandrome
{
www.ignousolvedassignments.com
pubc statc vod man(Strng arg| |) throws IOExcepton
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.n));
Strng word=br.readLne( );
nt fag=1;
nt eft=0;
nt rght=word.ength( )-1;
whe(eft<rght)
{
www.ignousolvedassignments.com
f(word.charAt(eft)!=word.charAt(rght))
{
fag=0;
}
eft++;
rght--;
}
f(fag==1)
System.out.prntn("pandrome")
; ese
System.out.prntn("not pandrome");
}
}
www.ignousolvedassignments.com
9uestion A : a% 7hat is multithreading : ;*3lain advantages o/
multithreaded 3rogramming with the hel3 o/ a ava 3rogram.
Solution :
A multithreaded program contains two or more parts that can run concurrently. #ach part of such a
program is called a thread, and each thread defines a separate path of execution. A multithreading is a
speciali.ed form of multitasking. /ultitasking threads re%uire less overhead than multitasking processes.
Lfe Cyce of a Thread:
New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
Waiting: +ometimes a thread transitions to the waiting state while the thread waits for another
thread to perform a task.A thread transitions back to the runnable state only when another
thread signals the waiting thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates
;*am3le
www.ignousolvedassignments.com
<< !reate a ne8 t)rea1.
'lass /e8L)rea1 implements Junna&le {
L)rea1 t;
/e8L)rea1() {
<< !reate a ne84 se'on1 t)rea1
t " ne8 L)rea1(t)is4 6,emo L)rea16);
System.out.println(6!)il1 t)rea1: 6 7 t);
t.start(); << Start t)e t)rea1
}
<< L)is is t)e entry point *or t)e se'on1 t)rea1.
pu&li' 0oi1 run() {
try {
*or(int i " 5; i $ 5; iEE) {
System.out.println(6!)il1 L)rea1: 6 7 i);
<< Het t)e t)rea1 sleep *or a 8)ile.
L)rea1.sleep(555);
}
} 'at') (Gnterrupte1?3'eption e) {
www.ignousolvedassignments.com
System.out.println(6!)il1 interrupte1.6);
}
System.out.println(6?3iting ')il1 t)rea1.6);
}
}
'lass L)rea1,emo {
pu&li' stati' 0oi1 main(String args[]) { ne8
/e8L)rea1(); << 'reate a ne8 t)rea1 try {
*or(int i " 5; i $ 5; iEE) { System.out.println(6Main
L)rea1: 6 7 i); L)rea1.sleep(1555);
}
} 'at') (Gnterrupte1?3'eption e) { System.out.println(6Main
t)rea1 interrupte1.6);
}
System.out.println(6Main t)rea1 e3iting.6);
}
}
b% 7hat is <&O stream in ava: 7rite a 3rogram in ava to create a /ile to
store a ava 3rogram in it. Solution :
The |ava I/O means |ava Input/Output. It s provded by the |ava.o package. Ths
package has an InputStream and OutputStream. |ava InputStream s defned for
readng the stream, byte stream and array of byte stream.
www.ignousolvedassignments.com
9uestion B : a% =ow a ava "33let is di//erent /rom ava "33lication
3rogram: Create an "33let 3rogram to dis3la2 current date and time.
Solution :
,ll Java programs can be classified as Applications and Applets. -he striking differences are
that applications contain main"$ method where as applets do not. (ne more is, applications can
be eecuted at .(/ prompt and applets in a browser. &e can say, an applet is an Internet
application.
,pplet is a Java program eecuted by a browser. -he position of applets in software world is
they occupy the client!side position in &eb communication. (n the server!side, you guess,
another Java program comes, Servlets. ,pplets on client!side and servlets on server!side
makes Java a truly 0Internet-based language0. -o eecute applets, the browsers come with
J1E "Java 1untime Environment$. -he browsers with Java 1untime Environment "or to say,
J#M$ loaded are known as Java enabled browsers.
Applications Vs. Applets
www.ignousolvedassignments.com
Appet program to dspay current date and tme.
import ;a0a.applet.=;
import ;a0a.a8t.=; import
;a0a.util.=; import
;a0a.te3t.=;
pu&li' 'lass !lo'-9pplet e3ten1s 9pplet implements Junna&le{ L)rea1
t4t1;
pu&li' 0oi1 start(){ t "
ne8 L)rea1(t)is);
t.start();
}
pu&li' 0oi1 run(){
t1 " L)rea1.'urrentL)rea1(); 8)ile(t1
"" t){
repaint(); try{
t1.sleep(1555);
}'at')(Gnterrupte1?3'eption e){}
}
}
pu&li' 0oi1 paint(+rap)i's g){ !alen1ar
'al " ne8 +regorian!alen1ar(); ,ate
1"'al.getLime();
Simple,ate>ormat s1*"ne8 Simple,ate>ormat(611EMMEyyyy )):mm:ss6);
g.1ra8String(s1*.*ormat(1)4 54 #5);
}
}
www.ignousolvedassignments.com
To call this applet, you need to create an html file
<MLMH$
<.:,N$
<1i0 align " 6'enter6$
<922H?L !:,? " 6!lo'-9pplet6 @G,LM " 65556 M?G+ML " 6D556$<<922H?L$
<<1i0$
<<.:,N$
<<MLMH$
b$ &hat is layout manager2 &hich is the default layout manager2 .ifferentiate
among the way of managing components by 3 different layouts.
/olution 4
! layout manager is an object that is used to organi5e components in a container.!nd it is an
interface in the ja"a class libraries that describes how a container and a layout manager
communicate.
6order &ayout is the default layout manager .
There are 7 main &ayouts in ja"a +%%%%%%
". Border 'ayout:
- #t has fi"e areas for holding components+ north, east, west, south and center
- When there are only 7 elements to be placed, border layout is the right choice
#. (low 'ayout:
- )efault layout manager.
- #t lays out the components from left to right
(. $ard 'ayout:
- )ifferent components at different times are laid out
- .ontrolled by a combo bo', determining which panel the .ard layout displays
). )rid 'ayout:
- ! group of components are laid out # e1ual si5e and displays them in certain rows and columns
*. )rid Bag 'ayout:
- *le'ible layout for placing components within a grid of cells
- !llows certain components to span more than one cell
- The rows of the grid are not of the same height and height
www.ignousolvedassignments.com
Question 8 : a) What is a socet ! "#plain how a networ socet is created using
Java.
Solution :
A socket s one end-pont of a two-way communcaton nk between two
programs runnng on the network. Socket casses are used to represent the
connecton between a cent program and a server program. The |ava.net
package provdes two casses--Socket and ServerSocket--that mpement the
cent sde of the connecton and the server sde of the connecton, respectvey.
Normay, a server runs on a specfc computer and has a socket that s bound to
a specfc port number. The server |ust wats, stenng to the socket for a cent
to make a connecton request.
On the cent-sde: The cent knows the hostname of the machne on whch the
server s runnng and the port number on whch the server s stenng. To make a
connecton request, the cent tres to rendezvous wth the server on the server's
machne and port. The cent aso needs to dentfy tsef to the server so t bnds
to a oca port number that t w use durng ths connecton. Ths s usuay
assgned by the system.
An endpont s a combnaton of an IP address and a port number. Every TCP
connecton can be unquey dentfed by ts two endponts. That way you can
have mutpe connectons between your host and the server.
b) What is $%S! "#plain co&ponents o' $%S.
Solution :
The DNS translates Internet domain and host names to I* addresses. ,)+ automatically converts
the names we type in our $eb browser address bar to the I* addresses of $eb servers hosting
those sites.
,)+ implements a distributed database to store this name and address information for all public
hosts on the Internet. ,)+ assumes I* addresses do not change 0are statically assigned rather
than dynamically assigned1.
The ,)+ database resides on a hierarchy of special database servers. $hen clients like $eb
browsers issue re%uests involving Internet host names, a piece of software called the DNS
resolver0usually built into the network operating system1 first contacts a +,- server to determine
the server2s I* address. If the ,)+ server does not contain the needed mapping, it will in turn
forward the re%uest to a different ,)+ server at the next higher level in the hierarchy. After
potentially several forwarding and delegation messages are sent within the ,)+ hierarchy, the I*
www.ignousolvedassignments.com
address for the given host eventually arrives at the resolver, that in turn completes the re%uest over
Internet *rotocol.
,)+ additionally includes support for cachingre%uests and for redundancy. /ost network operating
systems support configuration of primary, secondary, and tertiary ,)+ servers, each of which can
service initial re%uests from clients. .nternet -ervice /roviders 0.-/s! maintain their own ,)+ servers and use
+12/ to automatically configure clients, relieving most home users of the burden of ,)+ configuration.
*+S $O",O+E+-S:
The )($ consists of three components. The first is a 8(ame $pace8 that establishes the syntactical
rules for creating and structuring legal )($ names. The second is a 89lobally )istributed
)atabase8 implemented on a network of 8(ame $er"ers8. The third is 8:esol"er8 software, which
understands how to formulate a )($ 1uery and is built into practically e"ery #nternet%capable
application.
0A!+ame Spa%e:
The )($ 8(ame $pace8 is the familiar in"erted tree hierarchy with a null node named 88 at the top.
The child nodes of the root node are the Top &e"el )omains /T&)s0%.com, .net, .org, .go",
.mil%and the country code T&)s, including .jp, .uk, .us, .ca, and so forth. (ode names, known as
labels, can be as many as ;< characters long, with upper% and lower%case alphabetical letters,
numerals, and the hyphen symbol constituting the complete list of legal characters. &abels cannot
begin with a hyphen. 4pper% and lower%case letters are treated e1ui"alently. ! label can appear in
multiple places within the name space, but no two nodes with the same label can ha"e the same
parent node+ ! node name must be uni1ue among its siblings.
03! +ame Servers:
The second key component of the )($ is a globally connected network of 8name ser"ers8. ,ach
5one has a primary or master name ser"er, which is the authoritati"e source for the 5one3s resource
records. The primary name ser"er is the only ser"er that can be updated by means of local
administrati"e acti"ity. $econdary or sla"e name ser"ers hold replicated copies of the primary
ser"er3s data in order to pro"ide redundancy and reduce the primary ser"er3s workload.
*urthermore, name ser"ers generally cache data they ha"e looked up, which can greatly speed up
subse1uent 1ueries for the same data. (ame ser"ers also ha"e a built%in agent mechanism that
knows where to ask for data it lacks. #f a name ser"er can3t find a domain within its 5one, it sends
the 1uery a step closer to the root, which will resend it yet a step closer if it can3t find the domain
itself. The process repeats until it reaches a T&), which ensures that the entire depth of the name
space will be 1ueried if necessary.
The combination of all the )($ name ser"ers and the architecture of the system creates a
remarkable database. There are more than <= million domain names in the popular T&)s for which
the whois utility works. (ominum, whose chief scientist, Paul Mockapetris, in"ented )($, claims
that there are more than >?? million domain names stored and that the system can easily handle
=@,??? 1ueries per second. The database is distributed%no single computer contains all the data.
(e"ertheless, data is maintained locally e"en though it3s distributed globally, and any de"ice
connected to the #P network can perform lookups. The update serial number mechanism in each
5one ensures a form of loose coherency on the network%if a record is out of date, the 1uerier knows
to check a more authoritati"e name ser"er.
www.ignousolvedassignments.com
02! .esolver:
The third component of the )($ is the 8resol"er8. The resol"er is a piece of software that3s
implemented in the #P stack of e"ery destination point, or 8host8 in #,T*%speak. When a host is
configured, manually or through )-.P, it3s assigned at least one default name ser"er along with its
#P address and subnet mask. This name ser"er is the first place that the host looks in order to
resol"e a domain name into an #P address. #f the domain name is in the local 5one, the default name
ser"er can handle the re1uest. therwise, the default name ser"er 1ueries one of the root ser"ers.
The root ser"er responds with a list of name ser"ers that contain data for the T&) of the 1uery. This
response is known as a referral. The name ser"er now 1ueries the T&) name ser"er and recei"es a
list of name ser"ers for the second%le"el domain name. The process repeats until the local name
ser"er recei"es the address for the domain name. The local ser"er then caches the record and
returns the address or other )($ data to the original 1uerier.newdi"
(or )ore Ignou Solved Assign&ents *lease Visit -
www.ignousolvedassign&ents.co&
+onnect on (aceboo :
http:,,www.'aceboo.co&,pages,IgnouSolvedAssign&entsco&,-./0..1.0.-- 002
Subscribe and 3et Solved Assign&ents $irect to 4our Inbo# :
http:,,'eedburner.google.co&,'b,a,&ailveri'4!uri5ignousolvedassign&ents6c o&

Anda mungkin juga menyukai