0% found this document useful (0 votes)
51 views

Programming in Java (2004-2005)

sadadasd

Uploaded by

jocansino4496
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Programming in Java (2004-2005)

sadadasd

Uploaded by

jocansino4496
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 50

1

PROGRAMMING IN JAVA LAB MANUAL

M.C.A. II Year IV Semester 2004 -05

MALLA REDDY ENGINEERING COLLEGE DEPAR MEN O! M. C. A.


Dept. of MCA programming in java Lab ---D.U.V

INDE"

S.No
1 2 3 4 Lab Objective

Contents

Page No.
3 4

Introduction About Lab Guidelines to Students List o! Lab "#ercises and s$llabus Progra%s 'escri(tion about installation and setting o! class(at) and (at)

& * 12 1 43 3

+ & & 1

Setting t)e (re re,uired needs !or success!ul running o! t)e java a((lications -ava a((lications based on various Conce(ts .iva /uestions and Ans0ers 2e!erences

Dept. of MCA

programming in java Lab ---D.U.V

LAB OBJEC IVE


Upon successful completion of t is Lab t e stu!ent "ill be able to# 1. 2. . 3. ).
+.

Demonstrate o" to install t e java soft"are of various version suc as j!$ 1.%&2.% etc. 'etting t e pre re(uire! nee!s for successful running of t e java applications Learn to "rite t e java programs& compiling an! running t e programs. Learn o" to use variables& Data t*pes &Arra*s control statements
,rite t e programs base! on --. concepts/0ncapsulation& 1n eritance& Abstractions an! pol*morp ism.

2. 4.

,rite t e applications basing on concept of interfaces an! 03ception an!ling.. Able to create multi t rea!s an! communicate bet"een t em.

5. 7. 1%.

Able to an!le t e various events suc as 6e* &mouse events. 8uil! o"n application base! on applets Able to Design t e 0ffective ,08 .A90

Dept. of MCA

programming in java Lab ---D.U.V

IN RODUC ION ABOU LAB


: ere are 2% s*stems /,1.;-< installe! in t is Lab . : eir configurations are as follo"s# .rocessor ;AM >ar! Dis$ Mouse ?et"or$ 1nterface car! So!t0are All s*stems are configure! to connect to a 'erver t roug operating s*stem. LA? running Linu3 # # # # # 1ntel Dual Core= 2.0 G#$ +12 M8 5% 98 -ptical Mouse .resent

: is is useful because stu!ents can save t eir "or$ in t eir o"n accounts. 0ac stu!ent@s "or$ is safe an! secure from ot er stu!ents. Latest :ec nologies li$e -racle 7i an! A200 are installe! in all t e s*stems.

MA'M / Macro Assembler < is installe! in all t e s*stems 'tu!ents can e3ecute t eir assembl* language programs using MA'M. MA'M is ver* useful stu!ents because " en t e* e3ecute t eir programs t e* can see contents of .rocessor ;egisters an! o" eac instruction is being e3ecute! in t e C.U. ;ational ;ose 'oft"are is installe! in some s*stems Using t is soft"are& stu!ents can !epict UML !iagrams of t eir projects. 'oft"are installe!# C& CBB& AD61.+& MA'M& -CC1C0-D.& A200 an! D-: ?0:& ;ational ;ose& -racle 7i& 1nformatica 4.1.2. '*stems are provi!e! for stu!ents in t e 1#1 ratio. '*stems are assigne! numbers an! same s*stem is allotte! for stu!ents " en t e* !o t e lab.

Dept. of MCA

programming in java Lab ---D.U.V

Guidelines to Students

Sett%&' () PA # a&* CLASSPA #


+%s se,t%(& e-./a%&s +(0 t( 1se t+e PA45 a&* CLASSPA45 e&2%r(&me&t 2ar%a3/es (& M%,r(s()t 4%&*(0s5 S(/ar%s5 a&* L%&1-. C(&s1/t t+e %&sta//at%(& %&str1,t%(&s %&,/1*e* 0%t+ 6(1r %&sta//at%(& () t+e Ja2a De2e/(.me&t 7%t 8JD79 s()t0are 31&*/e )(r ,1rre&t %&)(rmat%(&. A)ter %&sta//%&' t+e s()t0are5 t+e JD7 *%re,t(r6 0%// +a2e t+e str1,t1re s+(0& 3e/(0.

+e bin *%re,t(r6 ,(&ta%&s 3(t+ t+e ,(m.%/er a&* t+e /a1&,+er. U.*ate t+e PA # Var%a3/e 8M%,r(s()t 4%&*(0s N :2000:"P9 Y(1 ,a& r1& Ja2a a../%,at%(&s ;1st )%&e 0%t+(1t sett%&' t+e PA45 2ar%a3/e. Or5 6(1 ,a& (.t%(&a//6 set %t as a ,(&2e&%e&,e. Set t+e PA45 2ar%a3/e %) 6(1 0a&t t( 3e a3/e t( ,(&2e&%e&t/6 r1& t+e e-e,1ta3/es 8javac.e#e5 java.e#e5 javadoc.e#e5 a&* s( (&9 )r(m a&6 *%re,t(r6 0%t+(1t +a2%&' t( t6.e t+e )1// .at+ () t+e ,(mma&*. I) 6(1 *( &(t set t+e PA45 2ar%a3/e5 6(1 &ee* t( s.e,%)6 t+e )1// .at+ t( t+e e-e,1ta3/e e2er6 t%me 6(1 r1& %t5 s1,+ as< C<=Pr('ram !%/es=Ja2a=;*>?.@.0=3%&=;a2a, M6C/ass.;a2a

Dept. of MCA

programming in java Lab ---D.U.V

2 Note6 It %s 1se)1/ t( set t+e PA45 .erma&e&t/6 s( %t 0%// .ers%st a)ter re3((t%&'. ( set %t .erma&e&t/65 a** t+e )1// .at+ () t+e jd71.+.3 3%& *%re,t(r6 t( t+e PA45 2ar%a3/e. Set t+e PA45 as )(//(0s. ( ma>e a .erma&e&t ,+a&'e t( t+e CLASSPA # 2ar%a3/e5 1se t+e S6stem %,(& %& t+e C(&tr(/ Pa&e/. +e .re,%se .r(,e*1re 2ar%es *e.e&*%&' (& t+e 2ers%(& () 4%&*(0s. +e PA45 ,a& 3e a ser%es () *%re,t(r%es se.arate* 36 sem%,(/(&s 8A9. M%,r(s()t 4%&*(0s /((>s )(r .r('rams %& t+e PA45 *%re,t(r%es %& (r*er5 )r(m /e)t t( r%'+t. Y(1 s+(1/* +a2e (&/6 (&e bin *%re,t(r6 )(r t+e JD7 %& t+e .at+ at a t%me 8t+(se )(//(0%&' t+e )%rst are %'&(re*95 s( %) (&e %s a/rea*6 .rese&t5 6(1 ,a& 1.*ate t+at .art%,1/ar e&tr6. U.*ate t+e PA # Var%a3/e 8S(/ar%s a&* L%&1-9 Y(1 ,a& r1& t+e JD7 ;1st )%&e 0%t+(1t sett%&' t+e PA45 2ar%a3/e5 (r 6(1 ,a& (.t%(&a//6 set %t as a ,(&2e&%e&,e. #(0e2er5 6(1 s+(1/* set t+e .at+ 2ar%a3/e %) 6(1 0a&t t( 3e a3/e t( r1& t+e e-e,1ta3/es 8 javac5 java5 javadoc5 a&* s( (&9 )r(m a&6 *%re,t(r6 0%t+(1t +a2%&' t( t6.e t+e )1// .at+ () t+e ,(mma&*. I) 6(1 *( &(t set t+e PA45 2ar%a3/e5 6(1 &ee* t( s.e,%)6 t+e )1// .at+ t( t+e e-e,1ta3/e e2er6 t%me 6(1 r1& %t5 s1,+ as< B :1sr:/(,a/:;*>?.@.0:3%&:;a2a, M6C/ass.;a2a ( )%&* (1t %) t+e .at+ %s .r(.er/6 set5 e-e,1te< B ;a2a -2ers%(& +%s 0%// .r%&t t+e 2ers%(& () t+e java t((/5 %) %t ,a& )%&* %t.

Dept. of MCA

programming in java Lab ---D.U.V

List of Lab Exercises and Syllabus Programs


8""91 1. 1nstall t e java soft"are of various version suc as j!$ 1.%&2.% etc. 2. 'etting t e pre re(uire! nee!s for successful running of t e java applications 3. ,rite java base! program to illustrate -verloa!ing an! -verri!ing met o!s 8""92 1.,rite a program to illustrate 'ingle in eritance 2.,rite a program to illustrate multilevel in eritance 3.,rite a program to implementation of multiple in eritance using interfaces in java. 8""93 1..rogram to create pac$ages in java 2..rogram to !emonstrate t e importing an! accessing t e pac$ages 8""94 1..rogram to create : rea!. 2..rogram to create Multiple : rea!s using runnable interface. 3. .rogram to create Mutiple : rea!s using : rea! class. 8""9 1..rogram to implement inter-t rea! communication. 2.,rite program to !escribe t e life c*cle of Applet. 8""9+ .rograms to ,rite applets to !ra" t e a< line b< circle c< rectangle 8""9& ,rite a program to create an! manipulate t efollo"ing a<lables. b< te3tfiel!s c< te3tareas !<panels 8""9 1 1..rogram to !emonstrate Mouse0vent 2..rogram to an!le 6e*0vent
3.Write a program to illustrate the usage InnerClass.

8""9 * 1. ,rite a program t at illustrate t e boar!er la*out. 2. ,rite a program t at illustrate t e 9ri! la* out. Dept. of MCA programming in java Lab ---D.U.V

,006 1%
1 2 .rogram to implement : rea! s*nc roniEation .rogram to implement : rea! .riorit*.

SOLUTIONS:

Dept. of MCA

programming in java Lab ---D.U.V

7
WEEK1

1. Install t)e java so!t0are o! various version suc) as jd7 1.3:2.3 etc.
'tep1.As t e s*m$e* user& !o"nloa! t e free AD6 +.% F also $no"n as A2'0+ - from 'unGs "ebsite an! store it in a temporar* !irector* /c#Htmp<. Do"nloa! t e stan!alone version of t e A2'0 an! not t e ones bun!le! "it ?et8eans or "it Aava 00. : e instructions belo" appl* onl* to t e stan!alone version of t e AD6. 'tep2 1f *ou are in a countr* " ere it is available& !o"nloa! t e -ava Cr$(togra()$ "#tension ;-C"< =nli%ited Strengt) -urisdiction Polic$ >iles .3 from t e same page on t e "ebsite. 'ave t is file in t e temporar* !irector* /c#Htmp<. 1f *ou cannot !o"nloa! t is file& *ou "ill not be able to use an* s*mmetric $e* " ose siEe is greater t an 125-bits. 'tep3.9o to t e c6?t%( !irector* an! install t e AD6 b* e3ecuting t e !o"nloa!e! binar* file using j!$-1I+I%I%3-"in!o"s-i+52-p.e3e

'tep )#'elect I acce(t t)e ter%s in t)e license agree%ent an! clic$ Ne#t to continue. Jou s oul! see#

'tep + 'elect t e little pull-!o"n icon ne3t to 'e%os an! select 'on@t install t)is !eature no0. Dept. of MCA programming in java Lab ---D.U.V

1% 'tep 2 Do t e same for Source Code an! Public -2". : ese are not nee!e! for 'trong6e*. Jour panel s oul! loo$ li$e t e follo"ing

'tep 4Clic$ t e C)ange... button on t e panel. Jou s oul! see#

'tep 5.C ange t e !efault >older na%e to C6?usr?local?jd71. .3A3#? an! clic$ O9. Jou ma* nee! to clic$ on 'evelo(%ent 4ools first before t e C)ange... button is activate!. Jou s oul! see# ?ote# : e ?usr?local?jd71. .3A3# !irector* !oes not e3ist at t is stage& so *ou "ill not be able to select it from t e 9U1. Jou "ill ave to t*pe it in into t e >older Na%e fiel! at t e bottom of t e "iEar!& as s o"n belo".

Dept. of MCA

programming in java Lab ---D.U.V

11

'tep 7 Clic$ Ne#t to continue. Jou s oul! see a Progress panel t at ta$es a fe" minutes to go t roug t e installation.

'tep 1% , en t e installation is complete& *ou s oul! see t e follo"ing

'tep11. Clic$ Cinis to e3it t e "iEar!.

Dept. of MCA

programming in java Lab ---D.U.V

12

2. 'etting t e pre re(uire! nee!s for successful running of t e java applications


'tep1.:o a!! t e Aava e3ecutable to *our Co%%and Pro%(t pat & open t e Control Panel /from StartBCControl Panel< 'tep2.'elect t e S$ste% option an! open its !ialog panel. Jou s oul! see

'tep3.C oose t e Advanced tab. Jou s oul! see

'tep)# Clic$ on "nviron%ent .ariables. Jou s oul! see

Dept. of MCA

programming in java Lab ---D.U.V

13

'tep+. 'li!e t e sli!er in t e S$ste% variables section till *ou see t e Pat) variable. >ig lig t it& as follo"s#

'tep2. Clic$ on t e "dit button. Jou s oul! see

'tep 4..ress t e 5o%e $e* on *our .C to go to t e beginning& an! a!! t e follo"ing to t e .ariable value c#HusrHlocalHj!$1.+.%I%3HbinK Dept. of MCA programming in java Lab ---D.U.V

1) , en complete!& it s oul! resemble t e follo"ing

Clic$ O9 to e3it t e "dit S$ste% .ariable panel. 'tep5.Clic$ O9 again to e3it t e "nviron%ent .ariables panel. 'tep7.Clic$ O9 to e3it t e S$ste% Pro(erties panel. 'tep1%.Cinall*& e3it t e Control .anel.

Dept. of MCA

programming in java Lab ---D.U.V

1+

-ava a((lications based on various Conce(ts


8rite java based (rogra% to illustrate Overloading and Overriding %et)ods
OVERRIDING when you extend a class and write a method in the derived class which is exactly similar to the one present in the base class, it is termed as overridin ! E-am./e< .13/%, ,/ass BaseC/assC .13/%, 2(%* met+(* (O2err%*e89 C ::S(me ,(*e +ere D D .13/%, ,/ass Der%2e*C/ass e-te&*s BaseC/assC .13/%, 2(%* met+(* (O2err%*e89 C ::S(me &e0 ,(*e +ere D D As 6(1 ,a& see5 %& t+e ,/ass Der%2e*C/ass5 0e +a2e (2err%**e& t+e met+(* .rese&t %& t+e BaseC/ass 0%t+ a ,(m./ete/6 &e0 .%e,e () ,(*e %& t+e Der%2e*C/ass. 4+at t+at e))e,t%2e/6 mea&s %s t+at %) 6(1 ,reate a& (3;e,t () Der%2e*C/ass a&* ,a// t+e met+(* (O2err%*e89 met+(*5 t+e ,(*e %& t+e *er%2e*C/ass 0%// 3e e-e,1te*. I) 6(1 +a*&Et (2err%**e& t+e met+(* %& t+e Der%2e*C/ass t+e& t+e met+(* %& t+e BaseC/ass 0(1/* +a2e 3ee& ,a//e*. Dept. of MCA programming in java Lab ---D.U.V

12 OVER"O#DING $ when you have more than one method with the same name but di%%erent ar uments, the methods are said to be overloaded! E-am./e< .13/%, ,/ass O2erL(a*%&'E-am./eC .13/%, 2(%* a**8%&t %5 %&t ;9 C %&t > F % G ;A D .13/%, 2(%* a**8Str%&' s5 Str%&' t9 C %&t > F I&te'er..arseI&t8s9 G I&te'er..arseI&t8t9A D D As 6(1 ,a& see %& t+e e-am./e a3(2e5 0e +a2e t+e same met+(* a**89 ta>%&' t0( .arameters 31t 0%t+ *%))ere&t *ata t6.es. D1e t( (2er/(a*%&' 0e ,a& &(0 ,a// t+e a** met+(* 36 e%t+er .ass%&' %t a Str%&' (r %&t .

,006 2 1.8rite a (rogra% to illustrate Single in)eritance


LM 'ingle 1n etitance :o Cin! Area -f ;ectangle ML class Dimensions N int lengt K int brea!t K O class ;ectangle e3ten!s Dimensions N Dept. of MCA programming in java Lab ---D.U.V

14 int aK voi! area/< N a P lengt M brea!t K O O class Area N public static voi! main/'tring argsQR< N ;ectangle ;ect P ne" ;ectangle/<K ;ect.lengt P 4K ;ect.brea!t P 12K ;ect.area/<K '*stem.out.println/S: e Area of rectangle of lengt S B;ect.lengt BS an! brea!t SB;ect.brea!t BS is SB;ect.a<K O O LM -utput M : e Area of rectangle of lengt 4 an! brea!t 12 is 112 ML

2.8rite a (rogra% to illustrate %ultilevel in)eritance


Multilevel in eritance is a java feature " ere t e properties of a class are in erite! b* a class " ic e3ten!s one or more classes " ic e3ten! its features... 03ample# public class A N public 'tring get?ame/<N return S;oc$*SK O O public class 8 e3ten!s A N public int getAge/< N return 2)K O O public class C e3ten!s 8 N public 'tring getA!!ress/<N return S?ort Carolina& U'ASK O O public class D e3ten!s C N public voi! print N Dept. of MCA programming in java Lab ---D.U.V

15 '*stem.out.println/get?ame/<<K '*stem.out.println/getAge/<<K '*stem.out.println/getA!!ress/<<K O O : is met o! "oul! print t e follo"ing in t e console# 2oc7$ 24 Nort) Carolina: =SA

3.8rite a (rogra% to i%(le%entation o! %ulti(le in)eritance using inter!aces in java.


'imple .rogram -n Aava for t e implementation of Multiple in eritance using interfaces to calculate t e area of a rectangle an! triangle LM Area -f ;ectangle an! :riangle using 1nterface M L interface Area N float compute/float 3& float *<K O class ;ectangle implements Area N public float compute/float 3& float *< N return/3 M *<K O O class :riangle implements Area N public float compute/float 3&float *< N return/3 M *L2<K O O class 1nterfaceArea N public static voi! main/'tring argsQR< N ;ectangle rect P ne" ;ectangle/<K :riangle tri P ne" :riangle/<K Area areaK Dept. of MCA programming in java Lab ---D.U.V

17 area P rectK '*stem.out.println/SArea -f ;ectangle P SB area.compute/1&2<<K area P triK '*stem.out.println/SArea -f :riangle P SB area.compute/1%&2<<K O O LMM -U:.U: MM Area -f ;ectangle P 2.% Area -f :riangle P 1%.% ML 8""93

1. Progra% to create (ac7ages in java


pac$age pac$K public class parent1 N public parent1/< N '*stem.out.println/S>elloS<K O voi! met o!/< N '*stem.out.println/S?eelima S<K O O

2.Progra% to de%onstrate t)e i%(orting and accessing t)e (ac7ages


1mport pac$age pac$K public class c il!1 e3ten!s parent1 N public c il!1/< N '*stem.out.println/S>elloS<K O voi! met o!/< Dept. of MCA programming in java Lab ---D.U.V

2% N '*stem.out.println/S?eelima .aramsett*S<K O public static voi! main/'tring srgQR< N c il!1 c 1Pne" c il!1/<K c 1.met o!/<K O 8""94

1.Progra% to create 4)read.


class MyThread extends Thread{ String s=null; MyThread(String s1){ s=s1; start(); public void run(){ System.out.println(s); public class !unThread{ public static void main(String args"#){ MyThread m1=new MyThread($Thread started....$);

2.Progra% to create Dulti(le 4)reads using runnable inter!ace.


class MyThread1 i ple ents !unna%le{ Thread t; String s=null; MyThread1(String s1){ s=s1; t=new Thread(this); t.start(); public void run(){ System.out.println(s);

Dept. of MCA

programming in java Lab ---D.U.V

21

public class !una%leThread{ public static void main(String args"#){ MyThread1 m1=new MyThread1($Thread started....$);

3. .rogram to create Mutiple : rea!s using : rea! class.


class MyThread1 i ple ents !unna%le{ Thread t; MyThread1(String s) { t=new Thread(this&s); t.start(); public void run() { !or(int i=';i();i**) { System.out.println($Thread +ame me()); tr" { Thread.sleep(1'''); catc#(./-eption e){

,$*Thread.-urrentThread().get+a

public class !unna%leThread1{ public static void main(String args"#) { System.out.println($Thread +ame ,$*Thread.-urrentThread().get+ame( )); MyThread1 m1=new MyThread1($My Thread 1$); MyThread1 m0=new MyThread1($My Thread 0$);

C#Hnis aTjava ;unnable: rea!1 : rea! 8""9

1.Progra% to i%(le%ent interBt)read co%%unication.


class ' are! N int numP%K boolean value P falseK s*nc roniEe! int get/< N if /valuePPfalse< tr* N "ait/<K Dept. of MCA programming in java Lab ---D.U.V

22 O catc /1nterrupte!03ception e< N '*stem.out.println/S1nterrupte!03ception caug tS<K O '*stem.out.println/Sconsume# S B num<K valuePfalseK notif*/<K return numK O s*nc roniEe! voi! put/int num< N if /valuePPtrue< tr* N "ait/<K O catc /1nterrupte!03ception e< N '*stem.out.println/S1nterrupte!03ception caug tS<K O t is.numPnumK '*stem.out.println/S.ro!uce# S B num<K valuePfalseK notif*/<K O O class .ro!ucer e3ten!s : rea! N ' are! sK .ro!ucer/' are! s< N t is.sPsK t is.start/<K O public voi! run/< N int iP%K s.put/BBi<K O O class Consumer e3ten!s : rea!N ' are! sK Consumer/' are! s< N t is.sPsK t is.start/<K O Dept. of MCA programming in java Lab ---D.U.V

23 public voi! run/< N s.get/<K O O public class 1nter: rea!N public static voi! main/'tringQR args< N ' are! sPne" ' are!/<K ne" .ro!ucer/s<K ne" Consumer/s<K O O -utput of t e .rogram# C#Hnis aTjavac 1nter: rea!.java C#Hnis aTjava 1nter: rea! .ro!uce# 1 consume# 1

$%Write &pplet

progra

to

describe

t#e

li!e

c"cle

o!

import 1a2a.applet.3pplet; import 1a2a.a4t.5raphi-s; 66+o need to e/tend 73pplet& sin-e 4e don8t add any -omponents; 664e 1ust paint. pu%li- -lass Simple e/tends 3pplet { String9u::er %u::er; pu%li- 2oid init() { %u::er = ne4 String9u::er(); addItem($initiali;ing... $); pu%li- 2oid start() { addItem($starting... $); pu%li- 2oid stop() { addItem($stopping... $); pu%li- 2oid destroy() { addItem($preparing :or unloading...$); pri2ate 2oid addItem(String ne4Word) {

Dept. of MCA

programming in java Lab ---D.U.V

2)
System.out.println(ne4Word); %u::er.append(ne4Word); repaint(); pu%li- 2oid paint(5raphi-s g) { 66<ra4 a !e-tangle around the applet8s display area. g.dra4!e-t('& '& getWidth() = 1& get>eight() = 1); 66<ra4 the -urrent string inside the re-tangle. g.dra4String(%u::er.toString()& )& 1));

,006 2#

Progra%s to 8rite a((lets to dra0 t)e various s)a(es. a<circle b<2ectangle c<Lines
import java.applet.MK import java.a"t.MK public class ' apColor e3ten!s AppletN int 3P3%%&*P1%%&rP+%K public voi! paint/9rap ics g<N g.setColor/Color.re!<K LLDra"ing line color is re! g.!ra"Line/3&3%%&2%%&1%<K g.setColor/Color.magenta<K g.!ra"'tring/SLineS&1%%&1%%<K g.!ra"-val/3-r&*-r&1%%&1%%<K g.setColor/Color.*ello"<K LLCill t e *ello" color in circle g.fill-val/ 3-r&*-r& 1%%& 1%% <K g.setColor/Color.magenta<K g.!ra"'tring/SCircleS&24+&1%%<K g.!ra";ect/)%%&+%&2%%&1%%<K g.setColor/Color.*ello"<K LLCill t e *ello" color in rectangel g.fill;ect/ )%%& +%& 2%%& 1%% <K g.setColor/Color.magenta<K g.!ra"'tring/S;ectangelS&)+%&1%%<K O O >ere is t e >:ML co!e of t e program# U>:MLT U>0ADT UL>0ADT Dept. of MCA programming in java Lab ---D.U.V

2+ U8-DJT U!iv alignPScenterST UA..L0: AL19? P SC0?:0;S C-D0 P S' apColor.classS ,1D:> P S5%%ST >019>: P S+%%STULA..L0:T UL!ivT UL8-DJT UL>:MLT

WEEK'

,rite a program to create an! manipulate t efollo"ing a<8uttons. b< C ec$bo3e group c< te3tareas an! te3tfiel! !<panels a9,(*e t+at ,reates t+e 31tt(&s a&* rea,ts t( 31tt(& ,/%,>s. 8#ereHs t+e 0+(/e .r('ram.9
//In initialization code: %1 = ne4 9utton(); %1.set?a%el($<isa%le middle %utton$); %0 = ne4 9utton($Middle %utton$);

Dept. of MCA

programming in java Lab ---D.U.V

22

%3 = ne4 9utton($.na%le middle %utton$); %3.disa%le(); . . . pu%li- %oolean a-tion(.2ent e& @%1e-t arg) { @%1e-t target = e.target; i: (target == %1) { 66They -li-Aed $<isa%le middle %utton$ %0.disa%le(); %1.disa%le(); %3.ena%le(); return true; i: (target == %3) { 66They -li-Aed $.na%le middle %utton$ %0.ena%le(); %1.ena%le(); %3.disa%le(); return true; return :alse;

b<c ec$bo39roup t e co!e creates bot groups of c ec$bo3es. ?ote t at onl* t e secon!& mutuall*-e3clusive group of c ec$bo3es is controlle! b* a C ec$bo39roup.
Banel p1& p0; Che-A%o/ -%1& -%0& -%3; 66These are independent -he-A%o/es. Che-A%o/ -%C& -%)& -%D; 66These -he-A%o/es are part o: a group. Che-A%o/5roup -%g; -%1 = ne4 Che-A%o/(); 66<e:ault state is $o::$ (:alse). -%1.set?a%el($Che-A%o/ 1$); -%0 = ne4 Che-A%o/($Che-A%o/ 0$); -%3 = ne4 Che-A%o/($Che-A%o/ 3$); -%3.setState(true); 66Set state to $on$ (true). . . . -%g = ne4 Che-A%o/5roup(); -%C = ne4 Che-A%o/($Che-A%o/ C$& -%g& :alse); 66initial state, o:: (:alse) -%) = ne4 Che-A%o/($Che-A%o/ )$& -%g& :alse); 66initial state, o:: -%D = ne4 Che-A%o/($Che-A%o/ D$& -%g& :alse); 66initial state, o::

-) //Where instance variables are defined: Te/tEield te/tEield; Te/t3rea te/t3rea; pu%li- 2oid init() { te/tEield = ne4 Te/tEield(0'); te/t3rea = ne4 Te/t3rea()& 0'); te/t3rea.set.dita%le(:alse); ...//Add the two components to the panel.

Dept. of MCA

programming in java Lab ---D.U.V

24
pu%li- %oolean a-tion(.2ent e2t& @%1e-t arg) { String te/t = te/tEield.getTe/t(); te/t3rea.appendTe/t(te/t * $Fn$); te/tEield.sele-t3ll(); return true; d)>ereGs

an e3ample of using a .anel instance to ol! some Components#


ne4 Banel(); 9utton($9utton 1$)); 9utton($9utton 0$)); 9utton($9utton 3$));

Banel p1 = p1.add(ne4 p1.add(ne4 p1.add(ne4

>ereGs an e3ample of a .anel subclass t at !ra"s a frame aroun! its contents.


-lass Eramed3rea e/tends Banel { pu%li- Eramed3rea(Coordinates<emo -ontroller) { ...//Set the layout manager. //Add any Components this anel contains... 66.nsure that no Component is pla-ed on top o: the :rame. 66The inset 2alues 4ere determined %y trail and error. pu%li- Insets insets() { return ne4 Insets(C&C&)&)); 66<ra4 the :rame at this Banel8s edges. pu%li- 2oid paint(5raphi-s g) { <imension d = si;e(); Color %g = get9a-Aground(); g.setColor(%g); g.dra43<!e-t('& '& d.4idth = 1& d.height = 1& true); g.dra43<!e-t(3& 3& d.4idth = G& d.height = G& :alse);

8""9 1

1.Progra% to de%onstrate Douse "vent

3 sel:=-ontained 7Banel -lass that handles its o4n mouse e2ents. import 1a2a.a4t.H; import 1a2a.a4t.e2ent.H; import 1a2a/.s4ing.H; pu%li- -lass Sel:ContainedBanel e/tends 7Banel { pri2ate int /1& y1& /0& y0;

Dept. of MCA

programming in java Lab ---D.U.V

25 pu%li- Sel:ContainedBanel() { addMouse?istener( ne4 Mouse3dapter() { pu%li- 2oid mouseBressed( Mouse.2ent e ) { /1 = e.getI(); y1 = e.getJ(); pu%li- 2oid mouse!eleased( Mouse.2ent e ) { /0 = e.getI(); y0 = e.getJ(); repaint(); ); addMouseMotion?istener( ne4 MouseMotion3dapter() { pu%li- 2oid mouse<ragged( Mouse.2ent e ) { /0 = e.getI(); y0 = e.getJ(); repaint(); ); pu%li- <imension getBre:erredSi;e() { return ne4 <imension( 1)'& 1'' ); pu%li- 2oid paintComponent( 5raphi-s g ) { super.paintComponent( g ); g.dra4@2al( Math.min( /1& /0 )& Math.min( y1& y0 )& Math.a%s( /1 = /0 )& Math.a%s( y1 = y0 ) );

66 Creating a sel:=-ontained su%-lass o: 7Banel 66 that pro-esses its o4n mouse e2ents. Dept. of MCA programming in java Lab ---D.U.V

27 import 1a2a.a4t.H; import 1a2a.a4t.e2ent.H; import 1a2a/.s4ing.H; pu%li- -lass Sel:ContainedBanelTest e/tends 7Erame { pri2ate Sel:ContainedBanel myBanel; pu%li- Sel:ContainedBanelTest() { myBanel = ne4 Sel:ContainedBanel(); myBanel.set9a-Aground( Color.yello4 ); Container - = getContentBane(); -.set?ayout( ne4 Elo4?ayout() ); -.add( myBanel ); addMouseMotion?istener( ne4 MouseMotion?istener() { pu%li- 2oid mouse<ragged( Mouse.2ent e ) { setTitle( $<ragging, /=$ * e.getI() * $; y=$ * e.getJ() ); pu%li- 2oid mouseMo2ed( Mouse.2ent e ) { setTitle( $Mo2ing, /=$ * e.getI() * $; y=$ * e.getJ() ); ); setSi;e( 3''& 0'' ); sho4(); pu%li- stati- 2oid main( String args"# ) { Sel:ContainedBanelTest app = ne4 Sel:ContainedBanelTest(); app.addWindo4?istener( ne4 Windo43dapter() { pu%li- 2oid 4indo4Closing( Windo4.2ent e ) { System.e/it( ' );

Dept. of MCA

programming in java Lab ---D.U.V

3% );

2.Progra% to )andle 9e$"vent


pu%li- -lass Key.2ent<emo ... implements Key?istener ... { ...//where initialization occurs: typing3rea = ne4 7Te/tEield(0'); typing3rea.addKey?istener(this); 66Ln-omment this i: you 4ish to turn o:: :o-us 66tra2ersal. The :o-us su%system -onsumes 66:o-us tra2ersal Aeys& su-h as Ta% and Shi:t Ta%. 66I: you un-omment the :ollo4ing line o: -ode& this 66disa%les :o-us tra2ersal and the Ta% e2ents 66%e-ome a2aila%le to the Aey e2ent listener. 66typing3rea.setEo-usTra2ersalKeys.na%led(:alse); ... 6HH >andle the Aey typed e2ent :rom the te/t :ield. H6 pu%li- 2oid AeyTyped(Key.2ent e) { displayIn:o(e& $K.J TJB.<, $); 6HH >andle the Aey=pressed e2ent :rom the te/t :ield. H6 pu%li- 2oid AeyBressed(Key.2ent e) { displayIn:o(e& $K.J B!.SS.<, $); 6HH >andle the Aey=released e2ent :rom the te/t :ield. H6 pu%li- 2oid Aey!eleased(Key.2ent e) { displayIn:o(e& $K.J !.?.3S.<, $); ... pri2ate 2oid displayIn:o(Key.2ent e& String AeyStatus){ 66Jou should only rely on the Aey -har i: the e2ent 66is a Aey typed e2ent. int id = e.getI<(); String AeyString; i: (id == Key.2ent.K.JMTJB.<) { -har - = e.getKeyChar(); AeyString = $Aey -hara-ter = 8$ * - * $8$; else { int AeyCode = e.getKeyCode(); AeyString = $Aey -ode = $ * AeyCode * $ ($ * Key.2ent.getKeyTe/t(AeyCode) * $)$; int modi:iers./ = e.getModi:iers./(); String modString = $e/tended modi:iers = $ * modi:iers./; String tmpString = Key.2ent.getModi:iers./Te/t(modi:iers./); i: (tmpString.length() N ') { modString *= $ ($ * tmpString * $)$; else { modString *= $ (no e/tended modi:iers)$;

Dept. of MCA

programming in java Lab ---D.U.V

31

String a-tionString = $a-tion AeyO $; i: (e.is3-tionKey()) { a-tionString *= $J.S$; else { a-tionString *= $+@$; String lo-ationString = $Aey lo-ation, $; int lo-ation = e.getKey?o-ation(); i: (lo-ation == Key.2ent.K.JM?@C3TI@+MST3+<3!<) { lo-ationString *= $standard$; else i: (lo-ation == Key.2ent.K.JM?@C3TI@+M?.ET) { lo-ationString *= $le:t$; else i: (lo-ation == Key.2ent.K.JM?@C3TI@+M!I5>T) { lo-ationString *= $right$; else i: (lo-ation == Key.2ent.K.JM?@C3TI@+M+LMB3<) { lo-ationString *= $numpad$; else { 66 (lo-ation == Key.2ent.K.JM?@C3TI@+ML+K+@W+) lo-ationString *= $unAno4n$; ...//!isplay information about the "ey#vent...

3.8rite a (rogra% to illustrate t)e Inner Classes


1nner Class 03ample :o see an inner class in use& letGs first consi!er an arra*. 1n t e follo"ing e3ample& "e "ill create an arra*& fill it "it integer values an! t en output onl* values of even in!ices of t e arra* in ascen!ing or!er.

public class Data'tructure N LLcreate an arra* private final static int '1V0 P 1+K private intQR arra*-f1nts P ne" intQ'1V0RK

public Data'tructure/< N Dept. of MCA programming in java Lab ---D.U.V

32 LLfill t e arra* "it ascen!ing integer values for /int i P %K i U '1V0K iBB< N arra*-f1ntsQiR P iK O O

public voi! print0ven/< N LLprint out values of even in!ices of t e arra* 1nner0ven1terator iterator P t is.ne" 1nner0ven1terator/<K " ile /iterator. as?e3t/<< N '*stem.out.println/iterator.get?e3t/< B S S<K O O

LLinner class implements t e 1terator pattern private class 1nner0ven1terator N LLstart stepping t roug t e arra* from t e beginning private int ne3t P %K

public boolean as?e3t/< N LLc ec$ if a current element is t e last in t e arra* return /ne3t UP '1V0 - 1<K O

Dept. of MCA

programming in java Lab ---D.U.V

33 public int get?e3t/< N LLrecor! a value of an even in!e3 of t e arra* int retValue P arra*-f1ntsQne3tRK LLget t e ne3t even element ne3t BP 2K return retValueK O O

public static voi! main/'tring sQR< N LLfill t e arra* "it integer values an! print out onl* values of even in!ices Data'tructure !s P ne" Data'tructure/<K !s.print0ven/<K O O : e output is# % 2 ) 2 5 1% 12 1) .,006 7

8rite a (rogra% t)at illustrate t)e boarder la$out.


: e (orderLa"out manager arranges components "it in specifie! regions of a container. Vali! regions are S?ort S& S'out S& S0astS& S,estS& an! SCenterS. 8elo" s o"s an e3ample of t e (orderLa"out la*out manager.

Dept. of MCA

programming in java Lab ---D.U.V

3)

?otice t at components place! "it in a region of t e frame are e3ten!e! to fit t at region. -nl* one component s oul! be positione! in a particular region at a time. 1f more t an one component is a!!e! to a region& t e most recent component "ill obscure t e previousl* a!!e! ones.: e co!e for (orderLa"outExa ple of above Cigure. 'ince t e !efault la*out manager for frames is (orderLa"out& "e !o not e3plicitl* set t e la*out manager. public class 8or!erLa*out03ample e3ten!s Crame N public 8or!erLa*out03ample/'tring title< N super/title<K a!!/S?ort S& ne" 8utton/S?ort S<<K a!!/S'out S& ne" 8utton/S'out S<<K a!!/S0astS& ne" 8utton/S0astS<<K a!!/S,estS& ne" 8utton/S,estS<<K a!!/SCenterS& ne" 8utton/SCenterS<<K O public static voi! main/'tringQR args< N 8or!erLa*out03ample ble P ne" 8or!erLa*out03ample/S8or!erLa*out03ampleS<K ble.set'iEe/3%%& 2%%<K ble.s o"/<K OO Dept. of MCA programming in java Lab ---D.U.V

3+

,006 1% 1.Progra% to i%(le%ent 4)read s$nc)roniEation


4)e source code o! t)e T#readS"nc#roni)ation (rogra%.
-lass ThreadSyn-hroni;ation { pu%li- stati- 2oid main(String args"#) { MyThread thread1 = ne4 MyThread($thread1, $); MyThread thread0 = ne4 MyThread($thread0, $); thread1.start(); thread0.start(); %oolean thread1Is3li2e = true; %oolean thread0Is3li2e = true; do { i: (thread1Is3li2e PP Qthread1.is3li2e()) { thread1Is3li2e = :alse; System.out.println($Thread 1 is dead.$);

i: (thread0Is3li2e PP Qthread0.is3li2e()) { thread0Is3li2e = :alse; System.out.println($Thread 0 is dead.$);

4hile(thread1Is3li2e RR thread0Is3li2e);

Dept. of MCA

programming in java Lab ---D.U.V

32
-lass MyThread e/tends Thread { stati- String message"# = { $7a2a$& $is$& $hot&$& $aromati-&$& $and$& $in2igorating.$ ;

pu%li- MyThread(String id) { super(id);

pu%li- 2oid run() { Syn-hroni;ed@utput.display?ist(get+ame()&message);

2oid randomWait() { try { sleep((long)(3'''HMath.random())); -at-h (Interrupted./-eption /) { System.out.println($InterruptedQ$);

-lass Syn-hroni;ed@utput

Dept. of MCA

programming in java Lab ---D.U.V

34
{ pu%li- stati- syn-hroni;ed 2oid display?ist(String name&String list"#) { :or(int i=';i(list.length;**i) { MyThread t = (MyThread) Thread.-urrentThread(); t.randomWait(); System.out.println(name*list"i#);

Compile an! run t e program before going on "it its anal*sis. Jou mig t be surprise! at t e results t at *ouGve obtaine!. >ere are t e results of an e3ample run on m* s*stem#
C,F1a2aF1dgF-h'SN1a2a ThreadSyn-hroni;ation thread1, 7a2a thread1, is thread1, hot& thread1, aromati-& thread1, and thread1, in2igorating. Thread 1 is dead. thread0, 7a2a thread0, is thread0, hot& thread0, aromati-& thread0, and thread0, in2igorating. Thread 0 is dead.

?o" e!it ThreadSyn-hroni;ation.1a2a an! !elete t e syn-hroni;ed $e*"or! in t e !eclaration of t e display?ist() met o! of class Syn-hroni;ed@utput. 'ave ThreadSyn-hroni;ation.1a2a& recompile it& an! rerun it "it t e ne" c ange in place. Jou ma* no" get output similar to t is#
C,F1a2aF1dgF-h'SN1a2a ThreadSyn-hroni;ation thread0, 7a2a thread1, 7a2a thread1, is thread0, is thread0, hot& thread0, aromati-& thread1, hot& thread0, and thread0, in2igorating.

Dept. of MCA

programming in java Lab ---D.U.V

35
Thread 0 thread1, thread1, thread1, Thread 1 is dead. aromati-& and in2igorating. is dead.

2..rogram to implement : rea! .riorit*. LMM M : is class !emonstrates t e use of t rea!s. : e main/< met o! is t e initial M met o! invo$e! b* t e interpreter. 1t !efines an! starts t"o more t rea!s an! M t e t ree t rea!s run at t e same time. ?ote t at t is class e3ten!s : rea! M an! overri!es its run/< met o!. : at met o! provi!es t e bo!* of one of t e M t rea!s starte! b* t e main/< met o! ML public class : rea!Demo e3ten!s : rea! N LMM M : is met o! overri!es t e run/< met o! of : rea!. 1t provi!es t e bo!* for M t is t rea!. ML public voi! run/< N for /int i P %K i U +K iBB< compute/<K O

LMM Dept. of MCA programming in java Lab ---D.U.V

37 M : is main met o! creates an! starts t"o t rea!s in a!!ition to t e initial M t rea! t at t e interpreter creates to invo$e t e main/< met o!. ML public static voi! main/'tringQR args< N LL Create t e first t rea!# an instance of t is class. 1ts bo!* is LL t e run/< met o! above : rea!Demo t rea!1 P ne" : rea!Demo/<K

LL Create t e secon! t rea! b* passing a ;unnable object to t e LL : rea!/< construtor. : e bo!* of t is t rea! is t e run/< met o! LL of t e anon*mous ;unnable object belo". : rea! t rea!2 P ne" : rea!/ne" ;unnable/< N public voi! run/< N for /int i P %K i U +K iBB< compute/<K O O<K

LL 'et t e priorities of t ese t"o t rea!s& if an* are specifie! if /args.lengt TP 1< t rea!1.set.riorit*/1nteger.parse1nt/argsQ%R<<K if /args.lengt TP 2< t rea!2.set.riorit*/1nteger.parse1nt/argsQ1R<<K

Dept. of MCA

programming in java Lab ---D.U.V

)% LL 'tart t e t"o t rea!s running t rea!1.start/<K t rea!2.start/<K

LL : is main/< met o! is run b* t e initial t rea! create! b* t e LL Aava interpreter. ?o" t at t rea! !oes some stuff& too. for /int i P %K i U +K iBB< compute/<K

LL ,e coul! "ait for t e t rea!s to stop running "it t ese lines LL 8ut t e* arenGt necessar* ere& so "e !onGt bot er. LL tr* N LL t rea!1.join/<K LL t rea!2.join/<K LL O catc /1nterrupte!03ception e< NO

LL : e Aava VM e3its onl* " en t e main/< met o! returns& an! " en all LL t rea!s stop running /e3cept for !aemon t rea!s--see setDaemon/<<. O

LL : rea!Local objects respresent a value accesse! "it get/< an! set/<. LL 8ut t e* maintain a !ifferent value for eac t rea!. : is object $eeps LL trac$ of o" man* times eac t rea! as calle! compute/<. static : rea!Local numcalls P ne" : rea!Local/<K Dept. of MCA programming in java Lab ---D.U.V

)1

LMM : is is t e !umm* met o! our t rea!s all call ML static s*nc roniEe! voi! compute/< N LL Cigure out o" man* times "eGve been calle! b* t e current t rea! 1nteger n P /1nteger< numcalls.get/<K if /n PP null< n P ne" 1nteger/1<K else n P ne" 1nteger/n.intValue/< B 1<K numcalls.set/n<K

LL Displa* t e name of t e t rea!& an! t e number of times calle! '*stem.out.println/: rea!.current: rea!/<.get?ame/< B S# S B n<K

LL Do a long computation& simulating a Scompute-boun!S t rea! for /int i P %& j P %K i U 1%%%%%%K iBB< j BP iK

LL Alternativel*& "e can simulate a t rea! subject to net"or$ or 1LLL !ela*s b* causing it to sleep for a ran!om amount of time# tr* N LL 'top running for a ran!om number of millisecon!s : rea!.sleep//int< /Mat .ran!om/< M 1%% B 1<<K O catc /1nterrupte!03ception e< N Dept. of MCA programming in java Lab ---D.U.V

)2 O

LL 0ac t rea! politel* offers t e ot er t rea!s a c ance to run. LL : is is important so t at a compute-boun! t rea! !oes not SstarveS LL ot er t rea!s of e(ual priorit*. : rea!.*iel!/<K O O

Dept. of MCA

programming in java Lab ---D.U.V

)3

*iva +uestions , &nswers

/uestion6 , at !o *ou un!erstan! b* '*nc roniEationW Ans0er6 '*nc roniEation is a process of controlling t e access of s are! resources b* t e multiple t rea!s in suc a manner t at onl* one t rea! can access one resource at a time. 1n non s*nc roniEe! multit rea!e! application& it is possible for one t rea! to mo!if* a s are! object " ile anot er t rea! is in t e process of using or up!ating t e objectGs value. '*nc roniEation prevents suc t*pe of !ata corruption. ".g. S$nc)roniEing a !unction6 public s*nc roniEe! voi! Met o!1 /< N LL Appropriate met o!-relate! co!e. O ".g. S$nc)roniEing a bloc7 o! code inside a !unction6 public m*Cunction /<N s*nc roniEe! /t is< N LL '*nc roniEe! co!e ere. O O /uestion6 , at is Collection A.1W Ans0er6 : e Collection A.1 is a set of classes an! interfaces t at support operation on collections of objects. : ese classes an! interfaces are more fle3ible& more po"erful& an! more regular t an t e vectors& arra*s& an! as tables if effectivel* replaces. "#a%(le o! classes# -as#Set& -as#.ap& &rra"List& Lin/edList& TreeSet an! Tree.ap. "#a%(le o! inter!aces# 0ollection& Set& List an! .ap% /uestion6 1s 1terator a Class or 1nterfaceW , at is its useW Ans0er6 1terator is an interface " ic is use! to step t roug t e elements of a Collection. /uestion6 , at is similaritiesL!ifference bet"een an Abstract class an! 1nterfaceW Ans0er6 Differences are as follo"s#

1nterfaces provi!e a form of multiple in eritance. A class can e3ten! onl* one ot er class. 1nterfaces are limite! to public met o!s an! constants "it no implementation. Abstract classes can ave a partial implementation& protecte! parts& static met o!s& etc. A Class ma* implement several interfaces. 8ut in case of abstract class& a class ma* e3ten! onl* one abstract class. 1nterfaces are slo" as it re(uires e3tra in!irection to to fin! correspon!ing met o! in in t e actual class. Abstract classes are fast. programming in java Lab ---D.U.V

Dept. of MCA

)) 'imilarities#

?eit er Abstract classes or 1nterface can be instantiate!.

/uestion6 >o" to !efine an Abstract classW Ans0er6 A class containing abstract met o! is calle! Abstract class. An Abstract class canGt be instantiate!. 03ample of Abstract class# abstract class testAbstractClass N protecte! 'tring m*'tringK public 'tring getM*'tring/< N return m*'tringK O public abstract string an*AbstractCunction/<K O /uestion6 >o" to !efine an 1nterfaceW Ans0er6 1n Aava 1nterface !efines t e met o!s but !oes not implement t em. 1nterface can inclu!e constants. A class t at implements t e interfaces is boun! to implement all t e met o!s !efine! in 1nterface. 0maple of 1nterface# public interface sample1nterface N public voi! function-ne/<K public long C-?':A?:I-?0 P 1%%%K O /uestion6 03plain t e user !efine! 03ceptionsW Ans0er6 User !efine! 03ceptions are t e separate 03ception classes !efine! b* t e user for specific purpose!. An user !efine! can create! b* simpl* sub-classing it to t e 03ception class. : is allo"s custom e3ceptions to be generate! /using t ro"< an! caug t in t e same "a* as normal e3ceptions. 03ample# class m*Custom03ception e3ten!s 03ception N LL : e class simpl* as to e3ist to be an e3ception O /uestion6 03plain t e ne" Ceatures of AD8C 2.% Core A.1W Ans0er6 : e AD8C 2.% A.1 inclu!es t e complete AD8C A.1& " ic inclu!es bot core an! -ptional .ac$age A.1& an! provi!es in!uctrial-strengt !atabase computing capabilities. ?e" Ceatures in AD8C 2.% Core A.1# Dept. of MCA programming in java Lab ---D.U.V

)+

'crollable result sets- using ne" met o!s in t e ;esult'et interface allo"s programmaticall* move t e to particular ro" or to a position relative to its current position AD8C 2.% Core A.1 provi!es t e 8atc Up!ates functionalit* to t e java applications. Aava applications can no" use t e ;esult'et.up!ateDDD met o!s. ?e" !ata t*pes - interfaces mapping t e 'XL3 !ata t*pes Custom mapping of user-!efine! t*pes /U:Ds< Miscellaneous features& inclu!ing performance ints& t e use of c aracter streams& full precision for java.mat .8igDecimal values& a!!itional securit*& an! support for time Eones in !ate& time& an! timestamp values.

/uestion6 03plain garbage collectionW Ans0er6 9arbage collection is one of t e most important feature of Aava. 9arbage collection is also calle! automatic memor* management as AVM automaticall* removes t e unuse! variablesLobjects /value is null< from t e memor*. User program cannGt !irectl* free t e object from memor*& instea! it is t e job of t e garbage collector to automaticall* free t e objects t at are no longer reference! b* a program. 0ver* class in erits !inaliEe;< met o! from java.lang.Object& t e finaliEe/< met o! is calle! b* garbage collector " en it !etermines no more references to t e object e3ists. 1n Aava& it is goo! i!ea to e3plicitl* assign null into a variable " en no more in use. 1 Aava on calling S$ste%.gc;< an! 2unti%e.gc;<: AVM tries to rec*cle t e unuse! objects& but t ere is no guarantee " en all t e objects "ill garbage collecte!. /uestion6 >o" *ou can force t e garbage collectionW Ans0er6 9arbage collection automatic process an! canGt be force!. /uestion6 , at is --.'W Ans0er6 --. is t e common abbreviation for -bject--riente! .rogramming. /uestion6 Describe t e principles of --.'. Ans0er6 : ere are t ree main principals of oops " ic are calle! .ol*morp ism& 1n eritance an! 0ncapsulation. /uestion6 03plain t e 0ncapsulation principle. Ans0er6 0ncapsulation is a process of bin!ing or "rapping t e !ata an! t e co!es t at operates on t e !ata into a single entit*. : is $eeps t e !ata safe from outsi!e interface an! misuse. -ne "a* to t in$ about encapsulation is as a protective "rapper t at prevents co!e an! !ata from being arbitraril* accesse! b* ot er co!e !efine! outsi!e t e "rapper.

Dept. of MCA

programming in java Lab ---D.U.V

)2 /uestion6 03plain t e 1n eritance principle. Ans0er6 1n eritance is t e process b* " ic one object ac(uires t e properties of anot er object. /uestion6 03plain t e .ol*morp ism principle. Ans0er6 : e meaning of .ol*morp ism is somet ing li$e one name man* forms. .ol*morp ism enables one entit* to be use! as as general categor* for !ifferent t*pes of actions. : e specific action is !etermine! b* t e e3act nature of t e situation. : e concept of pol*morp ism can be e3plaine! as Sone interface& multiple met o!sS. /uestion6 03plain t e !ifferent forms of .ol*morp ism. Ans0er6 Crom a practical programming vie"point& pol*morp ism e3ists in t ree !istinct forms in Aava#

Met o! overloa!ing Met o! overri!ing t roug in eritance Met o! overri!ing t roug t e Aava interface

/uestion6 , at are Access 'pecifiers available in AavaW Ans0er6 Access specifiers are $e*"or!s t at !etermines t e t*pe of access to t e member of a class. : ese are# .ublic .rotecte! .rivate Defaults

/uestion6 Describe t e "rapper classes in Aava. Ans0er6 ,rapper class is "rapper aroun! a primitive !ata t*pe. An instance of a "rapper class contains& or "raps& a primitive value of t e correspon!ing t*pe. Collo"ing table lists t e primitive t*pes an! t e correspon!ing "rapper classes# Pri%itive
boolean b$te c)ar double !loat

8ra((er
java.lang.Foolean java.lang.F$te java.lang.C)aracter java.lang.'ouble java.lang.>loat

Dept. of MCA

programming in java Lab ---D.U.V

)4
int long s)ort void java.lang.Integer java.lang.Long java.lang.S)ort java.lang..oid

/uestion6 ;ea! t e follo"ing program# public class test N public static voi! main/'tring QR args< N int 3 P 3K int * P 1K if /3 P *< '*stem.out.println/S?ot e(ualS<K else '*stem.out.println/S0(ualS<K O O , at is t e resultW A. : e output is Y0(ualZ 8. : e output in Y?ot 0(ualZ C. An error at S if /3 P *<S causes compilation to fall. D. : e program e3ecutes but no output is s o" on consol Ans0er6 C /uestion6 " at is t e class variables W Ans0er6 , en "e create a number of objects of t e same class& t en eac object "ill s are a common cop* of variables. : at means t at t ere is onl* one cop* per class& no matter o" man* objects are create! from it. Class variables or static variables are !eclare! "it t e static $e*"or! in a class& but min! it t at it s oul! be !eclare! outsi!e outsi!e a class. : ese variables are store! in static memor*. Class variables are mostl* use! for constants& variable t at never c ange its initial value. 'tatic variables are al"a*s calle! b* t e class name. : is variable is create! " en t e program starts i.e. it is create! before t e instance is create! of class b* using ne" operator an! gets !estro*e! " en t e programs stops. : e scope of t e class variable is same a instance variable. : e class variable can be !efine! an*" ere at class level "it t e $e*"or! static. 1t initial value is same as instance variable. , en t e class variable is !efine! as int t en itGs initial value is b* !efault Eero& " en !eclare! boolean its !efault value is false an! null for object references. Class variables are associate! "it t e class& rat er t an "it an* object. /uestion6 , at is t e !ifference bet"een t e instanceof an! getclass& t ese t"o are same or not W Ans0er6 instanceof is a operator& not a function " ile getClass is a met o! of java.lang.-bject class. Consi!er a con!ition " ere "e use if/o.getClass/<.get?ame/<.e(uals/Sjava.lang.Mat S<<N O Dept. of MCA programming in java Lab ---D.U.V

)5 : is met o! onl* c ec$s if t e classname "e ave passe! is e(ual to java.lang.Mat . : e class java.lang.Mat is loa!e! b* t e bootstrap ClassLoa!er. : is class is an abstract class.: is class loa!er is responsible for loa!ing classes. 0ver* Class object contains a reference to t e ClassLoa!er t at !efines. getClass/< met o! returns t e runtime class of an object. 1t fetc es t e java instance of t e given full* (ualifie! t*pe name. : e co!e "e ave "ritten is not necessar*& because "e s oul! not compare getClass.get?ame/<. : e reason be in! it is t at if t e t"o !ifferent class loa!ers loa! t e same class but for t e AVM& it "ill consi!er bot classes as !ifferent classes so& "e canGt compare t eir names. 1t can onl* gives t e implementing class but canGt compare a interface& but instanceof operator can. : e instanceof operator compares an object to a specifie! t*pe. ,e can use it to test if an object is an instance of a class& an instance of a subclass& or an instance of a class t at implements a particular interface. ,e s oul! tr* to use instanceof operator in place of getClass/< met o!. ;emember instanceof opeator an! getClass are not same. :r* t is e3ample& it "ill elp *ou to better un!erstan! t e !ifference bet"een t e t"o. 1nterface oneN O Class :"o implements one N O Class : ree implements one N O public class :est N public static voi! main/'tring argsQR< N one test1 P ne" :"o/<K one test2 P ne" : ree/<K '*stem.out.println/test1 instanceof one<K LLtrue '*stem.out.println/test2 instanceof one<K LLtrue '*stem.out.println/:est.getClass/<.e(uals/test2.getClass/<<<K LLfalse O O /uestion6, * t rea!s bloc$ or enters to "aiting state on 1L-W A : rea!s enters to "aiting state or bloc$ on 1L- because ot er t rea!s can e3ecute " ile t e 1L- operations are performe!. 2 X , at are transient variables in javaW A :ransient variables are variable t at cannot be serialiEe!. /uestion6 >o" -bserver an! -bservable are use!W A 'ubclass of -bservable class maintain a list of observers. , enever an -bservable object is up!ate!& it invo$es t e up!ate/< met o! of eac of its observers to notif* t e observers t at it as a c ange! state. An observer is an* object t at implements t e interface -bserver. /uestion6 , at is s*nc roniEation A '*nc roniEation is t e abilit* to control t e access of multiple t rea!s to s are! resources. '*nc roniEation stops multit rea!ing. ,it s*nc roniEation & at a time onl* one t rea! "ill be able to access a s are! resource. Dept. of MCA programming in java Lab ---D.U.V

)7 /uestion6 , at is List interface W Ans0er6 List is an or!ere! collection of objects. /uestion6, at is a Vector Ans"er# Vector is a gro" able arra* of objects. /uestion6 , at is t e !ifference bet"een *iel!/< an! sleep/<W Ans0er , en a object invo$es *iel!/< it returns to rea!* state. 8ut " en an object invo$es sleep/< met o! enters to not rea!* state. /uestion6 , at are ,rapper Classes W Ans0er6 : e* are "rappers to primitive !ata t*pes. : e* allo" us to access primitives as objects. /uestion #Can "e call finaliEe/< met o! W Ans0er Jes. ?obo!* "ill stop us to call an* met o! & if it is accessible in our class. 8ut a garbage collector cannot call an objectGs finaliEe met o! if t at object is reac able. /uestion , at is t e !ifference bet"een time slicing an! preemptive sc e!uling W Ans0er61n preemptive sc e!uling& ig est priorit* tas$ continues e3ecution till it enters a not running state or a ig er priorit* tas$ comes into e3istence. 1n time slicing& t e tas$ continues its e3ecution for a pre!efine! perio! of time an! reenters t e pool of rea!* tas$s. /uestion , at is t e initial state of a t rea! " en it is create! an! starte!W Ans0er : e t rea! is in rea!* state. /uestion Can "e !eclare an anon*mous class as bot e3ten!ing a class an! implementing an interfaceW Ans0er# ?o. An anon*mous class can e3ten! a class or implement an interface& but it cannot be !eclare! to !o bot /uestion , at are t e !ifferences bet"een boolean [ operator an! [ operatorA Ans0er6, en an e3pression containing t e [ operator is evaluate!& bot operan!s are evaluate!. An! t e [ operator is applie! to t e operan!. , en an e3pression containing [[ operator is evaluate!& t e first operan! is evaluate!. 1f t e first operan! returns a value of true t en onl* t e secon! operan! is evaluate! ot er"ise t e secon! part "ill not get e3ecute!. [[ is also calle! s ort cut an!. /uestion , at is t e use of t e finall* bloc$W Ans0erCinall* is t e bloc$ of co!e t at e3ecutes al"a*s. : e co!e in finall* bloc$ "ill e3ecute even if an e3ception is occurre!. finall* "ill not e3ecute " en t e user calls '*stem.e3it/<. /uestion , at is an abstract met o! W Ans0erAn abstract met o! is a met o! t at !onGt ave a bo!*. 1t is !eclare! "it mo!ifier abstract.

Dept. of MCA

programming in java Lab ---D.U.V

+%

1E2E1EN0ES,
Text (oo/s: 1.<ietel&TInternet and 4orld 4ide 4e%, >o4 to programT. 0.Batri-A +aughton &>er2ert S-hildt&TComplete !e:eren-e 1a2a0T3e&TM> 3. 7oel SAlar UBrin-iples o: We% <esignT&ViAas !e:eren-e 9ooAs, 1. >ans 9ergstan&T 7a2a Ser2er BagesT&B.3 0. Se%esta U Brogramming the World Wide We%T.B.3 3. !eeta Sahoo&5angan Sahoo.T7a2a 0 the -omplete re:eren-e 9ooAT&5algotia.

Dept. of MCA

programming in java Lab ---D.U.V

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy