Sei sulla pagina 1di 47

RAMRAO ADIK INSTITUTE OF TECHNOLOGY,

NERUL
LAB MANUAL
Object Oriented Pr!r"##in! "nd Met$d%!&
'C#()ter En!ineerin!*
LIST OF E+PERIMENTS
Subject: OOPM
Lab Session: ,$r-./ee0
Year & Semester: S1E1 Se# III'CBGS Re2i-ed* No. of Lectures per week: 3
Facutly Name: Pr41R"j"-$ree S$ed"!e, Pr41 S#it" B$ir, Pr41 S#it" B$"rne
Sr1N1 Tit%e
1
Write a simple program in a!a to Swap two numbers.
"
Write a program to fin# ma$imum an# minimum between % numbers using #ecision
making statements &input wit' comman#(line argument)
%
Write a program to fin# smallest of n numbers taken from user using array.
*
Write a program to #emonstrate use of #ifferent met'o#s of String class.
+
Write a program to create a ,ircle class an# implement met'o# to calculate area of
circle.
- Write a program to implement met'o# o!erloa#ing to calculate area of rectangle.
.
Write a program to perform a##ition of two comple$ numbers by passing an#
returning object as an argument.
/
Write a program to implement multile!el in'eritance #emonstrating met'o#
o!erri#ing.
0 Write a program to #emonstrate use of collection classes.
11 Write program to #emonstrate interfaces in ja!a.
11 Write a program to create an# import your own package.
1" Write a program on e$ception 'an#ling
1% Write a program to #emonstrate multit'rea#ing.
1* Write a program for implementation of 2pplet to print #ifferent s'apes an# string..
1+ ,ase Stu#y :Your 2pplication
E5(eri#ent N1 6
Ai#7 Write a simple program in a!a to Swap two numbers.
T$er&7
a!a is an object(oriente# language similar to ,334 but simplifie# to eliminate language features
t'at cause common programming errors. a!a source co#e files &files wit' a .ja!a e$tension) are
compile# into a format calle# byteco#e &files wit' a .class e$tension)4 w'ic' can t'en be
e$ecute# by a a!a interpreter. ,ompile# a!a co#e can run on most computers because a!a
interpreters an# runtime en!ironments4 known as a!a 5irtual 6ac'ines &56)4 e$ist for most
operating systems4 inclu#ing 7N894 t'e 6acintos' :S4 an# Win#ows. ;yteco#e can also be
con!erte# #irectly into mac'ine language instructions by a just(in(time compiler &8<).
a!a is a general purpose programming language wit' a number of features t'at make t'e
language well suite# for use on t'e Worl# Wi#e Web. Small a!a applications are calle# a!a
applets an# can be #ownloa#e# from a Web ser!er an# run on your computer by a a!a(
compatible Web browser4 suc' as Netscape Na!igator or 6icrosoft 8nternet =$plorer.
You can follow t'e step by step proce#ure to arri!e at t'e result.
1. ,reate a a!a program by typing its co#e in any te$t e#itor suc' as Notepa#.
". Sa!e t'e program by t'e name same as t'at of t'e class containing t'e main &) met'o#. For
e.g. if you create a program to a## two integers t'en name t'e class a as 2##<wo8nt.
,lass 2##<wo8nt
>
public static !oi# main &String args ?@)
>
int aA+4 bA/4 cA1B
cAa3bB
System.out.println &C<'e sum is:D 3 c)B
E
Sa!e t'is program in t'e #irectory w'ere FG is installe#. a!a Fe!elopment Git &FG) is a
program #e!elopment en!ironment for writing a!a applets an# applications. 8t consists of
numerous #e!elopment tools4 classes4 an# met'o#s. <'e FG pro!i#es a collection of t'e a!a
tools4 w'ic' are use# w'ile #e!eloping an# running a!a programs. For e.g.
,:Hja!aHj#k1.+.1I1*HbinH wit' t'e file name 2##<wo8nt.ja!a.
%. Now go to t'e start menu an# open t'e CJunD #ialogue bo$ an# type cm#. You will see t'e
comman# prompt.
*. Now switc' to t'e #irectory w'ere you 'a!e sa!e# t'e a!a program i.e.
,:Hja!aHj#k1.+.1I1*HbinH
+. <ype ja!ac 2##<wo8nt.ja!a to compile t'e program.
-. You will see t'at t'e program compiles successfully an# you are left wit' t'e prompt
,:Hja!aHj#k1.+.1I1*HbinH. an# 2##<wo8nt.class file will be create# in t'e ,:Hja!aHj#k1.+.1I1*Hbin
#irectory.
.. Now to run t'e program type ja!a 2##<wo8nt
You will see t'e output as: <'e sum is: 1%
E5(%"n"tin 4 #"in #et$d dec%"r"tin 78
()b%ic -t"tic 2id #"in' Strin! "r!-9 : *
#"in' * 78 is t'e entry point of t'e program. Jat'er we can say it is t'e main gate to enter insi#e
t'e apartment. 8t s'oul# be public because t'e compiler nee# to enter insi#e t'e met'o# &<'e
guest nee# to access t'e apartment to reac' t'e security guar#).
()b%ic 78 <'e main met'o# must be public because it is call from outsi#e t'e class. 8t is calle#
by j!m.
-t"tic 78 Since main met'o# is written insi#e a class an# to access a met'o# of a class we nee# to
create an object of t'at class first. Since main &) is t'e met'o# w'ic' compiler nee# to call before
creating any object of t'at class we nee# to #eclare main as static. Static met'o#s can be calle#
#irectly by using t'e class name. <'atKs w'y t'e name of t'e file s'oul# be same as t'e name of
t'e class contain main &) met'o#.
2id 78 Since t'e met'o# can return any type of !alue or it mig't not return anyt'ing also so t'e
compiler is #esigne# in suc' a way t'at it s'oul# not take any return !alue so we #eclare main as
!oi# type.
A%!rit$#7
1. Start.
". Fefine class Swap
%. 8nitialiLe !alue of a4 b.
*. Feclare a temporary !ariable.
+. Swap a & b.
+.1 temp M( a
+." a M( b
+.% b M( temp
-. Fisplay a & b.
.. Stop.
Cnc%)-in7 <'us wit' t'is first e$periment we 'a!e stu#ie# 'ow to create4 sa!e4 compile an#
e$ecute simple ja!a program.
E5(eri#ent N1 ,
Ai# 7 Write a program to fin# ma$imum an# minimum between % numbers using #ecision
making statements &input wit' comman#(line argument).
T$er& 7 a!a application can accept any number of arguments #irectly from t'e comman# line.
<'e user can enter comman#(line arguments w'en in!oking t'e application. W'en running t'e
ja!a program from ja!a comman#4 t'e arguments are pro!i#e# after t'e name of t'e class
separate# by space. For e$ample4 suppose a program name# ,mn#Line2rguments t'at accept
comman# line arguments as a string array an# print t'em on stan#ar# output #e!ice.
,mn#Line2rguments.ja!a
class ,mn#Line2rguments
>
public static !oi# main&String?@ args)
>
int lengt' A args.lengt'B if
&lengt' MA 1)
>
System.out.println&NYou nee# to enter some arguments.N)B
E
for &int i A 1B i M lengt'B i33)
>
System.out.println&args?i@)B
E
E
E
,ompile t'e program wit' t'e statement ja!ac ,mn#Line2rguments.ja!a
Jun program wit' some comman# line arguments like: ja!a
,mn#Line2rguments Lero one two t'ree
OUTPUT 7 Lero
:ne
two t'ree
P"r-in! N)#eric C##"nd8Line Ar!)#ent- 7
8f an application nee#s to support a numeric comman#(line argument4 it must con!ert a String
argument t'at represents a number4 suc' as N%*N4 to a numeric !alue. Oere is a co#e snippet t'at
con!erts a comman#(line argument to an int:
class e$ample
>
Public static !oi# main&String args?@)
>
int first2rg4 secon#2rgB
first2rg A 8nteger.parse8nt&args?1@)B secon#2rg A
8nteger.parse8nt&args?1@)B System.out.println&C first
input: C3 first2rg)B
System.out.println&C secon# input: C3 secon#2rg)B
E
E
("r-e+++ 7 2ccepts a string !alue an# con!erts t'at !alue into primiti!e #ata type. 8t is also
calle# as t'e parser met'o# in w'ic' 999 represents a Wrapper class. For e$ample4 parse8nt& )4
parseFloat& )4 parseFouble& ).
A%!rit$#7
1. Start.
". Fefine class 6a$imum.
%. Feclare % integer !ariables a4 b an# c.
*. Jea# % !ariables a4 b4 c.
+. Set aA 8nteger.parse8nt&args?1@)
Set bA 8nteger.parse8nt&args?1@) Set cA
8nteger.parse8nt&args?"@)
-. if&aQb)
>
largeAaB
E
else
>
largeAbB
E
if& cQlarge)
>
largeAcB
E
else
>
largeAlargeB
E
.. Fisplay Clarge C as ma$imum number.
/. Stop.
Cnc%)-in 7 We 'a!e stu#ie# comman# line argument concept to rea# input from user. <'ree
integer numbers are taken from user at e$ecution time an# ma$imum number is #isplaye# on
screen.
E5(eri#ent N1 ;
Ai# 7 Program to perform smallest of n numbers taken from user using array.
T$er&7
2n array is a container object t'at 'ol#s a fi$e# number of !alues of a single type. <'e lengt' of
an array is establis'e# w'en t'e array is create#. 2fter creation4 its lengt' is fi$e#. You 'a!e seen
an e$ample of arrays alrea#y4 in t'e main met'o# of t'e NOello Worl#RN application. <'is section
#iscusses arrays in greater #etail.
An array of 10 elements.
=ac' item in an array is calle# an element4 an# eac' element is accesse# by its numerical index.
2s s'own in t'e prece#ing illustration4 numbering begins wit' 1. <'e 0t' element4 for e$ample4
woul# t'erefore be accesse# at in#e$ /.
Arr"& wit' more t'an one #imension is calle# multi#imensional array. <'e two #imensional
arrays is calle# a matri$.
Dec%"rin! Arr"&7
S&nt"5 7
#ataItype 2rrayIname? @Anew
:J
#ataItype?@?@ arrayInameB
Cre"tin! M)%ti8Di#en-in"% Arr"&7
S&nt"5 7
#ataItype 2rrayIname?@?@ A new #ataItype?noIofIrows@?noIofIcolumns@B
For e$ample: int a?@?@ A new int?%@?%@B
float ab?@?@Anew float?+@?+@B
A%!rit$# 7
1. Start
". Fecalre class 6in=lement
%. Feclare t'e integer array a?11@ an# a !ariable min.
*. <ake input in array from user.
+. 8nitialiLe min A a?1@.
-. i. Start for loop wit' iA1.
ii. compare t'e array !alue wit' min.
iii. if minQa?i@ store t'e !alue a?i@ into min
i!. increment t'e !alue of 8 by 1.
.. Print t'e min !alue.
/. Stop.
Cnc%)-in7 <'us we 'a!e stu#ie# array an# 'a!e implemente# program to fin# minimum !alue
from an array.
E5(eri#ent N1 3
Ai#7 Write a program to #emonstrate use of #ifferent met'o#s of String class.
T$er&7 String manipulation is t'e most common part of many a!a programs. Strings are !ery
important in programming languages as t'ey are use# to process long te$tualSsymbolic
information. <'e information you pro!i#e is in form of or#ere# seTuence of c'aracters an#
symbols is calle# as string.
8n c4 c33 c'aracter arrays are use# to process long te$tual information. 7sing c'aracter
arrays is time consuming so in ja!a4 strings are not consi#ere# as t'e fun#amental #ata type. 8n
a!a Strin! class is pro!i#e# to work wit' strings along wit' facility of c'aracter array.
8n a!a4 Strings are immutable as once an object of t'e String class is create# an#
initialiLe# wit' some !alue t'en it cannot be c'ange#. <'e a!a #e!elopment en!ironment
pro!i#es two classes t'at store an# manipulate c'aracter #ata: Strin!4 for constant strings4 an#
Strin!B)44er4 for mutable strings.
<'e Strin!B)44er class is use# to represent c'aracters t'at can be mo#ifie#. <'is is simply
use# for concatenation or manipulation of t'e strings. String;uffer is mainly use# for t'e
#ynamic string concatenation w'ic' en'ances t'e performance. 2 string buffer implements a
mutable seTuence of c'aracters. 2 string buffer is like a String4 but can be mo#ifie#. 2t any point
in time it contains some particular seTuence of c'aracters4 but t'e lengt' an# content of t'e
seTuence can be c'ange# t'roug' certain met'o# calls.
De4inin! -trin! /it$ Strin! c%"-- 7
1. String str A new String & )B
str A COelloDB
". String str A COiDB
De4inin! -trin! /it$ Strin!B)44er c%"-- 7
String;uffer str A new String;uffer&COelloD)B
De4inin! "rr"& 4 -trin!- 7
String array?@ A>Cstr1D4 Dstr"D4 Dstr%D 4 Cstr*DEB
Di44erent Strin! c%"-- #et$d- "re !i2en be%/ 7
61 -1%en!t$' * 7 <'is met'o# is use# to fin# t'e lengt' of t'e string s.
,1 -61cnc"t'-, * 7 <'is met'o# is use# to concatenate two strings i.e. string s1 an# string s".
;1 -61tL/erC"-e' * 7 <'is met'o# is use# to con!ert string s1 to lower case.
31 -61tU((erC"-e' * 7 <'is met'o# is use# to con!ert string s1 to upper case.
<1 -61-)b-trin!'n* 7 <'is met'o# gi!es t'e sub string starting from t'e nt' c'aracter till en#
position.
=1 -61-)b-trin!'n,#* 7 <'is met'o# gi!es t'e sub string starting from t'e nt' c'aracter upto mt'
c'aracter4 e$clu#ing mt' c'aracter.
>1 -61c$"rAt'n* 7 <'is met'o# is use# to get t'e c'aracter present at in#e$ UnK of t'e gi!en string
s1.
?1 -61e@)"%-'-,* 7 <'is met'o# returns true if string s1 is eTual to string s".
A1 -61c#("reT'-,* 7 <'is met'o# returns negati!e if s1Ms"4 returns positi!e if s1Qs" an#
returns Lero if string s1As".
6B1 -61inde5O4'C5D* 7 <'is met'o# gi!es t'e position of t'e first occurrence of c'aracter U$K in t'e
string s1.
661 -61%"-tInde5O4'C5D* 7 <'is met'o# gi!es t'e position of t'e last occurrence of c'aracter U$K in
t'e string s1.
6,1 -61tri#' * 7 <'is met'o# remo!es t'e w'ite spaces at start an# en# of t'e string s1.
A%!rit$# 7
'Nte7 A%!rit$# de(end- n t$e #et$d- /$ic$ &) "re !in! t i#(%e#ent in t$i-
e5(eri#ent1*

Cnc%)-in7 Wit' t'is e$periment we 'a!e learne# #ifference between String an# String;uffer
an# we 'a!e also stu#ie# #ifferent met'o#s of String class
E5(eri#ent N1 <
Ai#7 Write a program to create a ,ircle class an# implement met'o# to calculate area of circle.
T$er&7
:bjects are t'e basic runtime entities in an object oriente# system. 2 class may be t'oug't of as a
U#ata typeK an# an object as U!ariableK of t'at #ata type. <'e #ata an# co#e of t'e class are
accesse# by object of t'at class.
8n t'is program4 t'e object of class circle is use# to access t'e met'o#s: get#ata&) & area&) of t'is
class.
Synta$:(
class ,lassIName
>
public static !oi# main&String args?@)
>
SS StatementsB
E
E

For e$ample:(
class Joom
>
float lengt'B
float brea#t'B
!oi# get#ata&float a4 float b)
>
lengt'AaB
brea#t'AbB
E
public static !oi# main&String args?@)
>
float areaB
Joom r1Anew Joom&)B
J1.get#ata&"1411)B
areaAr1.lengt'Vr1.brea#t'B
System.out.println&C2reaA D3area)B
E
E
:utput:(
2reaA"11.1
A%!rit$#:
1. Start.
". Feclare a class name# ,ircle.
%. 8nitialiLe t'e reTuire# !ariables.
*. Feclare a met'o# get#ata&) an# get !alue of ra#ius from main function as a
parameter.
+. Feclare a met'o# area to calculate t'e area of circle an# #isplay t'e result.
-. Feclare main&) an# create object of class ,ircle. 2n# access t'e met'o#s wit' t'e
'elp of object.
.. Fisplay t'e area.
/. Stop.
Cnc%)-in: <'us4 we 'a!e stu#ie# 'ow to #efine class an# use objects to access members of
class.
E5(eri#ent N1 =
Ai#7 Write a program to implement met'o# o!erloa#ing to calculate area of rectangle..
T$er&7
a!a allows to create met'o#s t'at 'a!e t'e same name4 but #ifferent parameter lists an#
#ifferent #efinitions. <'is is calle# met'o# o!erloa#ing.
class ,lassName
>
!oi# Function1&#ataItype a4 #ataItype b)
>
SS Statements
E
!oi# Function1&#ataItype a4 #ataItype b4 #ataItype c)
>
SS Statements
E
public static !oi# main&String args?@)
>
,lassName objAnew ,lassName&)B
obj.Function1&5alue145alue")B
obj.Function1&5alue145alue"45alue%)B
E
E
For e$ample:(
class ,alculation
>
!oi# sum&int a4int b)
>
System.out.println&N2##ition of two numbers is:N3&a3b))B
E
!oi# sum&int a4 int b4 int c)
>
System.out.println&N2##ition of t'ree numbers is:N3&a3b3c))B
E
public static !oi# main&String args?@)
>
,alculation cAnew ,alculation&)B
c.sum&114*14-1)B
c.sum&"14"1)B
E
E
:utput:(
2##ition of two numbers is: 111
2##ition of t'ree numbers is: *1
A%!rit$#:
1. Start.
". Feclare a class Jectangle.
%. 8nitialiLe t'e reTuire# !ariables.
*. Feclare two met'o#s wit' same name 'a!ing parameter of #ifferent #ata type.
,alculate area in t'e met'o#s itself.
+. Feclare main&) an# create object of class. 2n# access t'e met'o#s wit' t'e 'elp of
object.
-. Fisplay t'e result.
.. Stop.
Cnc%)-in: <'us4 we 'a!e calculate# t'e absolute !alue of number using one of t'e feature of
ja!a calle# met'o# o!erloa#ing.
E5(eri#ent N1 >
Ai#7 Write a program to perform a##ition of two comple$ numbers by passing an# returning
object as an argument.
T$er&7 2 constructor is a special public member met'o# w'ose task is to initialiLe t'e object
#ata members w'en an object is #eclare#. <'e constructor of a class s'oul# 'a!e t'e same name
as t'e class. For e$ample if t'e name of class is =mployee t'en t'e constructor is a met'o# wit'
t'e name =mployee& ).
,'aracteristics of a constructor are :
1. <'ey s'oul# be #eclare# in t'e public section.
". <'ey automatically get in!oke# w'en t'e objects are create#.
%. <'ey #o not 'a!e return types not e!en !oi# an# t'erefore t'ey cannot return !alues.
*. Like ot'er met'o#s t'ey can 'a!e #efault arguments.
<ypes of ,onstructor:
1. Fefault ,onstructor: 2 constructor wit'out arguments is calle# a #efault constructor. W'en
no constructor is create# e$plicitly t'en a!a first implicitly creates a constructor wit'out any
parameter an# in!okes it. <'e #efault constructor t'en initialiLes t'e instance !ariables to #efault
!alues4 i.e. Lero for numeric #ata types4 null for string type an# false for ;oolean.
". ParameteriLe# ,onstructor: <'e constructor wit' arguments is calle# a parameteriLe#
constructor. 8n parameteriLe# constructors t'e instance !ariable is initialiLe# automatically at run
time accor#ing to t'e !alues passe# to parameters #uring t'e object creation.
,onstructor o!erloa#ing means we can create an# use more t'an one constructor in a class. 2
constructor can be o!erloa#e# on t'e basis of following facts:
1. Number of parameters
". Fata type of parameters
%. :r#er of parameters
W'en we create object of t'e classes4 t'e instance !ariables are initialiLe# accor#ing to t'e
constructor signature.
For e$ample :
class Pro#uct
>
int $4 yB
Pro#uct& )B SSFefault ,onstructor
Pro#uct&int a4 int b ) SSParameteriLe# ,onstructor
E
2lgorit'm :
1. Start
". Fefine class comple$
%. Feclare two !ariables $ & y
*. Fefine constructor
comple$&)
>
$A1
yA1
E
comple$&float real4float img)
>
$ArealB
yAimgB
E
+. Fefine s'ow met'o# to #isplay number
-. Fefine sum met'o# w'ic' takes object as an argument
!oi# sum&comple$ c14comple$ c")
>
$Ac1.$3c".$B
yAc1.y3c".yB
E

.. Fefine ,onstructor:!erloa# class
/. Fefine main met'o#
0. ,reate 24 ;4, objects of ,omple$ type.
11. Wi!e call to sum & s'ow met'o#.
11. Stop
Cnc%)-in7 We 'a!e stu#ie# to #efine constructor4 #ifferent types of constructor an# constructor
o!erloa#ing. Oence implemente# t'e program on a##ition of two comple$ numbers.
E5(eri#ent N1?
Ai#7 Write a program to implement multile!el in'eritance #emonstrating met'o# o!erri#ing.
T$er&7 8n'eritance means to take somet'ing t'at is alrea#y ma#e. 8t is one of t'e most
important features of :bject :riente# Programming. 8t is t'e concept t'at is use# for reusability
purpose. 8n'eritance is t'e mec'anism t'roug' w'ic' we can #eri!e classes from ot'er classes.
<'e #eri!e# class is calle# as c'il# class or t'e subclass or we can say t'e e$ten#e# class an# t'e
class from w'ic' we are #eri!ing t'e subclass is calle# t'e base class or t'e parent class or t'e
super class. <o #eri!e a class in ja!a t'e keywor# e$ten#s is use#.
T&(e- 4 In$erit"nce7
<'e #eri!e# class in'erits some or all of t'e features from t'e base class. 2 class can also in'erit
properties from more t'an one class or from more t'an one le!el.
61 Sin!%e In$erit"nce7 2 #eri!e# class wit' only one base class is calle# as Single
8n'eritance.


,1 Hier"rc$ic"% In$erit"nce7 6ore t'an one class may in'erit t'e features of one class t'is
process is calle# as Oierarc'ical 8n'eritance1
;1 M)%ti%e2e% In$erit"nce7 <'e mec'anism of #eri!ing a class from anot'er #eri!e# class is
calle# 6ultile!el 8n'eritance.
A
B
A
B
C
D
A
B
C
31 H&brid In$erit"nce7 <'ere coul# be situations w'ere we nee# to apply one or more
types of in'eritances to #esign a program t'is process is calle# Oybri# 8n'eritance.
A%!rit$#7
1. Start
". ,reate class ,ar
".1 Fefine a met'o# !e'icle<ype&)
%. Fefine class 6aruti w'ic' e$ten#s ,ar class.
%.1 Write bran#&) to #isplay bran#.
%." Write spee#&) to #isplay spee#.
*. Fefine class 6aruti/11 w'ic' e$ten#s 6aruti.
*.1 :!erri#e a met'o# spee#&).
+. Fefine main met'o#
A
B C
D
-. ,reate object of 6aruti/11 class.
/.1 8n!oke !e'icle<ype&)
/." 8n!oke bran#&)
/.% 8n!oke spee#&)
0. Stop.
Cnc%)-in7 We 'a!e implemente# multile!el in'eritance.
E5(eri#ent N1A
Ai#7 Write a program to #emonstrate use of collection classes.
T$er&7 <'e 2rrayList class e$ten#s 2bstractList an# implements t'e List interface. 2rrayList
supports #ynamic arrays t'at can grow as nee#e#.
Stan#ar# a!a arrays are of a fi$e# lengt'. 2fter arrays are create#4 t'ey cannot grow or s'rink4
w'ic' means t'at you must know in a#!ance 'ow many elements an array will 'ol#.
2rray lists are create# wit' an initial siLe. W'en t'is siLe is e$cee#e#4 t'e collection is
automatically enlarge#. W'en objects are remo!e#4 t'e array may be s'runk.
<'e 2rrayList class supports t'ree constructors. <'e first constructor buil#s an empty array list.
2rrayList& )
<'e following constructor buil#s an array list t'at is initialiLe# wit' t'e elements of t'e
collection c.
2rrayList&,ollection c)
<'e following constructor buil#s an array list t'at 'as t'e specifie# initial capacity. <'e capacity
is t'e siLe of t'e un#erlying array t'at is use# to store t'e elements.
<'e capacity grows automatically as elements are a##e# to an array list.
2rrayList&int capacity)
2part from t'e met'o#s in'erite# from its parent classes4 2rrayList #efines following met'o#s:
Sr1N Met$d- /it$ De-cri(tin
1
2id "dd'int inde5, Object e%e#ent*
8nserts t'e specifie# element at t'e specifie# position in#e$ in t'is list. <'rows
8n#e$:ut:f;oun#s=$ception if t'e specifie# in#e$ is is out of range &in#e$ M 1 XX in#e$
Q siLe&)).
"
b%e"n "dd'Object *
2ppen#s t'e specifie# element to t'e en# of t'is list.
%
b%e"n "ddA%%'C%%ectin c*
2ppen#s all of t'e elements in t'e specifie# collection to t'e en# of t'is list4 in t'e
or#er t'at t'ey are returne# by t'e specifie# collectionYs iterator. <'rows
NullPointer=$ception if t'e specifie# collection is null.
*
b%e"n "ddA%%'int inde5, C%%ectin c*
8nserts all of t'e elements in t'e specifie# collection into t'is list4 starting at t'e
specifie# position. <'rows NullPointer=$ception if t'e specifie# collection is null.
+
2id c%e"r'*
Jemo!es all of t'e elements from t'is list.
-
Object c%ne'*
Jeturns a s'allow copy of t'is 2rrayList.
.
b%e"n cnt"in-'Object *
Jeturns true if t'is list contains t'e specifie# element. 6ore formally4 returns true if
an# only if t'is list contains at least one element e suc' t'at &oAAnull Z eAAnull :
o.eTuals&e)).
/
2id en-)reC"("cit&'int #inC"("cit&*
8ncreases t'e capacity of t'is 2rrayList instance4 if necessary4 to ensure t'at it can 'ol#
at least t'e number of elements specifie# by t'e minimum capacity argument.
0
Object !et'int inde5*
Jeturns t'e element at t'e specifie# position in t'is list. <'rows
8n#e$:ut:f;oun#s=$ception if t'e specifie# in#e$ is is out of range &in#e$ M 1 XX in#e$
QA siLe&)).
11
int inde5O4'Object *
Jeturns t'e in#e$ in t'is list of t'e first occurrence of t'e specifie# element4 or (1 if t'e
List #oes not contain t'is element.
11
int %"-tInde5O4'Object *
Jeturns t'e in#e$ in t'is list of t'e last occurrence of t'e specifie# element4 or (1 if t'e
list #oes not contain t'is element.
1"
Object re#2e'int inde5*
Jemo!es t'e element at t'e specifie# position in t'is list. <'rows
8n#e$:ut:f;oun#s=$ception if in#e$ out of range &in#e$ M 1 XX in#e$ QA siLe&)).
1%
(rtected 2id re#2eR"n!e'int 4r#Inde5, int tInde5*
Jemo!es from t'is List all of t'e elements w'ose in#e$ is between from8n#e$4
inclusi!e an# to8n#e$4 e$clusi!e.
1*
Object -et'int inde5, Object e%e#ent*
Jeplaces t'e element at t'e specifie# position in t'is list wit' t'e specifie# element.
<'rows 8n#e$:ut:f;oun#s=$ception if t'e specifie# in#e$ is is out of range &in#e$ M
1 XX in#e$ QA siLe&)).
1+
int -iEe'*
Jeturns t'e number of elements in t'is list.
1-
Object9: tArr"&'*
Jeturns an array containing all of t'e elements in t'is list in t'e correct or#er. <'rows
NullPointer=$ception if t'e specifie# array is null.
1.
Object9: tArr"&'Object9: "*
Jeturns an array containing all of t'e elements in t'is list in t'e correct or#erB t'e
runtime type of t'e returne# array is t'at of t'e specifie# array.
1/ 2id tri#TSiEe'*
<rims t'e capacity of t'is 2rrayList instance to be t'e listYs current siLe.
A%!rit$#7
'Nte7 A%!rit$# de(end- n t$e #et$d- /$ic$ &) "re !in! t i#(%e#ent in t$i-
e5(eri#ent1*
Cnc%)-in7 <'us we 'a!e implemente# #ifferent met'o#s of 2rrayList class to un#erstan#
collection classes.
E5(eri#ent N1 6B
Ai#7 8 Write program to #emonstrate interfaces in ja!a.
T$er&7 <'e mec'anism of in'eriting t'e features of more t'an one base class into a single class
is known as multiple in'eritances. a!a #oes not support multiple in'eritance but t'e multiple
in'eritance can be ac'ie!e# by using t'e inter4"ce1
8n a!a 6ultiple 8n'eritance can be ac'ie!e# t'roug' use of 8nterfaces by implementing
more t'an one interface in a class. 2n interface is a group of relate# met'o#s wit' empty bo#ies.
8nterfaces #efine only abstract met'o#s an# final fiel#s. <'erefore it is t'e responsibility of t'e
class t'at implements an interface to #efine t'e co#e for implementation of t'ese met'o#s.
S&nt"57
interface 8nterfaceName
>
returnItype met'o#Iname1&parameter(list)B
#ataItype !ariableIname A!alueB
E

A%!rit$# 7
1. Start
". ,reate class Stu#ent
".1 Feclare rollIno as int type
"." Write getnumber&) met'o# to get roll number of a stu#ent
".% Write putnumber&) met'o# to print roll number of a stu#ent
%. Fefine class test w'ic' e$ten#s stu#ent
%.1 Feclare sem14sem" as float type
%." Write getmarks&) met'o# to get marks of a stu#ent
%.% Write putmarks&) met'o# to print marks of a stu#ent
*. Fefine interface sports
*.1 Feclare score of float type
*." #eclare putscore&)B
+. Fefine class Jesult w'ic' e$ten#s test & implements sports
+.1 Feclare total of type float
+." Write #isplay&) met'o#
+.".1 ,alculate total of sem14sem" & score
+."." 8n!oke putnumber&) 4putmarks&)4putscore&) met'o#s
+.".% Print total
+.% Write putscore&) met'o# to #isplay score
-. Fefine class Oybri#
.. Fefine main met'o#.
/. ,reate object of class Jesult
/.1 8n!oke getnumber&)
/." 8n!oke getmarks&)
/.% 8n!oke #isplay&)
0. Stop
Cnc%)-in7 We 'a!e implemente# multiple in'eritances in a!a wit' t'e 'elp of interfaces.
E5(eri#ent N1 66
Ai# 7 Write a program to create an# import your own package.
T$er& 7
Bene4it- 4 P"c0"!e-
61 Packages allow us to organiLe classes into smaller units an# make it easy to locate an#
use t'e appropriate class file.
,1 8t 'elps to a!oi# naming conflict.
;1 Packages protect classes4 #ata an# met'o#s.
Cre"tin! " P"c0"!e
<o create a package4 you c'oose a name for t'e package an# put a package statement wit'
t'at name at t'e top of e!ery source file t'at contains t'e types &classes4 interfaces) t'at you want
to inclu#e in t'e package.
<'e package statement for e$ample4 package grap'icsB must be t'e first line in t'e source
file. <'ere can be only one package statement in eac' source file4 an# it applies to all types in t'e
file.
Package FirstPackage
Public class Jectangle
>
SS class bo#y
E
<'is file woul# be store# as 2.ja!a in a #irectory name# FirstPackage..
8f we #o not use a package statement4 t'en t'at class is store# in #efault package &unname#
package). Wenerally speaking4 an unname# package is only for small or temporary applications
or w'en you are just beginning t'e #e!elopment process. :t'erwise4 classes an# interfaces
belong in name# packages.
U-in! P"c0"!e Me#ber-
<'e types t'at comprise a package are known as t'e package members.
<o use a public package member from outsi#e its package4 you must #o one of t'e following:
Jefer to t'e member by its fully Tualifie# name
8mport t'e package member
8mport t'e memberYs entire package
I#(rtin! " P"c0"!e Me#ber
<o import a specific member into t'e current file4 put an import statement at t'e beginning of t'e
file before any type #efinitions but after t'e package statement4 if t'ere is one.
For e$ample4
import FirstPackage.JectangleB
Now you can refer to t'e Jectangle class by its simple name.
Jectangle myJectangle A new Jectangle&)B
myJectangle is an object of class Jectangle
<o import an =ntire Package wit' all t'e classes4 we 'a!e to use t'e asterisk &V) wil#car#
c'aracter.
import FirstPackage.VB
A%!rit$# 7
'Nte7 A%!rit$# de(end- n t$e ("c0"!e n"#e "nd c%"-- n"#e )-ed in t$i- e5(eri#ent1*
Cnc%)-in 7 Wit' t'is e$periment we 'a!e learne# to create user #efine# package.
E5(eri#ent N1 6,
Ai#7 Write a program on e$ception 'an#ling1
T$er&7 2n e$ception is an abnormal con#ition t'at arises in a co#e seTuence at run time. 8n
ot'er wor#s4 an e$ception is a run(time error.
2 a!a e$ception is an object t'at #escribes an e$ceptional con#ition i.e.4 an error con#ition t'at
'as occurre# in a piece of co#e. W'en t'is type of con#ition arises4 an object representing t'at
e$ception is create# an# t'rown in t'e met'o# t'at cause# t'e error by t'e a!a Juntime. <'at
met'o# may c'oose to 'an#le t'e e$ception itself4 or pass it on.
8f we want t'e program to continue wit' t'e e$ecution of remaining co#e4 t'en we s'oul# try to
catc' t'e e$ception object t'rown by t'e error con#ition an# t'en #isplay an appropriate message
for taking correcti!e action. <'is task is known as e$ception 'an#ling.
<'is mec'anism performs following task:
1. Fin# t'e problem&'it t'e e$ception)
". 8nform t'at an error 'as occurre# & <'row an e$ception)
%. Jecei!e t'e error information & catc' t'e e$ception)
*. <ake correcti!e action &'an#le t'e e$ception)
8n try we put t'e co#e w'ose e$ceptions we want or nee# to trap. 8n catc' we put t'e co#e
t'at will be e$ecute# if an# only if an e$ception of t'e gi!en type is t'rown. 2 try block s'oul#
associate wit' at least a catc' or a finally block. <'e seTuence of try4 catc' an# finally matters a
lot. 8f you mo#ify t'e or#er of t'ese t'en t'e co#e wonKt compile. <'e final concept is t'ere
s'oul# be a single try4 multiple catc' blocks an# a single finally block in a try(catc'(finally
block. 8t is always a goo# practice to use t'e finally block. <'e reason for using t'e finally block
is4 any unrelease# resources can be release# an# t'e memory can be free#. 8f you 'a!e any catc'
clauses associate# wit' t'e try block4 you must put t'e finally clause after all t'e catc' clauses.
We can 'a!e multiple catc' blocks associate# wit' a single try block4 to catc' #ifferent types of
e$ceptions.
Str)ct)re 4 tr&8c"tc$84in"%%& b%c0 i- "- 4%%/- 7
try
>S ;lock of co#e wit' multiple e$it points E
catc' &=$ception e)
> System.out.println &N Woo# 6orning RN)B E
catc' & =$ception e)
> System.out.println &N Oello RN)BE
finally
> SS ;lock of co#e t'at is always e$ecute# w'en t'e try block is e$ite#4
SS no matter 'ow t'e try block is e$ite#.
System.out.println &N Welcome N)B
E
A%!rit$# 7
1. Start
". Fefine class 6ulti=$ceptionFemo
%. Feclare array a of siLe %.
*. Feclare !ariable bA+
+. Write try block
>
int bAarr?*@S&a(arr?1@)B
E
-. Write t'ree catc' blocks
a. <o 'an#le Fi!i#e by Lero error
b. <o #isplay 2rray in#e$ =rror
c. <o #isplay Wrong #ata type
.. Stop.
Cnc%)-in 7 We 'a!e learne# one of t'e ja!a feature calle# e$ception 'an#ling.
E5(eri#ent N1 6;
Ai# 7 W2P to print 12";%,*F+=-F.W/O0811.
T$er& 7
Prce--e- "nd T$re"d-
8n concurrent programming4 t'ere are two basic units of e$ecution: processes an#
t'rea#s. 8n t'e a!a programming language4 concurrent programming is mostly concerne# wit'
t'rea#s.
Prce--e- 7 2 process 'as a self(containe# e$ecution en!ironment. 2 process generally 'as a
complete4 pri!ate set of basic run(time resourcesB in particular4 eac' process 'as its own memory
space.
T$re"d- 7 <'rea#s are sometimes calle# lig'tweig't processes. ;ot' processes an# t'rea#s
pro!i#e an e$ecution en!ironment4 but creating a new t'rea# reTuires fewer resources t'an
creating a new process. <'rea#s e$ist wit'in a process [ e!ery process 'as at least one t'rea#.
<'rea#s s'are t'e processYs resources4 inclu#ing memory an# open files. 6ultit'rea#e#
e$ecution is an essential feature of t'e a!a platform. =!ery application 'as at least one t'rea# [
or se!eral4 if you count NsystemN t'rea#s t'at #o t'ings like memory management an# signal
'an#ling. ;ut from t'e application programmerYs point of !iew4 you start wit' just one t'rea#4
calle# t'e main t'rea#.
Di44erent -t"te- 4 " t$re"d "re :
Ne/ -t"te \ 2fter t'e creations of <'rea# instance t'e t'rea# is in t'is state but before t'e start&)
met'o# in!ocation. 2t t'is point4 t'e t'rea# is consi#ere# not ali!e.

R)nn"b%e 'Re"d&8t8r)n* -t"te \ 2 t'rea# start its life from Junnable state. 2 t'rea# first enters
runnable state after t'e in!oking of start&) met'o# but a t'rea# can return to t'is state after eit'er
running4 waiting4 sleeping or coming back from blocke# state also. :n t'is state a t'rea# is
waiting for a turn on t'e processor.

R)nnin! -t"te F 2 t'rea# is in running state t'at means t'e t'rea# is currently e$ecuting. <'ere
are se!eral ways to enter in Junnable state but t'ere is only one way to enter in Junning state:
t'e sc'e#uler select a t'rea# from runnable pool.

De"d -t"te F 2 t'rea# can be consi#ere# #ea# w'en its run&) met'o# completes. 8f any t'rea#
comes on t'is state t'at means it cannot e!er run again.
B%c0ed 8 2 t'rea# can enter in t'is state because of waiting t'e resources t'at are 'ol# by
anot'er t'rea#.
2s we 'a!e seen #ifferent states t'at may be occur wit' t'e single t'rea#. 2 running t'rea# can
enter to any non(runnable state4 #epen#ing on t'e circumstances. 2 t'rea# cannot enter #irectly
to t'e running state from non(runnable state4 firstly it goes to runnable state. Now lets un#erstan#
t'e some non(runnable states w'ic' may be occur 'an#ling t'e multit'rea#s.
S%ee(in! \ :n t'is state4 t'e t'rea# is still ali!e but it is not runnable4 it mig't be return to
runnable state later4 if a particular e!ent occurs. :n t'is state a t'rea# sleeps for a specifie#
amount of time. You can use t'e met'o# sleep& ) to stop t'e running state of a t'rea#.
static !oi# sleep&long millisecon#) t'rows 8nterrupte#=$ception
G"itin! 4r Nti4ic"tin \ 2 t'rea# waits for notification from anot'er t'rea#. <'e t'rea# sen#s
back to runnable state after sen#ing notification from anot'er t'rea#.

final !oi# wait&long timeout) t'rows 8nterrupte#=$ception
final !oi# wait&long timeout4 int nanos) t'rows 8nterrupte#=$ception
final !oi# wait&) t'rows 8nterrupte#=$ception

Met$d Ret)rn T&(e De-cri(tin
current<'rea#& ) <'rea#
Jeturns an object reference to t'e t'rea# in w'ic' it is
in!oke#.
getName& ) String Jetrie!e t'e name of t'e t'rea# object or instance.
start& ) !oi# Start t'e t'rea# by calling its run met'o#.
run& ) !oi#
<'is met'o# is t'e entry point to e$ecute t'rea#4 like t'e
main met'o# for applications.
sleep& ) !oi#
Suspen#s a t'rea# for a specifie# amount of time &in
millisecon#s).
is2li!e& ) boolean
<'is met'o# is use# to #etermine t'e t'rea# is running or
not.
acti!e,ount& ) 8nt
<'is met'o# returns t'e number of acti!e t'rea#s in a
particular t'rea# group an# all its subgroups.
interrupt& ) !oi# <'e met'o# interrupt t'e t'rea#s on w'ic' it is in!oke#.
yiel#& ) !oi#
;y in!oking t'is met'o# t'e current t'rea# pause its
e$ecution temporarily an# allow ot'er t'rea#s to e$ecute.
join& ) !oi#
<'is met'o# an# join&long millisec) <'rows
8nterrupte#=$ception. <'ese two met'o#s are in!oke# on a
t'rea#. <'ese are not returne# until eit'er t'e t'rea# 'as
complete# or it is time# out respecti!ely.
Some 8mportant 6et'o#s #efine# in ja!a.lang.<'rea# are s'own in t'e table:
<'rea#s can be create# in a!a in t'e following ways :
=$ten#ing t'e ja!a.lang.<'rea# class
8mplementing t'e ja!a.lang.Junnable 8nterface
61 E5tendin! t$e j"2"1%"n!1T$re"d c%"--
<'is is a simplest form of creating t'rea#s in a program. ,onsi#er t'e following co#e
snippet.
public class <'rea#=$ample e$ten#s <'rea#
>
public !oi# run&)
>
System.out.println&C<'is is an e$ample on e$ten#ing t'rea# classD)B
E
(((((
(((((
E
8n t'is co#e snippet4 t'e <'rea#=$ample class is create# by e$ten#ing t'e <'rea# class. <'e
run& ) met'o# of t'e <'rea# class is o!erri##en by t'e <'rea#=$ample class to pro!i#e t'e co#e
to be e$ecute# by a t'rea#.
8n a!a we cannot e$ten# a class from more t'an one class. <'erefore w'ile creating a t'rea#
by e$ten#ing t'e <'rea# class we cannot simultaneously e$ten# any ot'er class.
,1 E5tendin! t$e j"2"1%"n!1R)nn"b%e Inter4"ce
<'rea#s can also be create# by implementing t'e Junnable interface of t'e ja!a.lang
package. <'is package allows to #efine a class t'at can implement t'e Junnable interface an#
e$ten# any ot'er class. ,onsi#er t'e following co#e snippet.
public class <'rea#=$ample implements Junnable
>
public !oi# run&)
>
System.out.println&C<'is is an e$ample on runnable interfaceD)B
E
public static !oi# main&String?@ args)
>
<'rea#=$ample t'r# A new <'rea#=$ample& )B
<'rea# < A new <'ear#&t'r#)B
E
E
8n abo!e co#e snippet4 t'e <'rea#=$ample class is #eclare# by implementing Junnable
interface an# o!erri#ing t'e run& ) met'o# in w'ic' it #efines t'e co#e to be e$ecute# by a
t'rea#.
A%!rit$# 7
1. Start
". Fefine class 2 w'ic' in'erits <'rea# class
".1 ,reate run& ) met'o# to print 1 to 11 numbers
For& int iA1BiMA11Bi33)
Print i
%. Fefine class ; w'ic' in'erits <'rea# class
%.1 ,reate run&) met'o# to print c'aracter using
For& c'ar iA-+BiMA.*Bi33)
Print i
*. Fefine class multit'rea#
+. Fefine main met'o#
-. ,reate objects of 2 & ;
.. 8n!oke a.start& ) t'en b.start& )
/. 8n!oke a.join& ) & b.join& )
0. Stop
Cnc%)-in7 8n t'is e$periment we 'a!e stu#ie# #ifferent met'o#s to create t'e t'rea# an# one
more e$ample on multit'rea#ing.
E5(eri#ent N163
Ai#7 Write a program for implementation of 2pplet to print #ifferent s'apes an# string..
T$er&7 a!a programs are classifie# into two groups: a!a application an# 2pplets. Programs
wit' classes t'at contain main met'o# an# run as stan#alone applications are calle# as a!a
applications. W'ile co#e written to e$ecute un#er t'e control of a browser is calle# an 2pplet.
2pplets can be use# to pro!i#e #ynamic user( interfaces an# a !ariety of grap'ical effects for
web pages.
Di44erence bet/een t$e A((%et- "nd "((%ic"tin- "re "- 4%%/-7
2pplets runs in a web browser4 embe##e# wit'in an 'tml page w'ile 2pplications runs
stan#alone.
2pplets runs insi#e t'e browser4 it implicitly uses t'e inbuilt facilities of e!ent 'an#ling
w'ile in applications you 'a!e to write t'e co#e for e!ent 'an#ling 4 user interface etc
e$plicitly.
Cre"tin 4 A((%et-7
For writing ja!a applet4 you must import java.applet.Applet an# java.awt.* as all applets are
subclasses of 2pplet class w'ic' pro!i#es t'e stan#ar# interface between t'e applet an# t'e
browser en!ironment an# 2W<&2bstract Win#ow <oolkit) package is a library of classes t'at
gi!e applets an# stan#(alone applications grap'ical capability.
Following steps are use# to create t'e applet:
Ste( 67 Write one simple application as follows4
import ja!a.applet.2ppletB
import ja!a.awt.VB
public class OelloWorl#2pplet e$ten#s 2pplet
>
Public !oi# paint &Wrap'ics g)
>
g.#rawString &COello Worl#RD 114 11)B
E
E
8n abo!e e$ample4 we 'a!e import t'e two packages applet an# awt an# e$ten#e# t'e class
2pplet. Oere paint &) met'o# of 2W< ,omponent class is o!erri##en an# t'is takes grap'ics
object as a parameter. 8t is use# to print t'e reTuire# string using t'e #rawstring &) met'o# wit' $
an# y co(or#inates for positioning t'e string on applet.
Ste( ,7 Sa!e t'is class as OelloWorl#2pplet.ja!a an# compile it using ja!ac. <'is will create
.class file.
Ste( ;7 ,reate an O<6L file an# write following co#e4
H$t#%I
H$e"dIJ"2" A((%etH.$e"dI
Hbd&I
H"((%et cdeKLHe%%Gr%dA((%et1c%"--L /idt$K3BB $ei!$tK6BBI
H."((%etI
H.bd&I
H.$t#%I
Ste( 37 Sa!e t'is file as OelloWorl#2pplet.'tml in t'e same #irectory as t'at of your ja!a file.
<'e applet tag in OelloWorl#2pplet.'tml loa#s t'e applet OelloWorl#2pplet.class wit'
wi#t' *11 an# 'eig't as 111.
Ste( <7 =$ecute t'e applet using applet!iewer OelloWorl#2pplet.'tml.
W'en an applet is loa#e#4 following t'ings 'appens(
2n instance of t'e appletKs controlling class is create#.
<'e applet initialiLes itself.
<'e applet starts running.
2n applet can react to major e!ents in t'e following ways:
1. 8t can initialiLe itself.
". 8t can start running.
%. 8t can stop running.
*. 8t can perform a final cleanup4 in preparation for being unloa#e#.
A%!rit$# 7
'Nte7 A%!rit$# de(end- n t$e #et$d- /$ic$ &) "re !in! t i#(%e#ent in t$i-
e5(eri#ent1*
Cnc%)-in 7 Wit' t'is e$periment we 'a!e learne# to create grap'ics in a!a wit' t'e 2pplet
class. Fifference between 2pplet program an# normal application program an# 'ow to create any
applet program.
E5(eri#ent N1 6<
Ai#7 Fesign an# implement a system for your case stu#y.
1. Fefine problem statement.
". Fin# out classes an# objects an# t'eir properties.
%. Fraw class #iagram an# object #iagram.
*. 2## met'o#s to classes an# implement.
+. Jefine abo!e objects by a##ing constructor an# local !ariables.
-. S'ow communication between t'e objects by calling instance of one object from
anot'er class using interaction #iagram.
.. Fin# relations'ip like in'eritance4 association4 aggregation4 composition.
/. Fesign mo#ule an# process #iagram.
Cnc%)-in7 <'us we 'a!e #esigne# an# implemente# real worl# system &case stu#y) using
:bject :riente# Programming 6et'o#ology.

Potrebbero piacerti anche