You are on page 1of 187

J.E.D.I.

Introduction to Programming II

Version 2.0 May 2006

Introduction to Programming II

Page 1

J.E.D.I.

Author Rebecca Ong Team Joyce A estro !"orence #a"agtas Romme" !eria Rebecca Ong Jo$n Pau" Petines %un Microsystems %un P$i"i&&ines

Requirements For the Laboratory Exercises


Minimum Hardware Con iguration

Microso t !indows o"erating systems '

Processor' (00 M)* Inte" Pentium III +or,station or e-ui a"ent Memory' ./0 megabytes #is$ s"ace' 12( megabytes o1 1ree dis, s&ace Processor* (00 M)* 2"tra 603 %un#"ade 1(03 or e-ui a"ent +or,station Memory' (12 megabytes #is$ s"ace' 1(0 megabytes o1 1ree dis, s&ace Processor* AMD O&teron 100 series %un 2"tra 20 +or,station or e-ui a"ent Memory' (12 megabytes #is$ s"ace* 1(0 megabytes o1 1ree dis, s&ace Processor' (00 M)* Inte" Pentium III +or,station or e-ui a"ent Memory' ./0 megabytes #is$ s"ace* 12( megabytes o1 1ree dis, s&ace Processor' Po+erP4 50 Memory' (12 megabytes

%o&arisTM o"erating system '%PARC (ersion)*

%o&arisTM o"erating system 'x+, (ersion)*

Linux o"erating system '

Macintosh -% . o"erating system*

#is$ s"ace' 12( megabytes o1 1ree dis, s&ace Recommended Hardware Con iguration

Microso t !indows o"erating systems ' Processor' 6/0 M)* Inte" Pentium III +or,station or e-ui a"ent Memory' (12 megabytes #is$ s"ace' 12( megabytes o1 1ree dis, s&ace Processor' 2"tra%PAR4 IIIi 1.( 5)* %un#"ade 1(00 +or,station or e-ui a"ent Memory' 1 gigabyte #is$ s"ace' 1(0 megabytes o1 1ree dis, s&ace Processor' AMD O&teron 100 series %un 2"tra 20 +or,station or e-ui a"ent Memory' 1 gigabyte #is$ s"ace* 1(0 megabytes o1 1ree dis, s&ace Processor' /00 M)* Inte" Pentium III +or,station or e-ui a"ent Memory' (12 megabytes #is$ s"ace* /01 megabytes o Processor' Po+erP4 5( Memory' 1 gigabyte ree dis$ s"ace

%o&arisTM o"erating system '%PARC (ersion)*

%o&arisTM o"erating system 'x+, (ersion)*

Linux o"erating system '

Macintosh -% . o"erating system*

#is$ s"ace' 12( megabytes o1 1ree dis, s&ace -"erating %ystem 7et#eans IDE runs on o&erating systems t$at su&&ort t$e Ja a8M VM. #e"o+ is a "ist o1 &"at1orms t$at 7et#eans IDE $as been tested on.

Mac O% : 10.0 %o tware 7et#eans IDE runs on t$e J2%E JD@ (.0 ;Ja a8M 2 JD@3 %tandard Edition>3 +$ic$ consists o1 t$e Ja a Runtime En ironment &"us de e"o&ers too"s 1or com&i"ing3 debugging3 and running a&&"ications +ritten in t$e Ja a8M "anguage. 7et#eans IDE (.0 $as a"so runs on J2%E %D@ ersion 1.0.23 but it $as on"y been tested on JD@ (.0. !or more in1ormation3 &"ease isit' $tt&'AA+++.netbeans.orgAcommunityAre"easesA(0Are"notes.$tm"

Microso1t 9indo+s :P Pro1essiona" %P2 %o"aris o&erating system ;%PAR4< and =/6 P"at1orm Editions> ersions /3 ?3 and 10 Red )at !edora 4ore .

Tab&e o Contents
1 Re ie+ o1 #asic 4once&ts in Ja a........................................................................10 1.1 ObBecti es................................................................................................10 1.2 ObBectCOriented 4once&ts...........................................................................10 1.2.1 ObBectCOriented Design....................................................................... 10

Introduction to Programming II

Page 2

J.E.D.I.

1.2.2 4"ass.................................................................................................10 1.2.. ObBect...............................................................................................1( 1.2.0 Attribute............................................................................................1( 1.2.( Met$od..............................................................................................1( 1.2.6 4onstructor........................................................................................1( 1.2.6 Pac,age ............................................................................................1( 1.2./ Enca&su"ation.....................................................................................1( 1.2.? Abstraction........................................................................................1( 1.2.10 In$eritance....................................................................................... 16 1.2.11 Po"ymor&$ism...................................................................................16 1.2.12 Inter1ace..........................................................................................16 1.. Ja a Program %tructure..............................................................................16 1...1 Dec"aring Ja a 4"asses.........................................................................16 1...2 Dec"aring Attributes............................................................................ 16 1.... Dec"aring Met$ods.............................................................................. 1/ 1...0 Dec"aring a 4onstructor.......................................................................1/ 1...( Instantiating a 4"ass............................................................................ 1? 1...6 Accessing ObBect Members...................................................................1? 1...6 Pac,ages...........................................................................................1? 1.../ 8$e Access Modi1iers........................................................................... 20 1...? Enca&su"ation.....................................................................................20 1...10 In$eritance....................................................................................... 21 1...11 O erriding Met$ods...........................................................................21 1...12 Abstract 4"asses and Met$ods.............................................................22 1...1. Inter1ace..........................................................................................2. 1...10 8$e t$is @ey+ord..............................................................................20 1...1( 8$e su&er @ey+ord............................................................................2( 1...16 8$e static @ey+ord............................................................................26 1...16 8$e 1ina" @ey+ord.............................................................................26 1...1/ Inner 4"asses....................................................................................2/ 1.0 E=ercises..................................................................................................2? 1.0.1 Mu"ti&"ication 8ab"e.............................................................................2? 1.0.2 5reatest 4ommon !actor ;54!>............................................................2? 1.0.. %$a&es..............................................................................................2? 1.0.0 Anima"s.............................................................................................2? 2 E=ce&tions and Assertions..................................................................................0 2.1 ObBecti es.................................................................................................0 2.2 9$at are E=ce&tionsD..................................................................................0 2.2.1 Introduction........................................................................................0 2.2.2 8$e Error and E=ce&tion 4"asses........................................................... .0 2.2.. An E=am&"e.........................................................................................1 2.. 4atc$ing E=ce&tions....................................................................................1 2...1 8$e tryCcatc$ %tatements......................................................................1 2...2 8$e 1ina""y @ey+ord..............................................................................0 2.0 8$ro+ing E=ce&tions...................................................................................6 2.0.1 8$e t$ro+ @ey+ord..............................................................................6 2.0.2 8$e t$ro+s @ey+ord.............................................................................6 2.( E=ce&tion 4ategories...................................................................................6 2.(.1 E=ce&tion 4"asses and )ierarc$y............................................................6 2.(.2 4$ec,ed and 2nc$ec,ed E=ce&tions...................................................... ./ 2.(.. 2serCDe1ined E=ce&tions......................................................................./ 2.6 Assertions................................................................................................. .? 2.6.1 9$at are AssertionsD............................................................................? 2.6.2 Enab"ing or Disab"ing Assertions........................................................... .?
Introduction to Programming II Page .

J.E.D.I.

2.6.. Assert %ynta=.....................................................................................0. 2.6 E=ercises..................................................................................................0( 2.6.1 )e=adecima" to Decima".......................................................................0( 2.6.2 Printing a Diamond.............................................................................0( Ad anced Programming 8ec$ni-ues....................................................................06 ..1 ObBecti es................................................................................................06 ..2 Recursion.................................................................................................06 ..2.1 9$at is RecursionD..............................................................................06 ..2.2 Recursion Vs. Iteration........................................................................06 ..2.. !actoria"s' An E=am&"e........................................................................06 ..2.0 Print n in any #ase' Anot$er E=am&"e....................................................0? ... Abstract Data 8y&es...................................................................................(1 ....1 9$at is an Abstract Data 8y&eD............................................................(1 ....2 %tac,s...............................................................................................(1 ..... Eueues..............................................................................................(1 ....0 %e-uentia" and Fin,ed Re&resentation................................................... (2 ....( %e-uentia" Re&resentation o1 an Integer %tac,........................................(. ....6 Fin,ed Fists........................................................................................(( ....6 Fin,ed Re&resentation o1 an Integer %tac,............................................. (6 ..../ Ja a 4o""ections..................................................................................(/ ..0 E=ercises..................................................................................................61 ..0.1 5reatest 4ommon !actor..................................................................... 61 ..0.2 %e-uentia" Re&resentation o1 an Integer Eueue...................................... 61 ..0.. Fin,ed Re&resentation o1 an Integer Eueue............................................61 ..0.0 Address #oo,.....................................................................................61 8our o1 t$e Ba a."ang Pac,age............................................................................62 0.1 ObBecti es................................................................................................62 0.2 8$e Mat$ 4"ass..........................................................................................62 0.. 8$e %tring and t$e %tring#u11er 4"ass...........................................................6( 0...1 %tring 4onstructors.............................................................................6( 0...2 %tring Met$ods...................................................................................6( 0.... 8$e %tring#u11er 4"ass.........................................................................6/ 0.0 8$e 9ra&&er 4"asses..................................................................................60 0.( 8$e Process and t$e Runtime 4"ass..............................................................61 0.(.1 8$e Process 4"ass............................................................................... 61 0.(.2 8$e Runtime 4"ass..............................................................................61 0.(.. O&ening t$e Registry Editor..................................................................61 0.6 8$e %ystem 4"ass......................................................................................62 0.6 E=ercises..................................................................................................60 0.6.1 E a"uate E=&ression............................................................................60 0.6.2 Pa"indrome......................................................................................... 60 0.6.. 7ote&ad............................................................................................. 60 8e=tC#ased A&&"ications....................................................................................6( (.1 ObBecti es................................................................................................6( (.2 4ommandCFine Arguments and %ystem Pro&erties......................................... 6( (.. Reading 1rom %tandard In&ut......................................................................66 (.0 !i"e )and"ing.............................................................................................6/ (.0.1 Reading 1rom a !i"e.............................................................................6? (.0.2 9riting to a !i"e................................................................................../0 (.( E=ercises................................................................................................../2 (.(.1 %&aces to 2nderscore........................................................................../2 (.(.2 Dra+ 8riang"e...................................................................................../2 %orting A"gorit$ms.........................................................................................../. 6.1 ObBecti es................................................................................................/.
Page 0

Introduction to Programming II

J.E.D.I.

6.2 Insertion %ort............................................................................................ /. 6.2.1 8$e A"gorit$m..................................................................................... /. 6.2.2 An E=am&"e......................................................................................../0 6.. %e"ection %ort.........................................................................................../0 6...1 8$e A"gorit$m..................................................................................... /0 6...2 An E=am&"e......................................................................................../( 6.0 Merge %ort................................................................................................ /( 6.0.1 Di ideCandC4on-uer Paradigm............................................................../( 6.0.2 2nderstanding Merge %ort..................................................................../( 6.0.. 8$e A"gorit$m..................................................................................... /6 6.0.0 An E=am&"e......................................................................................../6 6.( Euic,sort................................................................................................../6 6.(.1 8$e A"gorit$m..................................................................................... /6 6.(.2 An E=am&"e......................................................................................../6 6.6 E=ercises................................................................................................../? 6.6.1 Insertion %ort...................................................................................../? 6.6.2 %e"ection %ort...................................................................................../? 6.6.. Merge %ort ......................................................................................../? 6.6.0 Euic,sort...........................................................................................?0 6 Abstract 9indo+ing 8oo",it and %+ing................................................................?1 6.1 ObBecti es................................................................................................?1 6.2 Abstract 9indo+ing 8oo",it ;A98> s. %+ing.................................................?1 6.. A98 52I 4om&onents................................................................................?1 6...1 !undamenta" 9indo+ 4"asses...............................................................?1 6...2 5ra&$ics............................................................................................?. 6.... More A98 4om&onents........................................................................?( 6.0 Fayout Managers.......................................................................................?6 6.0.1 8$e !"o+Fayout Manager......................................................................?6 6.0.2 8$e #orderFayout Manager...................................................................?? 6.0.. 8$e 5ridFayout Manager....................................................................100 6.0.0 Pane"s and 4om&"e= Fayouts...............................................................101 6.( %+ing 52I 4om&onents............................................................................10. 6.(.1 %etting 2& 8o&CFe e" 4ontainers.........................................................100 6.(.2 A J!rame E=am&"e.............................................................................100 6.(.. A JO&tionPane E=am&"e..................................................................... 10( 6.6 E=ercises................................................................................................106 6.6.1 8icC8acC8oe......................................................................................106 6.6.2 4a"cu"ator........................................................................................106 / 52I E ent )and"ing........................................................................................10/ /.1 ObBecti es............................................................................................... 10/ /.2 8$e De"egation E ent Mode"......................................................................10/ /.2.1 Registration o1 Fisteners.....................................................................10? /.. E ent 4"asses..........................................................................................110 /.0 E ent Fisteners........................................................................................111 /.0.1 ActionFistener Met$od........................................................................111 /.0.2 MouseFistener Met$ods......................................................................111 /.0.. MouseMotionFistener Met$ods.............................................................112 /.0.0 9indo+Fistener Met$ods....................................................................112 /.0.( 5uide"ines 1or 4reating A&&"ications )and"ing 52I E ents.......................112 /.0.6 Mouse E ents E=am&"e...................................................................... 11. /.0.6 4"ose 9indo+ E=am&"e......................................................................116 /.( Ada&ter 4"asses.......................................................................................11/ /.(.1 4"ose 9indo+ E=am&"e......................................................................11/ /.6 Inner 4"asses and Anonymous Inner 4"asses............................................... 11?
Introduction to Programming II Page (

J.E.D.I.

/.6.1 Inner 4"asses....................................................................................11? /.6.2 4"ose 9indo+ E=am&"e......................................................................11? /.6.. Anonymous Inner 4"asses.................................................................. 120 /.6.0 4"ose 9indo+ E=am&"e......................................................................120 /.6 E=ercises................................................................................................121 /.6.1 8icC8acC8oe......................................................................................121 /.6.2 4a"cu"ator........................................................................................121 ? 8$reads......................................................................................................... 122 ?.1 ObBecti es............................................................................................... 122 ?.2 8$read De1inition and #asics.....................................................................122 ?.2.1 8$read De1inition..............................................................................122 ?.2.2 8$read %tates...................................................................................12. ?.2.. Priorities..........................................................................................12. ?.. 8$e 8$read 4"ass.....................................................................................120 ?...1 4onstructor......................................................................................120 ?...2 4onstants......................................................................................... 120 ?.... Met$ods...........................................................................................120 ?...0 A 8$read E=am&"e.............................................................................12( ?.0 4reating 8$reads.....................................................................................126 ?.0.1 E=tending t$e 8$read 4"ass................................................................126 ?.0.2 Im&"ementing t$e Runnab"e Inter1ace..................................................126 ?.0.. E=tending s. Im&"ementing...............................................................12/ ?.0.0 An E=am&"e 2sing t$e Boin Met$od...................................................... 12? ?.( %ync$roni*ation.......................................................................................1.0 ?.(.1 An 2nsync$roni*ed E=am&"e...............................................................1.0 ?.(.2 Foc,ing an ObBect............................................................................. 1.1 ?.(.. !irst %ync$roni*ed E=am&"e................................................................1.1 ?.(.0 %econd %ync$roni*ed E=am&"e............................................................1.2 ?.6 Intert$read 4ommunication.......................................................................1.0 ?.6.1 ProducerC4onsumer E=am&"e..............................................................1.( ?.6 4oncurrency 2ti"ities................................................................................1.? ?.6.1 8$e E=ecutor Inter1ace.......................................................................1.? ?.6.2 8$e 4a""ab"e Inter1ace........................................................................100 ?./ E=ercises................................................................................................102 ?./.1 #anner............................................................................................. 102 10 7et+or,ing..................................................................................................10. 10.1 #asic 4once&ts on 7et+or,ing.................................................................10. 10.1.1 IP Address......................................................................................10. 10.1.2 Protoco".......................................................................................... 10. 10.1.. Ports.............................................................................................. 100 10.1.0 8$e 4"ientA%er er Paradigm..............................................................100 10.1.( %oc,ets..........................................................................................10( 10.2 8$e Ja a 7et+or,ing Pac,age..................................................................10( 10.2.1 8$e %er er%oc,et and t$e %oc,et 4"ass..............................................10( 10.2.2 8$e Mu"ticast%oc,et and t$e DatagramPac,et 4"ass............................. 10? 10.. E=ercises..............................................................................................1(2 10...1 8ri ia %er er...................................................................................1(2 11 A&&"ets........................................................................................................ 1(. 11.1 ObBecti es.............................................................................................1(. 11.2 4reating A&&"ets....................................................................................1(. 11.2.1 )e""o 9or"d A&&"et...........................................................................1(. 11.. A&&"et Met$ods......................................................................................1(0 11...1 8$e A&&"et Fi1e 4yc"e....................................................................... 1(( 11...2 8$e &aint Met$od............................................................................1(6
Introduction to Programming II Page 6

J.E.D.I.

11.... 8$e s$o+%tatus Met$od................................................................... 1(6

Introduction to Programming II

Page 6

J.E.D.I.

1.0 Anima"s...............................................................................................1?0 4$a&ter 2 E=ercises........................................................................................1?( 2.1 )e=adecima" to Decima".........................................................................1?( 2.2 Printing a Diamond...............................................................................1?6 4$a&ter . E=ercises........................................................................................1?6 ..1 5reatest 4ommon !actor.......................................................................1?6 ..2 %e-uentia" Re&resentation o1 an Integer Eueue........................................ 1?6 ... Fin,ed Re&resentation o1 an Integer Eueue..............................................1?? ..0 Address #oo,.......................................................................................200 4$a&ter 0 E=ercises........................................................................................201 0.1 E a"uate E=&ression..............................................................................201 0.2 Pa"indrome........................................................................................... 201 0.. 7ote&ad............................................................................................... 201 4$a&ter ( E=ercises........................................................................................202 (.1 %&aces to 2nderscore............................................................................202 (.2 Dra+ 8riang"e.......................................................................................20. 4$a&ter 6 E=ercises........................................................................................200 6.1 Insertion %ort.......................................................................................200 6.2 %e"ection %ort.......................................................................................200 6.. Merge %ort ..........................................................................................20( 6.0 Euic, %ort............................................................................................ 206 4$a&ter 6 E=ercises........................................................................................206 6.1 8icC8acC8oe..........................................................................................206 6.2 4a"cu"ator............................................................................................20/ 4$a&ter / E=ercises........................................................................................210 /.1 8icC8acC8oe..........................................................................................210 /.2 4a"cu"ator............................................................................................21. 4$a&ter ? E=ercises........................................................................................21/ ?.1 #anner................................................................................................21/ 4$a&ter 10 E=ercises......................................................................................21? 10.1 8ri ia %er er....................................................................................... 21? 4$a&ter 11 E=ercises......................................................................................222 11.1 OneCP"ayer 8icC8acC8oe A&&"et..............................................................222 4$a&ter 12 E=ercises......................................................................................226 12.1 %im&"e Encry&tion...............................................................................226 4$a&ter 1. E=ercises......................................................................................22/ 1..1 %+a&&ing...........................................................................................22/ A&&endi= # ' Mac$ine Prob"ems........................................................................... 22? Mac$ine Prob"em 1' Po"ynomia" Arit$metic........................................................ 22? Mac$ine Prob"em 2' My DominoG......................................................................2.0

Introduction to Programming II

Page /

J.E.D.I.

/ Re(iew o 2asic Conce"ts in 3a(a


1.1 Objectives
#e1ore mo ing on to ot$er interesting 1eatures o1 Ja a3 "et us 1irst re ie+ some o1 t$e t$ings youH e "earned in your 1irst &rogramming course. 8$is "esson &ro ides a brie1 discussion o1 t$e di11erent obBectCoriented conce&ts in Ja a. A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. E=&"ain and use t$e basic obBectCoriented conce&ts in your &rograms c"ass obBect attribute met$od constructor &ac,age enca&su"ation abstraction in$eritance &o"ymor&$ism inter1ace

2. Describe ad anced obBectCoriented conce&ts and a&&"y t$em in &rogramming as +e""

.. Describe and use this3 super3 final and static ,ey+ords 0. Di11erentiate bet+een met$od o er"oading and met$od o erriding

1.2 Object-Oriented Concepts


1.2.1 Object-Oriented Design
ObBectCoriented design is a tec$ni-ue t$at 1ocuses design on obBects and c"asses based on rea" +or"d scenarios. It em&$asi*es state3 be$a ior and interaction o1 obBects. It &ro ides t$e bene1its o1 1aster de e"o&ment3 increased -ua"ity3 easier maintenance3 en$anced modi1iabi"ity and increase so1t+are reuse.

1.2.2 Class
A c"ass a""o+s you to de1ine ne+ data ty&es. It ser es as a b"ue&rint3 +$ic$ is a mode" 1or t$e obBects you create based on t$is ne+ data ty&e. 8$e tem&"ate student is an e=am&"e o1 a c"ass. 9e can de1ine e ery student to $a e a set o1 -ua"ities suc$ as name3 student number and sc$oo" "e e". 9e can a"so de1ine students
Introduction to Programming II Page ?

J.E.D.I.

to $a e t$e abi"ity to enro"" and to attend sc$oo".

1.2.3 Object
An obBect is an entity t$at $as a state3 be$a ior and identity +it$ a +e""Cde1ined ro"e in &rob"em s&ace. It is an actua" instance o1 a c"ass. 8$us3 it is a"so ,no+n as an instance. It is created e erytime you instantiate a c"ass using t$e new ,ey+ord. In a student registration system3 an e=am&"e o1 an obBect +ou"d be a student entity3 say Anna. Anna is an obBect o1 t$e c"ass student. 8$us3 t$e -ua"ities and abi"ities de1ined in t$e student tem&"ate are a"" a&&"icab"e to Anna. !or sim&"icity3 you can t$in, o1 a c"ass as a more genera" term com&ared to an obBect.

1.2.4 Attribute
An attribute re1ers to t$e data e"ement o1 an obBect. It stores in1ormation about t$e obBect. It is a"so ,no+n as a data member3 an instance ariab"e3 a &ro&erty or a data 1ie"d. 5oing bac, to t$e student registration system e=am&"e3 some attributes o1 a student entity inc"ude name3 student number and sc$oo" "e e".

1.2.5 Method
A met$od describes t$e be$a ior o1 an obBect. It is a"so ca""ed a 1unction or a &rocedure. !or e=am&"e3 &ossib"e met$ods a ai"ab"e 1or a student entity are enro"" and attend sc$oo".

1.2.

Constructor

A constructor is a s&ecia" ty&e o1 met$od used 1or creating and initia"i*ing a ne+ obBect. Remember t$at constructors are not members ;i.e.3 attributes3 met$ods or inner c"asses o1 an obBect>.

1.2.! "ac#age
A &ac,age re1ers to a grou&ing o1 c"asses andAor sub&ac,ages. Its structure is ana"ogous to t$at o1 a directory.

1.2.$ %ncapsulation
Enca&su"ation re1ers to t$e &rinci&"e o1 $iding design or im&"ementation in1ormation t$at are not re"e ant to t$e current obBect.

1.2.& Abstraction
9$i"e enca&su"ation is $iding t$e detai"s a+ay3 abstraction re1ers to ignoring as&ects o1 a subBect t$at are not re"e ant to t$e current &ur&ose in order to concentrate more 1u""y on t$ose t$at are.

Introduction to Programming II

Page 10

J.E.D.I.

1.2.1' (nheritance
In$eritance is a re"ations$i& bet+een c"asses +$erein one c"ass is t$e su&erc"ass or t$e &arent c"ass o1 anot$er. It re1ers to t$e &ro&erties and be$a iors recei ed 1rom an ancestor. It is a"so ,no+ as a IisCaI re"ations$i&. 4onsider t$e 1o""o+ing $ierarc$y.

SuperHero

FlyingSuperHero

UnderwaterSuperHero

Figure 1.1: Example of Inheritance

SuperHero is t$e su&erc"ass o1 FlyingSuperHero and UnderwaterSuperHero c"asses. 7ote t$at FlyingSuperHero IisCaI SuperHero. UnderwaterSuperHero IisCaI SuperHero as +e"".

1.2.11 "ol)*orphis*
Po"ymor&$ism is t$e abi"ity o1 an obBect to assume may di11erent 1orms. Fitera""y3 I&o"yI means many +$i"e Imor&$I means 1orm. Re1erring to t$e &re ious e=am&"e 1or in$eritance3 +e see t$at a SuperHero obBect can a"so be a FlyingSuperHero obBect or an UnderwaterSuperHero obBect.

1.2.12 (nter+ace
An inter1ace is a contract in t$e 1orm o1 a co""ection o1 met$od and constant dec"arations. 9$en a c"ass implements an inter1ace3 it &romises to im&"ement a"" o1 t$e met$ods dec"ared in t$at inter1ace.

Introduction to Programming II

Page 11

J.E.D.I.

1.3 ,ava "rogra* -tructure


8$is section summari*es t$e basic synta= used in creating Ja a a&&"ications.

1.3.1 Declaring ,ava Classes


<classDeclaration> ::= <modifier> class <name> { <attributeDeclaration>* <constructorDeclaration>* <methodDeclaration>* } +$ere <modifier is an access modi1ier3 +$ic$ may be combined +it$ ot$er ty&es o1 modi1ier.

Coding .uidelines/ 0 means that there may !e " or more occurrences of the line where it was applied to. <description indicates that you ha#e to su!stitute an actual #alue for this part instead of typing it as ease. $emem!er that for a top%le#el class& the only #alid access modifiers are pu!lic and pac'age (i.e.& if no access modifier prefixes the class 'eyword). 8$e 1o""o+ing e=am&"e dec"ares a SuperHero b"ue&rint. class SuperHero { String superPowers !" #oid setSuperPowers$String superPowers !% { this&superPowers = superPowers" } #oid printSuperPowers$% { for $int i = '" i < superPowers&length" i((% { S)stem&out&println$superPowers i!%" } } }

1.3.2 Declaring Attributes


<attributeDeclaration> ::= <modifier> <t)pe> <name> = <default*#alue>!" <t)pe> ::= b)te + short + int + long + char + float + double + boolean + <class> Coding .uidelines/ *+ indicates that this part is optional. )ere is an e=am&"e. public class ,ttributeDemo { pri#ate String stud-um" public boolean graduating = false" protected float units.a/en = '&'f"
Introduction to Programming II Page 12

J.E.D.I.

String college"

1.3.3 Declaring Methods


<methodDeclaration> ::= <modifier> <return.)pe> <name>$<parameter>*% { <statement>* } <parameter> ::= <parameter*t)pe> <parameter*name> 0! !or e=am&"e' class 1ethodDemo { int data" int getData$% { return data" } #oid setData$int data% { this&data = data" } #oid set1a2Data$int data30 int data4% { data = $data3>data4%5 data3 : data4" } }

1.3.4 Declaring a Constructor


<constructorDeclaration> ::= <modifier> <class-ame> $<parameter>*% { <statement>* } I1 no constructor is e=&"icit"y &ro ided3 a de1au"t constructor is automatica""y created 1or you. 8$e de1au"t constructor ta,es no arguments and its body contains no statements. Coding .uidelines/ ,he name of the constructor should !e the same as the class name. ,he only #alid <modifier for constructors are pu!lic& protected& and pri#ate. -onstructors do not ha#e return #alues. 4onsider t$e 1o""o+ing e=am&"e. class 6onstructorDemo { pri#ate int data" public 6onstructorDemo$% { data = 3''" } 6onstructorDemo$int data% { this&data = data" } }

Introduction to Programming II

Page 1.

J.E.D.I.

1.3.5 (nstantiating a Class


8o instantiate a c"ass3 +e sim&"y use t$e new ,ey+ord 1o""o+ed by a ca"" to a constructor. FetHs go direct"y to an e=am&"e. class 6onstruct7b8 { int data" 6onstruct7b8$% { 9* initiali:e data *9 } public static #oid main$String args !% { 6onstruct7b8 ob8 = new 6onstruct7b8$%" } }

99instantiation

1.3.

Accessing Object Me*bers

8o access members o1 an obBect3 +e use t$e IdotI notation. It is used as 1o""o+s' <ob8ect>&<member> 8$e ne=t e=am&"e is based on t$e &re ious one +it$ additiona" statements 1or accessing members and an additiona" met$od. class 6onstruct7b8 { int data" 6onstruct7b8$% { 9* initiali:e data *9 } #oid setData$int data% { this&data = data" } public static #oid main$String args !% { 6onstruct7b8 ob8 = new 6onstruct7b8$%" 99instantiation ob8&setData$3'%" 99access setData$% S)stem&out&println$ob8&data%" 99access data } } 8$e e=&ected out&ut o1 t$e gi en code is 1".

1.3.! "ac#ages
8o indicate t$at t$e source 1i"e be"ongs to a &articu"ar &ac,age3 +e use t$e 1o""o+ing synta=' <pac/ageDeclaration> ::= pac/age <pac/age-ame>" 8o im&ort ot$er &ac,ages3 +e use t$e 1o""o+ing synta=' <importDeclaration> ::= import <pac/age-ame&element,ccessed>"

Introduction to Programming II

Page 10

J.E.D.I.

9it$ t$is3 your source code s$ou"d $a e t$e 1o""o+ing 1ormat' <pac/ageDeclaration>! <importDeclaration>* <classDeclaration>( Coding .uidelines/ . indicates that there may !e 1 or more occurrences of the line where it was applied to. )ere is an e=am&"e. pac/age registration&reports" import registration&processing&*" 99imports all classes in registration&processing pac/age import 8a#a&util&;ist" import 8a#a&lang&*" 99imported b) default 99imports all classes in 8a#a&lang class 1)6lass { 9* details of 1)6lass *9 }

1.3.$ 1he Access Modi+iers


8$e 1o""o+ing tab"e summari*es t$e access modi1iers in Ja a. private %ame c"ass %ame &ac,age Di11erent &ac,age ;subc"ass> Di11erent &ac,age ;nonCsubc"ass>
,a!le 1: /ccess 0odifiers

de1au"tA&ac,age Jes Jes

protected Jes Jes Jes

public Jes Jes Jes Jes

Jes

1.3.& %ncapsulation
)iding e"ements o1 t$e im&"ementation o1 a c"ass can be done by ma,ing t$e members t$at you +ant to $ide &ri ate. 8$e 1o""o+ing e=am&"e $ides t$e secret 1ie"d. 7ote t$at t$is 1ie"d is indirect"y accessed by ot$er &rograms using t$e getter and setter met$ods. class <ncapsulation { pri#ate int secret" 99hidden field public boolean setSecret$int secret% { if $secret < 3 ++ secret > 3''% { return false" } this&secret = secret" return true" }
Introduction to Programming II Page 1(

J.E.D.I.

public getSecret$% { return secret" }

I1 you do not +ant ot$er c"asses to modi1y t$e secret 1ie"d3 you can set t$e access modi1ier o1 t$e setSecret() met$od to be pri#ate.

1.3.1' (nheritance
8o create a c$i"d c"ass or a subc"ass based on an e=isting c"ass3 +e use t$e e=tends ,ey+ord in dec"aring t$e c"ass. A c"ass can on"y e=tend one &arent c"ass. !or e=am&"e3 t$e 1oint c"ass be"o+ is t$e su&erc"ass o1 t$e -olored1oint c"ass. import 8a#a&awt&*" class Point { int 2" int )" } class 6oloredPoint e2tends Point { 6olor color" }

1.3.11 Overriding Methods


A subc"ass met$od o errides a su&erc"ass met$od +$en a subc"ass de1ines a met$od +$ose signature is identica" to a met$od in t$e su&erc"ass. 8$e signature o1 a met$od is Bust t$e in1ormation 1ound in t$e met$od $eader de1inition. 8$e signature inc"udes t$e return ty&e3 t$e name and t$e &arameter "ist o1 t$e met$od but it does not inc"ude t$e access modi1iers and t$e ot$er ty&es o1 ,ey+ords suc$ as final and static. 8$is is di11erent 1rom met$od o er"oading. Met$od o er"oading is brie1"y discussed in t$e subsection on t$e this ,ey+ord. class Superclass { #oid displa)$int n% { S)stem&out&println$=super: = ( n%" } } class Subclass e2tends Superclass { #oid displa)$int /% { 99o#erriding method S)stem&out&println$=sub: = ( /%" } } class 7#errideDemo { public static #oid main$String args !% { Subclass Sub7b8 = new Subclass$%" Superclass Super7b8 = Sub7b8" Sub7b8&displa)$>%" $$Superclass%Sub7b8%&displa)$?%" } }

Introduction to Programming II

Page 16

J.E.D.I.

It &roduces t$e 1o""o+ing out&ut. sub: > sub: ? 8$e met$od ca""ed is determined by t$e actua" data ty&e o1 t$e obBect t$at in o,ed t$e met$od. 8$e access modi1ier 1or t$e met$ods need not be t$e same. )o+e er3 t$e access modi1ier o1 t$e o erriding met$od must eit$er $a e t$e same access modi1ier as t$at o1 t$e o erridden met$od or a "ess restricti e access modi1ier. 4onsider t$e ne=t e=am&"e. 4$ec, out +$ic$ o1 t$e 1o""o+ing o erridding met$ods +ou"d cause a com&i"e time error to occur. class Superclass { #oid o#erridden1ethod$% { } } class Subclass3 e2tends Superclass { public #oid o#erridden1ethod$% { } } class Subclass4 e2tends Superclass { #oid o#erridden1ethod$% { } } class Subclass> e2tends Superclass { protected #oid o#erridden1ethod$% { } } class Subclass? e2tends Superclass { pri#ate #oid o#erridden1ethod$% { } } 8$e o#erridden0ethod() in Superclass $as t$e de1au"tA&ac,age access modi1ier. 8$e on"y modi1ier more restricti e t$an t$is is pri#ate. 8$us3 Su!class2 causes a com&i"er error because it tries to o erride o#erridden0ethod() in Superclass +it$ a more restricti e modi1ier pri#ate.

1.3.12 Abstract Classes and Methods


8$e genera" 1orm 1or an a!stract met$od is as 1o""o+s' abstract <modifier> <return.)pe> <name>$<parameter>*%" A c"ass containing an a!stract met$od s$ou"d be dec"ared as an a!stract c"ass. abstract class <name> { 9* constructors0 fields and methods *9 } 8$e ,ey+ord cannot be a&&"ied to a constructor or a static met$od. It a"so im&ortant to remember t$at a!stract c"asses cannot be instantiated.
Introduction to Programming II Page 16

J.E.D.I.

4"asses t$at extends an a!stract c"ass s$ou"d im&"ement a"" a!stract met$ods. I1 not t$e subc"ass itse"1 s$ou"d be dec"ared a!stract. Coding .uidelines/ 3ote that declaring an a!stract method is almost similar to declaring a normal class except that an a!stract method has no !ody and the header is immediately terminated !y a semicolon (4). !or e=am&"e' abstract class SuperHero { String superPowers !" #oid setSuperPowers$String superPowers !% { this&superPowers = superPowers" } #oid printSuperPowers$% { for $int i = '" i < superPowers&length" i((% { S)stem&out&println$superPowers i!%" } } abstract #oid displa)Power$%" } class @nderwaterSuperHero e2tends SuperHero { #oid displa)Power$% { S)stem&out&println$=6ommunicate with sea creatures&&&=%" S)stem&out&println$=Aast swimming abilit)&&&=%" } } class Al)ingSuperHero e2tends SuperHero { #oid displa)Power$% { S)stem&out&println$=Al)&&&=%" } }

1.3.13 (nter+ace
Dec"aring an inter1ace is basica""y dec"aring a c"ass but instead o1 using t$e class ,ey+ord3 t$e interface ,ey+ord is used. )ere is t$e synta=. <interfaceDeclaration> ::= <modifier> interface <name> { <attributeDeclaration>* <modifier> <return.)pe> <name>$<parameter>*%"!* } Members are pu!lic +$en t$e inter1ace is dec"ared pu!lic. Coding .uidelines/ /ttri!utes are implicitly static and final and must !e initiali5ed with a constant #alue. 6i'e in declaring a top%le#el class& the only #alid access modifiers are pu!lic and pac'age (i.e.& if no access modifier prefixes the class 'eyword). A c"ass can im&"ement an e=isting inter1ace by using t$e implements ,ey+ord. 8$is c"ass is 1orced to im&"ement a"" o1 t$e inter1aceHs met$ods. A c"ass may im&"ement more t$an one inter1ace.
Introduction to Programming II Page 1/

J.E.D.I.

8$e 1o""o+ing e=am&"e demonstrates $o+ to dec"are and use an inter1ace. interface 1)Bnterface { #oid i1ethod$%" } class 1)6lass3 implements 1)Bnterface { public #oid i1ethod$% { S)stem&out&println$=Bnterface method&=%" } #oid m)1ethod$% { S)stem&out&println$=,nother method&=%" }

class 1)6lass4 implements 1)Bnterface { public #oid i1ethod$% { S)stem&out&println$=,nother implementation&=%" } } class BnterfaceDemo { public static #oid main$String args !% { 1)6lass3 mc3 = new 1)6lass3$%" 1)6lass4 mc4 = new 1)6lass4$%" mc3&i1ethod$%" mc3&m)1ethod$%" mc4&i1ethod$%"

)ere is t$e e=&ected out&ut' Bnterface method& ,nother method& ,nother implementation&

1.3.14 1he this 2e)3ord


8$e t$is ,ey+ord can be used 1or t$e 1o""o+ing reasons' 1. Disambiguate "oca" attribute 1rom a "oca" ariab"e 2. Re1er to t$e obBect t$at in o,ed t$e nonCstatic met$od .. Re1er to ot$er constructors As an e=am&"e 1or t$e 1irst &ur&ose3 consider t$e 1o""o+ing code +$erein t$e data ser es as an attribute and a "oca" &arameter at t$e same time. class .hisDemo3 { int data" #oid method$int data% { this&data = data" 9* this&data refers to the attribute while data refers to the local #ariable *9 } } 8$e 1o""o+ing e=am&"e demonstrates $o+ this obBect is im&"icit"y re1erred to +$en its nonCstatic members are in o,ed.
Introduction to Programming II Page 1?

ariab"e

J.E.D.I.

class .hisDemo4 { int data" #oid method$% { S)stem&out&println$data%" 99this&data } #oid method4$% { method$%" 99this&method$%" } } #e1ore "oo,ing at anot$er e=am&"e3 "etHs 1irst re ie+ t$e meaning o1 met$od o er"oading. A constructor "i,e a met$od can a"so be o er"oaded. Di11erent met$ods +it$in a c"ass can s$are t$e same name &ro ided t$eir &arameter "ists are di11erent. O er"oaded met$ods must di11er in t$e number andAor ty&e o1 t$eir &arameters. 8$e ne=t e=am&"e $as o er"oaded constructors and t$e this re1erence can be used to re1er to ot$er ersions o1 t$e constructor. class .hisDemo> { int data" .hisDemo>$% { this$3''%" } .hisDemo>$int data% { this&data = data" } } Coding .uidelines/ -all to this() should !e the first statement in the constructor.

1.3.15 1he super 2e)3ord


8$e use o1 t$e super ,ey+ord is re"ated to in$eritance. It used to in o,e su&erc"ass constructors. It can a"so be used "i,e t$e this ,ey+ord to re1er to members o1 t$e su&erc"ass. 8$e 1o""o+ing &rogram demonstrates $o+ t$e super re1erence is used to ca"" su&erc"ass constructors. class Person { String first-ame" String last-ame" Person$String fname0 String lname% { first-ame = fname" last-ame = lname" } } class Student e2tends Person { String stud-um" Student$String fname0 String lname0 String s-um% { super$fname0 lname%" stud-um = s-um" } } Coding .uidelines/

Introduction to Programming II

Page 20

J.E.D.I.

super() refers to the immediate superclass. It should !e the first statement in the su!class7s constructor. 8$e ,ey+ord can a"so be used to re1er to su&erc"ass members as s$o+n in t$e 1o""o+ing e=am&"e. class Superclass{ int a" #oid displa)*a$%{ S)stem&out&println$=a = = ( a%" } } class Subclass e2tends Superclass { int a" #oid displa)*a$%{ S)stem&out&println$=a = = ( a%" } #oid set*super*a$int n%{ super&a = n" } #oid displa)*super*a$%{ super&displa)*a$%" } } class SuperDemo { public static #oid main$String args !%{ Superclass Super7b8 = new Superclass$%" Subclass Sub7b8 = new Subclass$%" Super7b8&a = 3" Sub7b8&a = 4" Sub7b8&set*super*a$>%" Super7b8&displa)*a$%" Sub7b8&displa)*a$%" Sub7b8&displa)*super*a$%" S)stem&out&println$Sub7b8&a%" } } 8$e a = a = a = 4 &rogram dis&"ays t$e 1o""o+ing resu"t. 3 4 >

1.3.1

1he static 2e)3ord

8$e static ,ey+ord can be a&&"ied to t$e members o1 a c"ass. 8$e ,ey+ord a""o+s static or c"ass members to be accessed e en be1ore any instance o1 t$e c"ass is created. A c"ass ariab"e be$a es "i,e a g"oba" accessed by a"" instances o1 t$e c"ass. ariab"e. 8$is means t$at t$e ariab"e can be

4"ass met$ods may be in o,ed +it$out creating an obBect o1 its c"ass. )o+e er3 t$ey can on"y access static members o1 t$e c"ass. In addition to t$is3 t$ey cannot re1er to this or super.

Introduction to Programming II

Page 21

J.E.D.I.

8$e static ,ey+ord can a"so be a&&"ied to b"oc,s. 8$ese are ca""ed static b"oc,s. 8$ese b"oc,s are e=ecuted on"y once3 +$en t$e c"ass is "oaded. 8$ese are usua""y used to initia"i*e c"ass ariab"es. class Demo { static int a = '" static #oid static1ethod$int i% { S)stem&out&println$i%" } static { 99static bloc/ S)stem&out&println$=.his is a static bloc/&=%" a (= 3" } } class StaticDemo { public static #oid main$String args !% { S)stem&out&println$Demo&a%" Demo&static1ethod$C%" Demo d = new Demo$%" S)stem&out&println$d&a%" d&static1ethod$'%" Demo e = new Demo$%" S)stem&out&println$e&a%" d&a (= >" S)stem&out&println$Demo&a(=0 = (d&a (=0 = (e&a%" } } 8$e out&ut 1or t$e source code is s$o+n be"o+. .his is a static bloc/& 3 C 3 ' 3 ?0 ?0 ?

1.3.1! 1he +inal 2e)3ord


8$e final ,ey+ord can be a&&"ied to ariab"es3 met$ods and c"asses. 8o remember t$e 1unction o1 t$e ,ey+ord3 Bust remember t$at it sim&"y restricts +$at +e can do +it$ t$e ariab"es3 met$ods and c"asses. 8$e a"ue o1 a 1ina" ariab"e can no "onger be modi1ied once its e=am&"e3 final int data = 3'" 8$e 1o""o+ing statement +i"" cause a com&i"ation error to occur' data((" A 1ina" met$od cannot be o erridden in t$e c$i"d c"ass. final #oid m)1ethod$% { 99in a parent class } my0ethod can no "onger be o erridden in t$e c$i"d c"ass. A 1ina" c"ass cannot be in$erited un"i,e ordinary c"asses. final public class 1)6lass {
Introduction to Programming II Page 22

a"ue $as been set. !or

J.E.D.I.

} Coding .uidelines/ 8rder of typing the final and pu!lic 'eyword may !e interchanged. )a ing t$is statement +i"" cause a com&i"ation error to occur since 0y-lass can no "onger be e=tended. public Drong6lass e2tends 1)6lass { }

1.3.1$ (nner Classes


An inner c"ass is sim&"y a c"ass dec"ared +it$in anot$er c"ass. class 7uter6lass { int data = C" class Bnner6lass { int data4 = 3'" #oid method$% { S)stem&out&println$data%" S)stem&out&println$data4%" } } public static #oid main$String args !% { 7uter6lass oc = new 7uter6lass$%" Bnner6lass ic = oc&new Bnner6lass$%" S)stem&out&println$oc&data%" S)stem&out&println$ic&data4%" ic&method$%" } } )ere is t$e e=&ected out&ut o1 t$e gi en code' C 3' 8o be ab"e to access t$e members o1 t$e inner c"ass3 +e need an instance o1 t$e inner c"ass. Met$ods o1 t$e inner c"ass can direct"y access members o1 t$e outer c"ass.

Introduction to Programming II

Page 2.

J.E.D.I.

0 Exce"tions and Assertions


2.1 Objectives
#asic e=ce&tion $and"ing $as been introduced to you in your 1irst &rogramming course. 8$is "esson &ro ides a dee&er understanding o1 e=ce&tions and a"so introduces assertions as +e"". A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. )and"e e=ce&tions by using try3 catc$ and 1ina""y 2. Di11erentiate bet+een t$e use o1 t$ro+ and t$ro+s .. 2se e=isting e=ce&tion c"asses 0. Di11erentiate bet+een c$ec,ed and unc$ec,ed e=ce&tions (. De1ine your o+n e=ce&tion c"asses 6. E=&"ain t$e bene1its o1 using assertions 6. 2se assertions

2.2 4hat are %5ceptions6


2.2.1 (ntroduction
#ugs or errors in &rograms are ery "i,e"y to occur e en i1 +ritten by a ery s,i""1u" and organi*ed &rogrammer. 8o a oid $a ing to s&end more time on errorCc$ec,ing rat$er t$an +or,ing on t$e actua" &rob"em itse"13 Ja a $as &ro ided us +it$ an e=ce&tion $and"ing mec$anism. E=ce&tions are s$ort 1or e=ce&tiona" e ents. 8$ese are sim&"y errors t$at occur during runtime3 causing t$e norma" &rogram 1"o+ to be disru&ted. 8$ere are di11erent ty&e o1 errors t$at can occur. %ome e=am&"es are di ide by *ero errors3 accessing t$e e"ements o1 an array beyond its range3 in a"id in&ut3 $ard dis, cras$3 o&ening a nonCe=istent 1i"e and $ea& memory e=$austed.

2.2.2 1he %rror and %5ception Classes


A"" e=ce&tions are subc"asses3 +$et$er direct"y or indirect"y3 o1 t$e root c"ass ,hrowa!le. Immediate"y under t$is c"ass are t$e t+o genera" categories o1 e=ce&tions' t$e Error c"ass and t$e Exception c"ass. 8$e Exception c"ass is re1er to conditions t$at user &rograms can reasonab"y dea" +it$. 8$ese are usua""y t$e resu"t o1 some 1"a+s in t$e user &rogram code. E=am&"e o1 Exceptions are t$e di ision by *ero error and t$e array outCo1Cbounds error. 8$e Error c"ass3 on t$e ot$er $and3 is used by t$e Ja a runCtime system to $and"e errors occurring in t$e runCtime en ironment. 8$ese are genera""y beyond t$e contro" o1 user &rograms since t$ese are caused by t$e runCtime en ironment. E=am&"es inc"ude out o1 memory errors and $ard dis, cras$.

Introduction to Programming II

Page 20

J.E.D.I.

2.2.3 An %5a*ple
4onsider t$e 1o""o+ing &rogram' class Di#E)Fero { public static #oid main$String args !% { S)stem&out&println$>9'%" S)stem&out&println$GPls& print me&H%" } } Running t$e code +ou"d dis&"ay t$e 1o""o+ing error message. <2ception in thread =main= 8a#a&lang&,rithmetic<2ception: 9 b) :ero at Di#E)Fero&main$Di#E)Fero&8a#a:>% 8$e message &ro ides t$e in1ormation on t$e ty&e o1 e=ce&tion t$at $as occurred and t$e "ine o1 code +$ere t$e e=ce&tion $ad originated 1rom. 8$is is $o+ t$e de1au"t $and"er dea"s +it$ uncaug$t e=ce&tions. 9$en no user code $and"es t$e occurring e=c&etion3 t$e de1au"t $and"er goes to +or,. It 1irst &rints out t$e descri&tion o1 t$e e=ce&tion t$at occured. Moreo er3 it a"so &rints t$e stac, trace t$at indicates t$e $ierarc$y o1 met$ods +$ere t$e e=ce&tion $a&&ened. Fast"y3 t$e de1au"t $and"er causes t$e &rogram to terminate. 7o+3 +$at i1 you +ant to $and"e t$e e=ce&tion in a di11erent mannerD !ortunate"y3 t$e Ja a &rogramming "anguage is incor&orated +it$ t$ese t$ree im&ortant ,ey+ords 1or e=ce&tion $and"ing3 t$e try3 catch and finally ,ey+ords.

2.3 Catching %5ceptions


2.3.1 1he tr)-catch -tate*ents
As mentioned in t$e &receding section3 t$e ,ey+ords try3 catch and finally are used to $and"e di11erent ty&es o1 e=ce&tions. 8$ese t$ree ,ey+ords are used toget$er but t$e finally b"oc, is o&tiona". It +ou"d be good to 1irst 1ocus on t$e 1irst t+o reser ed +ords and Bust go bac, to t$e finally "ater on. 5i en be"o+ is t$e genera" synta= 1or +riting a tryCcatc$ statement. tr) { <code to be monitored for e2ceptions> } catch $<<2ception.)pe3> <7b8-ame>% { <handler if <2ception.)pe3 occurs> } &&& } catch $<<2ception.)pe-> <7b8-ame>% { <handler if <2ception.)pe- occurs> } Coding .uidelines/ ,he catch !loc' starts after the close curly !race of the preceding try or catch !loc'. Statements within the !loc' are indented. A&&"ying t$is to Di #yKero &rogram youL e studies ear"ier3 class Di#E)Fero {
Introduction to Programming II Page 2(

J.E.D.I.

public static #oid main$String args !% { tr) { S)stem&out&println$>9'%" S)stem&out&println$GPlease print me&H%" } catch $,rithmetic<2ception e2c% { 99reaction to the e#ent S)stem&out&println$e2c%" } S)stem&out&println$G,fter e2ception&H%" }

8$e di ide by *ero error is an e=am&"e o1 an /rithmeticException. 8$us3 t$e e=ce&tion ty&e indicated in t$e catc$ c"ause is t$is c"ass. 8$e &rogram $and"es t$e error by sim&"y &rinting out t$e descri&tion o1 t$e &rob"em. 8$e out&ut o1 t$e &rogram t$is time +ou"d be as 1o""o+s' 8a#a&lang&,rithmetic<2ception: 9 b) :ero ,fter e2ception& A &articu"ar code monitored in t$e try b"oc, may cause more t$an one ty&e o1 e=ce&tion to occur. In t$is case3 t$e di11erent ty&es o1 errors can be $and"ed using se era" catch b"oc,s. 7ote t$at t$e code in t$e try b"oc, may on"y t$ro+ one e=ce&tion at a time but may cause di11erent ty&es o1 e=ce&tions to occur at di11erent times. )ere is an e=am&"e o1 a code t$at $and"es more t$an one ty&e o1 e=ce&tion. class 1ultiple6atch { public static #oid main$String args !% { tr) { int den = Bnteger&parseBnt$args '!%" 99line ? S)stem&out&println$>9den%" 99line C } catch $,rithmetic<2ception e2c% { S)stem&out&println$GDi#isor was '&H%" } catch $,rra)Bnde27ut7fEounds<2ception e2c4% { S)stem&out&println$G1issing argument&H%" } S)stem&out&println$G,fter e2ception&H%" } } In t$is e=am&"e3 "ine 0 may t$ro+ /rrayIndex8ut8f9oundsException +$en t$e user 1orgets to in&ut an argument +$i"e "ine ( t$ro+s an /rithmeticException i1 t$e user enters 0 as an argument. %tudy user' a> b> c> +$at $a&&ens to t$e &rogram +$en t$e 1o""o+ing arguments are entered by t$e 7o argument 1 0

I1 no argument +as &assed3 t$e 1o""o+ing out&ut +i"" be dis&"ayed' 1issing argument& ,fter e2ception& Passing 1 as argument gi es t$e 1o""o+ing out&ut' >
Introduction to Programming II Page 26

J.E.D.I.

,fter e2ception& Mean+$i"e3 &assing t$e argument " +i"" gi e t$is out&ut' Di#isor was '& ,fter e2ception& 7ested trys are a"so a""o+ed in Ja a. class -ested.r)Demo { public static #oid main$String args !%{ tr) { int a = Bnteger&parseBnt$args '!%" tr) { int b = Bnteger&parseBnt$args 3!%" S)stem&out&println$a9b%" } catch $,rithmetic<2ception e% { S)stem&out&println$GDi#ide b) :ero errorI=%" } } catch $,rra)Bnde27ut7fEounds<2ception e2c% { S)stem&out&println$G4 parameters are reJuiredI=%" } } } Ana"y*e +$at $a&&ens to t$e code +$en t$ese arguments are &assed to t$e &rogram' a> 7o argument b> 1( c> 1( . d> 1( 0 )ere are t$e e=&ected out&ut 1or eac$ sam&"e argument set' a> 7o argument 4 parameters are reJuiredI b> 1( 4 parameters are reJuiredI c> 1( . C d> 1( 0 Di#ide b) :ero errorI 8$e code be"o+ $as a nested try in disguise +it$ t$e use o1 met$ods. class -ested.r)Demo4 { static #oid nested.r)$String args !% { tr) { int a = Bnteger&parseBnt$args '!%" int b = Bnteger&parseBnt$args 3!%" S)stem&out&println$a9b%" } catch $,rithmetic<2ception e% { S)stem&out&println$=Di#ide b) :ero errorI=%" } } public static #oid main$String args !%{ tr) { nested.r)$args%" } catch $,rra)Bnde27ut7fEounds<2ception e% { S)stem&out&println$=4 parameters are reJuiredI=%" } }
Introduction to Programming II Page 26

J.E.D.I.

} 9$at is t$e out&ut o1 t$is &rogram +$en tested on t$e 1o""o+ing argumentsD a> 7o argument b> 1( c> 1( . d> 1( 0 8$e e=&ected out&ut 1or 3ested,ry:emo; is simi"ar to t$at o1 3ested,ry:emo.

2.3.2 1he +inall) 2e)3ord


!ina""y3 youL"" no+ incor&orate t$e finally ,ey+ord to tryCcatc$ statementsG )ere is $o+ t$is reser ed +ord 1its in' tr) { <code to be monitored for e2ceptions> } catch $<<2ception.)pe3> <7b8-ame>% { <handler if <2ception.)pe3 occurs> } &&& } finall) { <code to be e2ecuted before the tr) bloc/ ends> } Coding .uidelines/ /gain& same coding con#ention applies to the finally !loc' as in the catch !loc'. It starts after the close curly !race of the preceding catch !loc'.Statements within this !loc' are also indented. 8$e 1ina""y b"oc, contains t$e code 1or c"eaning u& a1ter a try or a catch. 8$is b"oc, o1 code is a"+ays e=ecuted regard"ess o1 +$et$er an e=ce&tion is t$ro+n or not in t$e try b"oc,. 8$is remains true e en i1 return3 continue or !rea' are e=ecuted. !our di11erent scenarios are &ossib"e in a tryCcatc$C1ina""y b"oc,. !irst3 a 1orced e=it occurs +$en t$e &rogram contro" is 1orced to s,i& out o1 t$e try b"oc, using a return3 a continue or a !rea' statement. %econd3 a norma" com&"etion $a&&ens +$en t$e t$e tryCcatc$C1ina""y statement e=ecutes norma""y +it$out any error occurring. 8$ird3 t$e &rogram code may $a e s&eci1ied in a &articu"ar catch b"oc, t$e e=ce&tion t$at +as t$ro+n. 8$is is ca""ed t$e caug$t e=ce&tion t$ro+n scenario. Fast3 t$e o&&osite o1 t$e t$ird scenario is t$e uncaug$t e=ce&tion t$ro+n. In t$is case3 t$e e=ce&tion t$ro+n +as not s&eci1ied in any catch b"oc,. 8$ese scenarios are seen in t$e 1o""o+ing code. class Ainall)Demo { static #oid m)1ethod$int n% throws <2ception{ tr) { switch$n% { case 3: S)stem&out&println$=first case=%" return" case >: S)stem&out&println$=third case=%" throw new Kuntime<2ception$=third case demo=%" case ?: S)stem&out&println$=fourth case=%" throw new <2ception$=fourth case demo=%" case 4: S)stem&out&println$=second case=%" } } catch $Kuntime<2ception e% { S)stem&out&print$=Kuntime<2ception caught: =%" S)stem&out&println$e&get1essage$%%" } finall) {
Introduction to Programming II Page 2/

J.E.D.I.

} public static #oid main$String args !%{ for $int i=3" i<=?" i((% { tr) { Ainall)Demo&m)1ethod$i%" } catch $<2ception e%{ S)stem&out&print$=<2ception caught: =%" S)stem&out&println$e&get1essage$%%" } S)stem&out&println$%" } }

S)stem&out&println$=tr)Lbloc/ is entered&=%"

8$e 1o""o+ing "ines are t$e e=&ected out&ut o1 t$is &rogram. first case tr)Lbloc/ is entered& second case tr)Lbloc/ is entered& third case Kuntime<2ception caught: third case demo tr)Lbloc/ is entered& fourth case tr)Lbloc/ is entered& <2ception caught: fourth case demo

Introduction to Programming II

Page 2?

J.E.D.I.

2.4 1hro3ing %5ceptions


2.4.1 1he thro3 2e)3ord
#esides catc$ing e=ce&tions3 Ja a a"so a""o+s user &rograms to t$ro+ e=ce&tions ;i.e.3 cause an e=ce&tiona" e ent to occur>. 8$e synta= 1or t$ro+ing e=ce&tions is sim&"e. )ere is it. throw <e2ception ob8ect>" 4onsider t$is e=am&"e. 9* .hrows an e2ception when the input is Gin#alid inputH& *9 class .hrowDemo { public static #oid main$String args !%{ String input = Gin#alid inputH" tr) { if $input&eJuals$Gin#alid inputH%% { throw new Kuntime<2ception$=throw demo=%" } else { S)stem&out&println$input%" } S)stem&out&println$=,fter throwing=%" } catch $Kuntime<2ception e% { S)stem&out&println$=<2ception caught here&=%" S)stem&out&println$e%" } } } 8$e sam&"e code gi es t$e 1o""o+ing out&ut' <2ception caught here& 8a#a&lang&Kuntime<2ception: throw demo

2.4.2 1he thro3s 2e)3ord


In t$e case t$at a met$od can cause an e=ce&tion but does not catc$ it3 t$en it must say so using t$e throws ,ey+ord. 8$is ru"e on"y a&&"ies to c$ec,ed e=ce&tions. JouL"" "earn more about c$ec,ed and unc$ec,ed e=ce&tions in t$e 1o""o+ing section on ME=ce&tion 4ategoriesN. )ere is t$e synta= 1or using t$e throws ,ey+ord' <t)pe> <method-ame> $<parameter;ist>% throws <e2ception;ist> { <methodEod)> } A met$od is re-uired to eit$er catc$ or "ist a"" e=ce&tions it mig$t t$ro+3 but it may omit t$ose o1 ty&e Error or RuntimeE=ce&tion3 or t$eir subc"asses. 8$is e=am&"e indicates t$at my0ethod does not $and"e -lass3otFoundException. class .hrowing6lass { static #oid m)1ethod$% throws 6lass-otAound<2ception { throw new 6lass-otAound<2ception $=8ust a demo=%" } }
Introduction to Programming II Page .0

J.E.D.I.

class .hrowsDemo { public static #oid main$String args !% { tr) { .hrowing6lass&m)1ethod$%" } catch $6lass-otAound<2ception e% { S)stem&out&println$e%" } } } 8$e &rogram gi es t$e 1o""o+ing out&ut' 8a#a&lang&6lass-otAound<2ception: 8ust a demo

2.5 %5ception Categories


2.5.1 %5ception Classes and 7ierarch)
As mentioned ear"ier3 t$e root c"ass o1 a"" e=ce&tion c"asses is t$e 8$ro+ab"e c"ass. Presented be"o+ is t$e e=ce&tion c"ass $ierarc$y. 8$ese e=ce&tions are a"" de1ined in t$e <a#a.lang &ac,age. Exce"tion C&ass Hierarchy 8$ro+ab"e Error Fin,ageError3 ... Virtua"Mac$ineError3 ... E=ce&tion 4"ass7ot!oundE=ce&tion3 4"one7ot%u&&ortedE=ce&tion3 I""ega"AccessE=ce&tion3 InstantiationE=ce&tion3 Interru&tedE=ce&tion3 IOE=ce&tion3 RuntimeE=ce&tion3

EO!E=ce&tion3 !i"e7ot!oundE=ce&tion3 ... Arit$meticE=ce&tion3 Array%toreE=ce&tion3 4"ass4astE=ce&tion3 I""ega"ArgumentE=ce&tion3 ;I""ega"8$read%tateE=ce&tion and 7umber!ormatE=ce&tion as subc"asses> I""ega"Monitor%tateE=ce&tion3 Inde=OutO1#oundsE=ce&tion3 7egati eArray%i*eE=ce&tion3 7u""PointerE=ce&tion3 %ecurityE=ce&tion

...

,a!le ;: Exception -lass Hierarchy

7o+ t$at youLre -uite 1ami"iar +it$ se era" e=ce&tion c"asses3 it is time to introduce to t$is ru"e' Mu"ti&"e catc$es s$ou"d be ordered 1rom subc"ass to su&erc"ass. class 1ultiple6atch<rror {
Introduction to Programming II Page .1

J.E.D.I.

public static #oid main$String args !%{ tr) { int a = Bnteger&parseBnt$args '!%" int b = Bnteger&parseBnt$args 3!%" S)stem&out&println$a9b%" } catch $<2ception e% { S)stem&out&println$e%" } catch $,rra)Bnde27ut7fEounds<2ception e4% { S)stem&out&println$e4%" } S)stem&out&println$=,fter tr)LcatchLcatch&=%" }

4om&i"ing t$e code +ou"d &roduce t$is error message since t$e Exception c"ass is a su&erc"ass o1 t$e /rrayIndex8ut8f9oundsException c"ass. 1ultiple6atch<rror&8a#a:M: e2ception 8a#a&lang&,rra)Bnde27ut7fEounds<2ception has alread) been caught } catch $,rra)Bnde27ut7fEounds<2ception e4% {

2.5.2 Chec#ed and 8nchec#ed %5ceptions


An e=ce&tion is eit$er c$ec,ed or unc$ec,ed. A c$ec,ed e=ce&tions is Bust an e=ce&tion t$at is c$ec,ed by Ja a com&i"er. 8$e com&i"er ma,es sure t$at t$e &rogram eit$er catc$es or "ists t$e occurring e=ce&tion in t$e throws c"ause. I1 t$e c$ec,ed e=ce&tion is neit$er caug$t nor "isted3 t$en a com&i"er error +i"" occur. 2n"i,e c$ec,ed e=ce&tions3 unc$ec,ed e=ce&tions are not subBect to com&i"eCtime c$ec,ing 1or e=ce&tion $and"ing. 8$e bui"tCin unc$ec,ed e=ce&tion c"asses are Error3 RuntimeE=ce&tion3 and t$eir subc"asses. 8$us3 t$ese ty&e o1 e=ce&tions are no "onger c$ec,ed because $and"ing a"" suc$ e=ce&tions may ma,e t$e &rogram c"uttered and may most "i,e"y become a nuisance.

2.5.3 8ser-De+ined %5ceptions


A"t$oug$ se era" e=ce&tion c"asses a"ready e=ist in t$e Ba a."ang &ac,age3 t$e bui"tCin e=ce&tion c"asses are not enoug$ to co er a"" &ossib"e ty&es o1 e=ce&tion t$at may occur. )ence3 it is ery "i,e"y t$at youL"" +ant to create your o+n e=ce&tion. !or creating your o+n e=ce&tion3 youL"" Bust $a e to create a c"ass t$at e=tends t$e RuntimeE=ce&tion ;or E=ce&tion> c"ass. 8$en3 it is u& to you to customi*e t$e c"ass according to t$e &rob"em you are so" ing. Members and constructors may be added to your e=ce&tion c"ass. )ere is an e=am&"e. class HateString<2ception e2tends Kuntime<2ception{ 9* -o longer add an) member or constructor *9 } class .estHateString { public static #oid main$String args !% {
Introduction to Programming II Page .2

J.E.D.I.

String input = =in#alid input=" tr) { if $input&eJuals$=in#alid input=%% { throw new HateString<2ception$%" } S)stem&out&println$=String accepted&=%" } catch $HateString<2ception e% { S)stem&out&println$=B hate this string: = ( input ( =&=%" }

)ere is t$e e=&ected out&ut o1 t$e code' B hate this string: in#alid input&

2.

Assertions

2. .1 4hat are Assertions6


Assertions a""o+ t$e &rogrammer to 1ind out i1 an assum&tion +as met. !or e=am&"e3 a date +it$ a mont$ +$ose range is not bet+een 1 and 12 s$ou"d be considered as in a"id. 8$e &rogrammer may assert t$at t$e mont$ s$ou"d "ie bet+een t$is range. A"t$oug$ it is &ossib"e to use ot$er constructs to simu"ate t$e 1unctiona"y o1 assertions3 it +ou"d be $ard to do t$is in suc$ a +ay t$at t$e assertion 1eature cou"d be disab"ed. 8$e nice t$ing about assertions is t$at t$e user $as t$e o&tion to turn it o11 or on at runtime. Assertions can be considered as an e=tension o1 comments +$erein t$e assert statement in1orms t$e &erson reading t$e code t$at a &articu"ar condition s$ou"d a"+ays be satis1ied. 9it$ assertions3 t$ere is no need to read t$roug$ eac$ o1 t$e comments to 1ind out t$e assum&tions made in t$e code. Instead3 running t$e &rogram itse"1 +i"" in1orm you i1 t$e assertions made are true or not. In t$e case t$at an assertion is not true3 an /ssertionError +i"" be t$ro+n.

2. .2 %nabling or Disabling Assertions


2sing assertions does not re-uire im&orting t$e <a#a.util.assert &ac,age. 8$ey are idea""y used to c$ec, t$e &arameters o1 nonC&ub"ic met$ods since &ub"ic met$ods can direct"y be accessed by any ot$er c"asses. It is &ossib"e t$at t$e aut$ors o1 t$ese ot$er c"asses are not a+are t$at t$ey +i"" $a e assertions enab"ed. 8$e &rogram may not +or, &ro&er"y in t$is case. !or nonC&ub"ic met$ods3 t$ese are genera""y ca""ed by codes +ritten by &eo&"e +$o $a e access to t$e met$ods. 8$us3 t$ey are a+are t$at +$en running t$eir code3 assertion s$ou"d be enab"ed. 8o com&i"e 1i"es t$at use assertions3 an e=tra command "ine &arameter is re-uired as s$o+n be"o+. 8a#ac Nsource 3&? 1)Program&8a#a I1 you +ant to run t$e &rogram +it$out t$e assertion 1eature3 Bust run t$e &rogram norma""y. 8a#a 1)Program )o+e er3 i1 you +ant to enab"e assertions3 you need to use t$e =ena!leassertions or =ea
Introduction to Programming II Page ..

J.E.D.I.

s+itc$. 8a#a Nenableassertions 1)Program 8o enab"e runtime assertion c$ec,ing in 7et#eans IDE3 sim&"y 1o""o+ t$ese ste&s' 1. Foo, 1or t$e &roBect name in t$e 1ro<ects &ane" on t$e "e1t. Rig$t c"ic, on t$e &roBect name or icon. 2. %e"ect 1roperties. 8$is is t$e "ast o&tion o1 t$e dro&Cdo+n menu. .. 4"ic, on $un 1rom t$e 4ategories &ane" on t$e "e1t. 0. Enter %ea 1or >0 8ptions te=t 1ie"d. (. 4"ic, on 8? button. 6. 4om&i"e and run t$e &rogram as usua". 8$e 1o""o+ing screen s$ots +i"" $e"& you understand t$e gi en ste&s'

Figure ;.1: Ena!ling /ssertions with 3et9eans = Steps 1 @ ;

Introduction to Programming II

Page .0

J.E.D.I.

Figure ;.;: Ena!ling /ssertions with 3et9eans = Step A

Introduction to Programming II

Page .(

J.E.D.I.

Figure ;.A: Ena!ling /ssertions with 3et9eans = Step 2

Introduction to Programming II

Page .6

J.E.D.I.

2. .3 Assert -)nta5
8$e assert statement $as t+o 1orms. 8$e sim&"er 1orm $as t$e 1o""o+ing synta=' assert <e2pression3>" +$ere <expression1 is t$e condition t$at is asserted to be true. 8$e ot$er 1orm uses t+o e=&ressions and t$e synta= 1or t$is 1ormat is s$o+n be"o+. assert <e2pression3> : <e2pression4>" +$ere <expression1 is t$e condition t$at is asserted to be true and <expression; some in1ormation $e"&1u" in diagnosing +$y t$e statement 1ai"ed. )ere is an e=am&"e t$at uses t$e sim&"e 1orm o1 assert. class ,ge,ssert { public static #oid main$String args !% { int age = Bnteger&parseBnt$args '!%" assert$age>'%" 9* if age is #alid $i&e&0 age>'% *9 if $age >= 3O% { S)stem&out&println$G6ongratsI PouQre an adultI =%H%" } } } 8$is code t$ro+s an /ssertionError +$en t$e &assed argument3 i.e.3 args*"+3 $as an integer a"ue "ess t$an 1 since t$e code asserts t$at age s$ou"d be greater t$an 0. In t$is case3 t$e 1o""o+ing error message is dis&"ayed at runtime. <2ception in thread =main= 8a#a&lang&,ssertion<rror at ,ge,ssert&main$,ge,ssert&8a#a:?% Ra#a Kesult: 3 Passing an argument a"ue t$at is greater t$an 0 but "ess t$an 1/ causes t$e &rogram to dis&"ay no out&ut. !or an argument a"ue at "east e-ua" to 1/3 t$e 1o""o+ing is t$e e=&ected out&ut' 6ongratsI PouQre an adultI =% 8$e succeeding code is simi"ar to t$e &re ious e=am&"e e=ce&t t$at is gi es additiona" in1ormation on t$e e=ce&tion t$at $as occurred. 8$is uses t$e second assert synta=. class ,ge,ssert { public static #oid main$String args !% { int age = Bnteger&parseBnt$args '!%" assert$age>'% : =age should at least be 3=" 9* if age is #alid $i&e&0 age>'% *9 if $age >= 3O% { S)stem&out&println$G6ongratsI PouQre an adultI =%H%" } } } 9$en t$e user in&uts an argument "ess t$an 13 an /ssertionError occurs and additiona" in1ormation on t$e e=ce&tion is dis&"ayed. !or t$is scenario3 t$e 1o""o+ing out&ut is
Introduction to Programming II Page .6

is

J.E.D.I.

dis&"ayed. <2ception in thread =main= 8a#a&lang&,ssertion<rror: age should at least be 3 at ,ge,ssert&main$,ge,ssert&8a#a:?% Ra#a Kesult: 3 !or t$e ot$er cases3 t$is &rogram gi es simi"ar out&ut to t$e &re ious e=am&"e.

Introduction to Programming II

Page ./

J.E.D.I.

2.! %5ercises
2.!.1 7e5adeci*al to Deci*al
5i en a $e=adecima" number as in&ut. 4on ert t$is number to its decima" e-ui a"ent. De1ine your o+n e=ce&tion c"ass and $and"e t$e case +$erein t$e user in&uts an in a"id $e=adecima" number.

2.!.2 "rinting a Dia*ond


5i en a &ositi e integer as in&ut. Print out a diamond using asteris,s based on t$e number entered by t$e user. 9$en t$e user enters a nonC&ositi e integer3 use assertions to $and"e t$is &rob"em. !or e=am&"e3 i1 t$e user in&uts t$e integer .3 your &rogram s$ou"d &rint out a diamond in t$e +it$ t$is 1ormat. O OOO OOOOO OOO O

Introduction to Programming II

Page .?

J.E.D.I.

4 Ad(anced Programming Techniques


3.1 Objectives
8$is modu"e introduces some ad anced &rogramming tec$ni-ues. Jou +i"" "earn about recursion and abstract data ty&es in t$is section. A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. De1ine and a&&"y recursion in &rogramming 2. Di11erentiate bet+een stac,s and -ueues 2. Im&"ement se-uentia" im&"ementation o1 stac,s and -ueues .. Im&"ement "in,ed im&"ementation o1 stac,s and -ueues 0. 2se e=isting -ollection c"asses

3.2 9ecursion
3.2.1 4hat is 9ecursion6
Recursion is a &o+er1u" &rob"emCso" ing tec$ni-ue t$at can be a&&"ied +$en t$e nature o1 t$e &rob"em is re&etiti e. Indeed3 t$is ty&e o1 &rob"ems are so" ab"e using iteration ;i.e.3 using "oo&ing constructs suc$ as for3 while and doC+$i"e>. In 1act3 iteration is a more e11icient too" com&ared to recursion but recursion &ro ides a more e"egant so"ution to t$e &rob"em. In recursion3 met$ods are a""o+ed to ca"" u&on itse"1. 8$e data &assed into t$e met$od as arguments are stored tem&orari"y onto a stac, unti" ca""s to t$e met$od $a e been com&"eted.

3.2.2 9ecursion :s. (teration


!or a better understanding o1 recursion3 "et us "oo, at $o+ it aries 1rom t$e tec$ni-ue o1 iteration. )and"ing &rob"ems +it$ re&etiti e nature using iteration re-uires e=&"icit use o1 re&etition contro" structures. Mean+$i"e3 1or recursion3 t$e tas, is re&eated by ca""ing a met$od re&etiti e"y. 8$e idea $ere is to de1ine t$e &rob"em in terms o1 sma""er instances o1 itse"1. 4onsider com&uting 1or t$e 1actoria" o1 a gi en integer. ItLs recursi e de1inition can be described as 1o""o+s' 1actoria";n> P 1actoria";nC1> O nQ 1actoria";1> P 1. !or e=am&"e3 t$e 1actoria" o1 2 is e-ua" to t$e 1actoria";1>O23 +$ic$ in turn is e-ua" to 2. 8$e 1actoria" o1 . is 63 +$ic$ is e-ua" to t$e 1actoria";2>O..

Introduction to Programming II

Page 00

J.E.D.I.

Figure A.1: Factorial Example

9it$ iteration3 t$e &rocess terminates +$en t$e "oo& condition 1ai"s. In t$e case o1 using recursion3 t$e &rocess ends once a &articu"ar condition ca""ed t$e base case is satis1ied. 8$e base case is sim&"y t$e sma""est instance o1 t$e &rob"em. !or e=am&"e3 as seen in t$e recursi e de1inition o1 1actoria"3 t$e sim&"est case is +$en t$e in&ut is 1. 1 1or t$is &rob"em is t$e base case. 8$e use o1 iteration and recursion can bot$ "ead to in1inite "oo&s i1 t$ese are not used correct"y. IterationLs ad antage o er recursion is good &er1ormance. It is 1aster com&ared to recursion since &assing o1 &arameters to a met$od causes ta,es some 4P2 time. )o+e er3 recursion encourages good so1t+are engineering &ractice because t$is tec$ni-ue usua""y resu"t in s$orter code t$at is easier to understand and it a"so &romotes reusabi"ity o1 a &re ious"y im&"emented so"ution. 4$oosing bet+een iteration and recursion is a matter o1 ba"ancing good &er1ormance and good so1t+are engineering.

3.2.3 ;actorials/ An %5a*ple


8$e 1o""o+ing code s$o+s $o+ to com&ute 1or t$e nt$ 1actoria" using t$e tec$ni-ue o1 iteration. class AactorialBter { static int factorial$int n% { int result = 3" for $int i = n" i > 3" iLL% { result *= i" } return result" } public static #oid main$String args !% { int n = Bnteger&parseBnt$args '!%" S)stem&out&println$factorial$n%%" } }

Introduction to Programming II

Page 01

J.E.D.I.

)ere is t$e e-ui a"ent code t$at uses t$e recursion too" instead. class AactorialKecur { static int factorial$int n% { if $n == 3% { 9* .he base case *9 return 3" } 9* Kecursi#e definition" SelfLin#ocation *9 return factorial$nL3%*n" } public static #oid main$String args !% { int n = Bnteger&parseBnt$args '!%" S)stem&out&println$factorial$n%%" } } 4onsider t$e e=&ected out&ut o1 t$e gi en codes 1or some integers. 8race +$at $a&&ens in t$e code 1or some in&ut. )ere are some sam&"e integers +it$ t$eir corres&onding out&ut. a> In&ut' 1 3 b> In&ut' . S c> In&ut' ( 34'

Introduction to Programming II

Page 02

J.E.D.I.

3.2.4 "rint n in an) <ase/ Another %5a*ple


7o+3 consider t$e &rob"em o1 &rinting a decima" number in a base s&eci1ied by t$e user. Reca"" t$at t$e so"ution 1or t$is is to use re&etiti e di ision and to +rite t$e remainders in re erse. 8$e &rocess terminates +$en t$e di idend is "ess t$an t$e base. Assume t$at t$e in&ut decima" number is 10 and +e +ant to con ert it to base /. )ere is t$e so"ution using &en and &a&er.

!rom t$e so"ution abo e3 10 is e-ui a"ent to 12 base /. )ere is anot$er e=am&"e. 8$e in&ut decima" is 16( to be con erted to base 16.

16( is e-ui a"ent to A( base 16. 7ote' AP10. 8$is is t$e iterati e so"ution 1or t$is &rob"em. class Dec.o7thers { public static #oid main$String args !% { int num = Bnteger&parseBnt$args '!%" int base = Bnteger&parseBnt$args 3!%" printEase$num0 base%" } static #oid printEase$int num0 int base% { int rem = 3" String digits = ='34>?CSTOMabcdef=" String result = ==" 9* the iterati#e step *9 while $numI='% { rem = numUbase" num = num9base" result = result&concat$digits&char,t$rem%(==%" } 9* printing the re#erse of the result *9 for$int i = result&length$%L3" i >= '" iLL% { S)stem&out&print$result&char,t$i%%" } } }

Introduction to Programming II

Page 0.

J.E.D.I.

7o+3 t$is is t$e recursi e e-ui a"ent o1 t$e so"ution abo e. class Dec.o7thersKecur { static #oid printEase$int num0 int base% { String digits = ='34>?CSTOMabcdef=" 9* Kecursi#e step*9 if $num >= base% { printEase$num9base0 base%" } 9* Ease case: num < base *9 S)stem&out&print$digits&char,t$numUbase%%" } public static #oid main$String args !% { int num = Bnteger&parseBnt$args '!%" int base = Bnteger&parseBnt$args 3!%" printEase$num0 base%" } } 8o gain a better understanding o1 t$e code3 trace it 1or a set o1 in&ut. )ere are some sam&"e in&ut. a> 7um' 103 base' 2 3'3' b> 7um' 1003 base' / 3?? c> 7um' 2003 base' ? 4?4

Introduction to Programming II

Page 00

J.E.D.I.

3.3 Abstract Data 1)pes


3.3.1 4hat is an Abstract Data 1)pe6
An abstract data ty&e ;AD8> is a co""ection o1 data e"ements &ro ided +it$ a set o1 o&erations t$at are de1ined on t$e data e"ements. %tac,s3 -ueues and binary trees are some e=am&"es o1 AD8. In t$is section3 you +i"" be "earning about stac,s and -ueues.

3.3.2 -tac#s
A stac, is a set o1 data e"ements +$erein mani&u"ation o1 t$e e"ements is a""o+ed on"y at t$e to& o1 t$e stac,. It is a "inear"y ordered co""ection o1 data on +$ic$ t$e disci&"ine o1 M"ast in3 1irst outN ;FI!O> is im&osed. %tac,s are use1u" 1or a ariety o1 a&&"ications suc$ as &attern recognition and con ersion among in1i=3 &ost1i= and &re1i= notations. 8$e t+o o&erations associated +it$ stac,s are t$e &us$ and &o& o&erations. Pus$ sim&"y means inserting at t$e to& o1 t$e stac, +$ereas &o& re1ers to remo ing t$e e"ement at t$e to& o1 t$e stac,. 8o understand $o+ t$e stac, +or,s3 imagine $o+ you +ou"d add or remo e a &"ate 1rom a stac, o1 &"ates. Jour instinct +ou"d te"" you to add or remo e on"y at t$e to& o1 t$e stac, because ot$er+ise3 t$ere is a danger o1 causing t$e stac, o1 &"ates to 1a"". )ere is a sim&"e i""ustration o1 $o+ a stac, "oo,s "i,e. nC1 ... 6 ( 0 . 2 1 0

Jay* @4 JoBo 8oto @y"a DM:

top

botto*

,a!le A: Stac' illustration

8$e stac, is 1u"" i1 t$e to& reac$es t$e ce"" "abe"ed nC1. I1 t$e to& is e-ua" to C13 t$is indicates t$at t$e stac, is em&ty.

3.3.3 =ueues
8$e -ueue is anot$er e=am&"e o1 an AD8. It is a "inear"y ordered co""ection o1 e"ements +$ic$ 1o""o+ t$e disci&"ine o1 M1irstCin3 1irstCoutN. Its a&&"ications inc"ude Bob sc$edu"ing in o&erating system3 to&o"ogica" sorting and gra&$ tra ersa". En-ueue and de-ueue are t$e o&erations associated +it$ -ueues. En-ueue re1ers to inserting at t$e end o1 t$e -ueue +$ereas de-ueue means remo ing 1ront e"ement o1 t$e -ueue. 8o remember $o+ a -ueue +or,s3 t$in, o1 t$e -ueueLs "itera" meaning R a "ine. Imagine yourse"1 "ining u& to get t$e c$ance meeting your 1a orite star u& c"ose. I1 a ne+ &erson +ou"d "i,e to Boin t$e "ine3 t$is &erson +ou"d $a e to go to t$e end o1 t$e "ine. Ot$er+ise3 t$ere +ou"d &robab"y be some 1ig$t. 8$is is $o+ en-ueue +or,s. 9$o gets to meet $isA$er 1a orite star 1irst among t$ose +$o are +aiting in t$e "ineD It s$ou"d $a e
Introduction to Programming II Page 0(

J.E.D.I.

been t$e 1irst &erson in t$e "ine. 8$is &erson gets to "ea e t$e "ine 1irst. Re"ate t$is to $o+ de-ueue +or,s. )ere is a sim&"e i""ustration o1 $o+ a -ueue "oo,s "i,e. 0 1 2 E e +ront . Jay* 0 @4 ( JoBo 6 8oto 6 @y"a / DM: end ? ... Insert De"ete nC1

,a!le 2: Bueue illustration

8$e -ueue is em&ty i1 end is "ess t$an 1ront. Mean+$i"e3 it is 1u"" +$en t$e end is e-ua" to nC1.

3.3.4 -e>uential and ?in#ed 9epresentation


AD8s can genera""y be re&resented using se-uentia" and "in,ed re&resentation. It is easier to create t$e se-uentia" re&resentation +it$ t$e use o1 arrays. )o+e er3 t$e &rob"em +it$ an array is its "imited si*e3 ma,ing it in1"e=ib"e. Memory s&ace is eit$er +asted or not enoug$ +it$ use o1 arrays. 4onsider t$is scenario. JouL e created an array and dec"ared it to be ab"e to store a ma=imum o1 (0 e"ements. I1 t$e user on"y inserts e=act"y ( e"ements3 ta,e note t$at 0( s&aces +ou"d $a e been +asted. On t$e ot$er $and3 i1 t$e user +ants to insert (1 e"ements3 t$e s&aces &ro ided in t$e array +ou"d not $a e been enoug$. 4om&ared to se-uentia" re&resentation3 t$e "in,ed re&resentation may be a "itt"e more di11icu"t to im&"ement but it is more 1"e=ib"e. It ada&ts to t$e memory need o1 t$e user. A more detai"ed e=&"anation on "in,ed re&resentation are discussed in a "ater section.

Introduction to Programming II

Page 06

J.E.D.I.

3.3.5 -e>uential 9epresentation o+ an (nteger -tac#


class SeJStac/ { int top = L3" 9* initiall)0 the stac/ is empt) *9 int memSpace !" 9* storage for integers *9 int limit" 9* si:e of memSpace *9 SeJStac/$% { memSpace = new int 3'!" limit = 3'" } SeJStac/$int si:e% { memSpace = new int si:e!" limit = si:e" } boolean push$int #alue% { top((" 9* chec/ if the stac/ is full *9 if $top < limit% { memSpace top! = #alue" } else { topLL" return false" } return true" } int pop$% { int temp = L3" 9* chec/ if the stac/ is empt) *9 if $top >= '% { temp = memSpace top!" topLL" } else { return L3" } return temp" } public static #oid main$String args !% { SeJStac/ m)Stac/ = new SeJStac/$>%" m)Stac/&push$3%" m)Stac/&push$4%" m)Stac/&push$>%" m)Stac/&push$?%" S)stem&out&println$m)Stac/&pop$%%" S)stem&out&println$m)Stac/&pop$%%" S)stem&out&println$m)Stac/&pop$%%" S)stem&out&println$m)Stac/&pop$%%" } }

Introduction to Programming II

Page 06

J.E.D.I.

8$e 1o""o+ing 1igure gi es a trace o1 SeCStac'Hs main met$od.

Figure A.;:,race of SeCStac'

Introduction to Programming II

Page 0/

J.E.D.I.

3.3.

?in#ed ?ists

#e1ore im&"ementing t$e "in,ed re&resentation o1 stac,s. FetLs 1irst study $o+ to create "in,ed re&resentation. In &articu"ar3 +eL"" be "oo,ing at "in,ed "ists. 8$e "in,ed "ist is a dynamic structure as o&&osed to t$e array3 +$ic$ is a static structure. 8$is means t$at t$e "in,ed "ist can gro+ and s$rin, in si*e de&ending on t$e need o1 t$e user. A "in,ed "ist is de1ined as a co""ection o1 nodes3 eac$ o1 +$ic$ consists o1 some data and a "in, or a &ointer to t$e ne=t node in t$e "ist. 8$e 1igure be"o+ s$o+s $o+ a node "oo,s "i,e.

Figure A.A: / node

)ere is an e=am&"e o1 a nonCem&ty "in,ed "ist +it$ t$ree nodes.

Figure A.2: / non%empty lin'ed list with three nodes

)ere is $o+ t$e node c"ass is im&"emented. 8$is c"ass can be used to create "in,ed "ists. class -ode { int data" -ode ne2t-ode" } 9* integer data contained in the node *9 9* the ne2t node in the list *9

class .est-ode { public static #oid main$String args !% { -ode empt);ist = null" 9* create an empt) list *9 9* head points to 3st node in the list *9 -ode head = new -ode$%" 9* initiali:e 3st node in the list *9 head&data = C" head&ne2t-ode = new -ode$%" head&ne2t-ode&data = 3'" 9* null mar/s the end of the list *9 head&ne2t-ode&ne2t-ode = null" 9* print elements of the list *9 -ode curr-ode = head" while $curr-ode I= null% { S)stem&out&println$curr-ode&data%" curr-ode = curr-ode&ne2t-ode" } } }

Introduction to Programming II

Page 0?

J.E.D.I.

)ere is a trace o1 ,est3odeHs main met$od.

Figure A.D: ,race of ,est3ode

Introduction to Programming II

Page (0

J.E.D.I.

3.3.! ?in#ed 9epresentation o+ an (nteger -tac#


7o+ t$at youL e "earned about "in,ed "ist. JouLre no+ ready to a&&"y +$at youL e "earned to im&"ement t$e "in,ed re&resentation o1 a stac,. class D)namicBntStac/{ pri#ate BntStac/-ode top" 9* head or top of the stac/ *9 class BntStac/-ode { 9* node class *9 int data" BntStac/-ode ne2t" BntStac/-ode$int n% { data = n" ne2t = null" } } #oid push$int n%{ 9* no need to chec/ for o#erflow *9 BntStac/-ode node = new BntStac/-ode$n%" node&ne2t = top" top = node" } int pop$% { if $is<mpt)$%% { return L3" 9* ma) throw a userLdefined e2ception *9 } else { int n = top&data" top = top&ne2t" return n" } } boolean is<mpt)$%{ return top == null" } public static #oid main$String args !% { D)namicBntStac/ m)Stac/ = new D)namicBntStac/$%" m)Stac/&push$C%" m)Stac/&push$3'%" 9* print elements of the stac/ *9 BntStac/-ode curr-ode = m)Stac/&top" while $curr-odeI=null% { S)stem&out&println$curr-ode&data%" curr-ode = curr-ode&ne2t" } S)stem&out&println$m)Stac/&pop$%%" S)stem&out&println$m)Stac/&pop$%%" } } Here is the e2pected output of the code:

Figure A.E: Expected 8utput of :ynamicStac'

Introduction to Programming II

Page (1

J.E.D.I.

Figure A.F: ,race of :ynamicStac'

Introduction to Programming II

Page (2

J.E.D.I.

3.3.$ ,ava Collections


JouH e no+ been introduced to t$e 1oundations o1 abstract data ty&es. In &articu"ar3 youH e "earned about t$e basics o1 "in,ed "ists3 stac,s and -ueues. A good ne+s is t$ese abstract data ty&es $a e a"ready been im&"emented and inc"uded in Ja a. 8$e Stac' and 6in'ed6ist c"asses are a ai"ab"e 1or use +it$out a 1u"" understanding o1 t$ese conce&ts. )o+e er3 as com&uter scientists3 it is im&ortant t$at +e understand t$e abstract data ty&es. 8$us3 a detai"ed e=&"anation +as sti"" gi en in t$e &receding section. 9it$ t$e re"ease o1 J2%E(.03 t$e Bueue inter1ace +as a"so made a ai"ab"e. !or t$e detai"s on t$ese c"asses and inter1ace3 &"ease re1er to t$e Ja a API documentation. Ja a $as &ro ided us +it$ ot$er -ollection c"asses and inter1aces3 +$ic$ are a"" 1ound in t$e <a#a.util &ac,age. E=am&"es o1 -ollection c"asses inc"ude 6in'ed6ist3 /rray6ist3 HashSet and ,reeSet. 8$ese c"asses are actua""y im&"ementations o1 di11erent co""ection inter1aces. At t$e root o1 t$e co""ection inter1ace $ierarc$y is t$e -ollection inter1ace. A co""ection is Bust a grou& o1 obBects t$at are ,no+n as its e"ements. 4o""ections may a""o+ du&"icates and re-uires no s&eci1ic ordering. 8$e %D@ does not &ro ide any bui"tCin im&"ementations o1 t$is inter1ace but direct subinter1aces3 t$e Set inter1ace and t$e 6ist inter1ace3 are a ai"ab"e. 7o+3 +$at is t$e di11erence bet+een t$ese t+o inter1aces. A set is an unordered co""ection t$at contains no du&"icates. Mean+$i"e3 a "ist is an ordered co""ection o1 e"ements +$ere du&"icates are &ermitted. HashSet3 6in'edHashSet and ,reeSet are some ,no+n im&"ementing c"asses o1 t$e inter1ace Set. /rray6ist3 6in'ed6ist and >ector are some o1 t$e c"asses im&"ementing t$e inter1ace 6ist. <root interface -ollection

<interface Set <implementing classes )as$%et Fin,ed)as$%et 8ree%et

<interface 6ist <implementing classes ArrayFist Fin,edFist Vector

,a!le D: Ga#a collections

8$e 1o""o+ing is a "ist o1 some o1 t$e -ollection met$ods &ro ided in t$e 4o""ections API o1 Ja a 2 P"at1orm %E 1.0.1. In Ja a 2 P"at1orm %E .1.(.03 t$ese met$ods +ere modi1ied to accomodate generic ty&es. %ince generic ty&es $a e not been discussed yet3 it is ad isab"e to consider t$ese met$ods 1irst. It is ad ised t$at you re1er to ne+er -ollection met$ods once you understand t$e generic ty&es3 +$ic$ is discussed in a "atter c$a&ter. Co&&ection Methods public boolean add$7b8ect o% Inserts t$e 8!<ect o to t$is co""ection. Returns true i1 o +as success1u""y added to t$e co""ection. public #oid clear$% Remo es a"" e"ements o1 t$is co""ection. public boolean remo#e$7b8ect o% Remo es a sing"e instance o1 t$e 8!<ect o 1rom t$is co""ection3 i1 it is &resent. Returns true i1 o +as 1ound and remo ed 1rom t$e co""ection. public boolean contains$7b8ect o% Returns true i1 t$is co""ection contains t$e 8!<ect o. public boolean is<mpt)$% Returns true i1 t$is co""ection does not contain any obBect or e"ement.
Introduction to Programming II Page (.

J.E.D.I.

public int si:e$% Returns t$e number o1 e"ements in t$is co""ection. public Bterator iterator$% Returns an iterator t$at a""o+s us to go t$roug$ t$e contents o1 t$is co""ection. public boolean eJuals$7b8ect o% Returns true i1 t$e 8!<ect o is e-ua" to t$is co""ection. public int hash6ode$% Returns t$e $as$ code a"ue ;i.e.3 t$e ID> 1or t$is co""ection. %ame obBects or co""ections $a e t$e same $as$ code a"ue or ID.
,a!le E: 0ethods of class -ollection

P"ease re1er to t$e API documentation 1or a com&"ete "ist o1 t$e met$ods 1ound in t$e -ollection3 6ist and Set inter1ace. 9eL"" no+ "oo, at some co""ection c"asses. P"ease re1er to t$e API 1or t$e "ist o1 met$ods inc"uded in t$ese c"asses. In a &receding section3 youL e seen $o+ to im&"ement a "in,ed "ist on your o+n. 8$e Ja a %D@ a"so $as &ro ided us +it$ a bui"tCin im&"ementation o1 t$e "in,ed "ist. 8$e 6in'ed6ist c"ass contains met$ods t$at a""o+s "in,ed "ists to be used as stac,s3 -ueues or some ot$er AD8. 8$e 1o""o+ing code s$o+s $o+ to use t$e 6in'ed6ist c"ass. import 8a#a&util&*" class ;in/ed;istDemo { public static #oid main$String args !% { ;in/ed;ist list = new ;in/ed;ist$%" list&add$new Bnteger$3%%" list&add$new Bnteger$4%%" list&add$new Bnteger$>%%" list&add$new Bnteger$3%%" S)stem&out&println$list ( =0 si:e = = ( list&si:e$%%" list&addAirst$new Bnteger$'%%" list&add;ast$new Bnteger$?%%" S)stem&out&println$list%" S)stem&out&println$list&getAirst$% ( =0 = ( list&get;ast$%%" S)stem&out&println$list&get$4% ( =0 = ( list&get$>%%" list&remo#eAirst$%" list&remo#e;ast$%" S)stem&out&println$list%" list&remo#e$new Bnteger$3%%" S)stem&out&println$list%" list&remo#e$>%" S)stem&out&println$list%" list&set$40 =one=%" S)stem&out&println$list%" } } 8$e /rray6ist is a resi*ab"e Ana"y*e t$e 1o""o+ing code. import 8a#a&util&*" class ,rra);istDemo { public static #oid main$String args !% { ,rra);ist al = new ,rra);ist$4%"
Introduction to Programming II Page (0

ersion an ordinary array. It im&"ements t$e 6ist inter1ace.

J.E.D.I.

} } 8$e HashSet is an im&"ementation o1 t$e Set inter1ace t$at uses a $as$ tab"e. 8$e use o1 a $as$ tab"e a""o+s easier and 1aster "oo, u& o1 e"ements. 8$e tab"e uses a 1ormu"a to determine +$ere an obBect is stored. 8race t$is &rogram t$at uses t$e HashSet c"ass. import 8a#a&util&*" class HashSetDemo { public static #oid main$String args !% { HashSet hs = new HashSet$C0 '&Cf%" S)stem&out&println$hs&add$=one=%%" S)stem&out&println$hs&add$=two=%%" S)stem&out&println$hs&add$=one=%%" S)stem&out&println$hs&add$=three=%%" S)stem&out&println$hs&add$=four=%%" S)stem&out&println$hs&add$=fi#e=%%" S)stem&out&println$hs%" } } 8$e ,reeSet is an im&"ementation o1 t$e Set inter1ace t$at uses a tree. 8$is c"ass ensures t$at t$e sorted set +i"" be arranged in ascending order. 4onsider $o+ t$e ,reeSet c"ass +as used in t$e 1o""o+ing source code. import 8a#a&util&*" class .reeSetDemo { public static #oid main$String args !% { .reeSet ts = new .reeSet$%" ts&add$=one=%" ts&add$=two=%" ts&add$=three=%" ts&add$=four=%" S)stem&out&println$ts%" } }

S)stem&out&println$al ( =0 si:e = = ( al&si:e$%%" al&add$=K=%" al&add$=@=%" al&add$=7=%" S)stem&out&println$al ( =0 si:e = = ( al&si:e$%%" al&remo#e$=@=%" S)stem&out&println$al ( =0 si:e = = ( al&si:e$%%" ;istBterator li = al&listBterator$%" while $li&has-e2t$%% S)stem&out&println$li&ne2t$%%" 7b8ect a ! = al&to,rra)$%" for $int i='" i<a&length" i((% S)stem&out&println$a i!%"

Introduction to Programming II

Page ((

J.E.D.I.

Figure A.H: ,reeSet Example

Introduction to Programming II

Page (6

J.E.D.I.

5 Tour o the java.lang Pac$age


4.1 Objectives
Ja a comes in +it$ many bui"tCin c"asses t$at you may 1ind use1u". FetHs e=&"ore t$ese c"asses. A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. A&&reciate and use e=isting Ja a c"asses 0ath String String9uffer 9ra&&er 1rocess System

4.2 1he Math Class


Ja a $as a"so &ro ided you +it$ &rede1ined constants and met$ods 1or &er1orming di11erent mat$ematica" o&erations suc$ as trigonometric 1unctions and "ogarit$ms. %ince t$ese met$ods are a"" static3 you can use t$em +it$out $a ing t$e need to instantiate a 0ath obBect. !or t$e com&"ete "ist o1 t$ese constants and met$ods3 &"ease re1er to t$e Ja a API documentation. Mean+$i"e3 $ere are some o1 t$e common met$ods you may 1ind use1u".

Introduction to Programming II

Page (6

J.E.D.I.

Math Methods public static double abs$double a% Returns t$e &ositi e a"ue o1 t$e &arameter. An o er"oaded met$od. 4an a"so ta,e in a 1"oat or an integer or a "ong integer as a &arameter3 in +$ic$ case t$e return ty&e is eit$er a 1"oat or an integer or a "ong integer3 res&ecti e"y. public static double random$% Returns a random &osti e a"ue greater t$an or e-ua" to 0.0 but "ess t$an 1.0. public static double ma2$double a0 double b% Returns t$e "arger a"ue bet+een t+o dou!le a"ues3 a and !. An o er"oaded met$od. 4an a"so ta,e in 1"oat or integer or "ong integer a"ues as &arameters3 in +$ic$ case t$e return ty&e is eit$er a 1"oat or an integer or a "ong integer3 res&ecti e"y. public static double min$double a0 double b% Returns t$e sma""er a"ue bet+een t+o dou!le a"ues3 a and !. An o er"oaded met$od. 4an a"so ta,e in 1"oat or integer or "ong integer a"ues as &arameters3 in +$ic$ case t$e return ty&e is eit$er a 1"oat or an integer or a "ong integer3 res&ecti e"y. public static double ceil$double a% Returns t$e sma""est integer greater t$an or e-ua" to t$e s&eci1ied &arameter a. public static double floor$double a% Returns t$e "argest integer t$at is "esser t$an or e-ua" to t$e s&eci1ied &arameter a. public static double e2p$double a% Returns Eu"erHs number e raised to t$e &o+er o1 t$e &assed argument a. public static double log$double a% Returns t$e natura" "ogarit$m ;base e> o1 a3 t$e dou!le a"ue &arameter. public static double pow$double a0 double b% Returns t$e dou!le a"ue o1 a raised to t$e dou!le a"ue o1 !. public static long round$double a% Returns t$e nearest long to t$e gi en argument. An o er"oaded met$od. 4an a"so ta,e in a float as an argument and returns t$e nearest int in t$is case. public static double sJrt$double a% Returns t$e s-uare root o1 t$e argument a. public static double sin$double a% Returns t$e trigonometric sine o1 t$e gi en ang"e a. public static double toDegrees$double angrad% Returns t$e degree a"ue a&&ro=imate"y e-ui a"ent to t$e gi en radian a"ue. public static double toKadians$double angdeg% Returns t$e radian a"ue a&&ro=imate"y e-ui a"ent to t$e gi en degree a"ue.
,a!le F: Some methods of class 0ath

Introduction to Programming II

Page (/

J.E.D.I.

8$e 1o""o+ing &rogram demonstrates $o+ t$ese met$ods are used. class 1athDemo { public static #oid main$String args !% { S)stem&out&println$=absolute #alue of LC: = ( 1ath&abs$LC%%" S)stem&out&println$=absolute #alue of C: = ( 1ath&abs$LC%%" S)stem&out&println$=random number$ma2 #alue is 3'%: = ( 1ath&random$%*3'%" S)stem&out&println$=ma2 of >&C and 3&4: = ( 1ath&ma2$>&C0 3&4%%" S)stem&out&println$=min of >&C and 3&4: = ( 1ath&min$>&C0 3&4%%" S)stem&out&println$=ceiling of >&C: = ( 1ath&ceil$>&C%%" S)stem&out&println$=floor of >&C: = ( 1ath&floor$>&C%%" S)stem&out&println$=e raised to 3: = ( 1ath&e2p$3%%" S)stem&out&println$=log 3': = ( 1ath&log$3'%%" S)stem&out&println$=3' raised to >: = ( 1ath&pow$3'0>%%" S)stem&out&println$=rounded off #alue of pi: = ( 1ath&round$1ath&PB%%" S)stem&out&println$=sJuare root of C = = ( 1ath&sJrt$C%%" S)stem&out&println$=3' radian = = ( 1ath&toDegrees$3'% ( = degrees=%" S)stem&out&println$=sin$M'%: = ( 1ath&sin$1ath&toKadians$M'%%%" } } )ere is a sam&"e out&ut o1 t$e gi en &rogram. 8ry running t$e &rogram yourse"1 and 1ee" 1ree to e=&eriment +it$ t$e gi en arguments. absolute #alue of LC: C absolute #alue of C: C random number$ma2 #alue is 3'%: ?&'OCC>>4>>C?TTS'C ma2 of >&C and 3&4: >&C min of >&C and 3&4: 3&4 ceiling of >&C: ?&' floor of >&C: >&' e raised to 3: 4&T3O4O3O4O?CM'?CC log 3': 4&>'4COC'M4MM?'?S 3' raised to >: 3'''&' rounded off #alue of pi: > sJuare root of C = 4&4>S'STMTT?MMTM 3' radian = CT4&MCTTMC3>'O4>4 degrees sin$M'%: 3&'

Introduction to Programming II

Page (?

J.E.D.I.

4.3 1he -tring and the -tring<u++er Class


8$e %tring c"ass &ro ided by t$e Ja a %D@ re&resents combinations o1 c$aracter "itera"s. 2n"i,e in ot$er &rogramming "anguages "i,e 4 or 4SS3 strings can be re&resented using an array o1 c$aracters or by sim&"y using t$e String c"ass. 8a,e note t$at a String obBect di11ers 1rom an array o1 c$aracters.

4.3.1 -tring Constructors


8$e String c"ass $as 11 constructors. 8o see $o+ some o1 t$ese constructors3 consider t$e gi en e=am&"e t$at 1o""o+s. 9* .his e2ample is ta/en from Dr& <ncarnacionQs notes& *9 class String6onstructorsDemo { public static #oid main$String args !% { String s3 = new String$%" 99 creates an empt) string char chars ! = { QhQ0 QeQ0 QlQ0 QlQ0 QoQ}" String s4 = new String$chars%" 99 s4 = =hello=" b)te b)tes ! = { QwQ0 QoQ0 QrQ0 QlQ0 QdQ }" String s> = new String$b)tes%" 99 s> = =world= String s? = new String$chars0 30 >%" String sC = new String$s4%" String sS = s4" S)stem&out&println$s3%" S)stem&out&println$s4%" S)stem&out&println$s>%" S)stem&out&println$s?%" S)stem&out&println$sC%" S)stem&out&println$sS%" } } )ere is t$e e=&ected out&ut o1 t$e gi en &rogram' hello world ell hello hello

4.3.2 -tring Methods


8$e 1o""o+ing is a "ist o1 some String met$ods. %tring Methods public char char,t$int inde2% Returns t$e c$aracter "ocated in t$e s&eci1ied index. public int compare.o$String anotherString% 4om&ares t$is string +it$ t$e s&eci1ied &arameter. Returns a negati e a"ue i1 t$is string comes "e=icogra&$ica""y be1ore t$e ot$er string3 0 i1 bot$ o1 t$e strings $a e t$e same a"ue and a &osti e a"ue i1 t$is string comes a1ter t$e ot$er string "e=icogra&$ica""y. public int compare.oBgnore6ase$String str% Fi,e com&are8o but ignores t$e case used in t$is string and t$e s&eci1ied string.

Introduction to Programming II

Page 60

J.E.D.I.

%tring Methods public boolean eJuals$7b8ect an7b8ect% Returns true i1 t$is string $as t$e same se-uence o1 c$aracters as t$at o1 t$e 8!<ect s&eci1ied3 +$ic$ s$ou"d be a String obBect. Ot$er+ise3 i1 t$e s&eci1ied &arameter is not a String obBect or i1 it doesnHt matc$ t$e se-uence o1 symbo"s in t$is string3 t$e met$od +i"" return 1a"se. public boolean eJualsBgnore6ase$String anotherString% Fi,e e-ua"s but ignores t$e case used in t$is string and t$e s&eci1ied string. public #oid get6hars$int srcEegin0 int src<nd0 char ! dst0 int dstEegin% 5ets t$e c$aracters 1rom t$is string starting at t$e src9egin inde= u& to t$e srcEnd inde= and co&ies t$ese c$aracters to t$e dst array starting at t$e dst9egin inde=. public int length$% Returns t$e "engt$ o1 t$is string. public String replace$char old6har0 char new6har% Returns t$e string +$erein a"" occurrences o1 t$e old-har in t$is string is re&"aced +it$ new-har. public String substring$int beginBnde20 int endBnde2% Returns t$e substring o1 t$is string starting at t$e s&eci1ied !eginIndex inde= u& to t$e endIndex inde=. public char ! to6har,rra)$% Returns t$e c$aracter array e-ui a"ent o1 t$is string. public String trim$% Returns a modi1ied co&y o1 t$is string +$erein t$e "eading and trai"ing +$ite s&ace are remo ed. public static String #alue7f$L% 8a,es in a sim&"e data ty&e suc$ as boo"ean3 integer or c$aracter3 or it ta,es in an obBect as a &arameter and returns t$e String e-ui a"ent o1 t$e s&eci1ied &arameter.
,a!le H: Some methods of class String

4onsider $o+ t$ese met$ods +ere used in t$e 1o""o+ing &rogram. class StringDemo { public static #oid main$String args !% { String name = =Ronathan=" S)stem&out&println$=name: = ( name%" S)stem&out&println$=>rd character of name: = ( name&char,t$4%%" 9* character that first appears alphabeticall) has lower unicode #alue *9 S)stem&out&println$=Ronathan compared to Solomon: = ( name&compare.o$=Solomon=%%" S)stem&out&println$=Solomon compared to Ronathan: = ( =Solomon=&compare.o$=Ronathan=%%" 9* QRQ has lower unicode #alue compared to Q8Q *9 S)stem&out&println$=Ronathan compared to 8onathan: = ( name&compare.o$=8onathan=%%" S)stem&out&println$=Ronathan compared to 8onathan $ignore
Introduction to Programming II Page 61

J.E.D.I.

case%: = ( name&compare.oBgnore6ase$=8onathan=%%" S)stem&out&println$=Bs Ronathan eJual to Ronathan5 = ( name&eJuals$=Ronathan=%%" S)stem&out&println$=Bs Ronathan eJual to 8onathan5 = ( name&eJuals$=8onathan=%%" S)stem&out&println$=Bs Ronathan eJual to 8onathan $ignore case%5 = ( name&eJualsBgnore6ase$=8onathan=%%" char char,rr ! = =Hi VV=&to6har,rra)$%" 9* -eed to add 3 to the endSrc inde2 of get6hars *9 =Ronathan=&get6hars$'0 40 char,rr0 >%" S)stem&out&print$=get6hars method: =%" S)stem&out&println$char,rr%" S)stem&out&println$=;ength of name: = ( name&length$%%" S)stem&out&println$=Keplace aQs with eQs in name: = ( name&replace$QaQ0 QeQ%%" 9* -eed to add 3 to the endBnde2 parameter of substring*9 S)stem&out&println$=, substring of name: = ( name&substring$'0 4%%" S)stem&out&println$=.rim W= a b c d e f W=: W== ( = a b c d e f =&trim$% ( =W==%" S)stem&out&println$=String representation of boolean e2pression 3'>3': = ( String&#alue7f$3'>3'%%" 9* toString method is implicitl) called in the println method*9 S)stem&out&println$=String representation of boolean e2pression 3'<3': = ( $3'<3'%%" 9* -ote thereQs no change in the String ob8ect name e#en after appl)ing all these methods& *9 S)stem&out&println$=name: = ( name%"

)ereHs t$e out&ut o1 t$e gi en &rogram. name: Ronathan >rd character of name: n Ronathan compared to Solomon: LM Solomon compared to Ronathan: M Ronathan compared to 8onathan: L>4 Ronathan compared to 8onathan $ignore case%: ' Bs Ronathan eJual to Ronathan5 true Bs Ronathan eJual to 8onathan5 false Bs Ronathan eJual to 8onathan $ignore case%5 true content of char,rr after get6hars method: Hi Ro ;ength of name: O Keplace aQs with eQs in name: Ronethen , substring of name: Ro .rim = a b c d e f =: =a b c d e f= String representation of boolean e2pression 3'>3': false String representation of boolean e2pression 3'<3': false name: Ronathan

Introduction to Programming II

Page 62

J.E.D.I.

4.3.3 1he -tring<u++er Class


Once a String obBect is created3 it can no "onger be modi1ied. A String9uffer obBect is simi"ar to a String obBect3 e=ce&t 1or t$e 1act t$at t$e String9uffer obBect is mutab"e or can be modi1ied. 9$ereas a String obBect is immutab"e3 String9uffer obBects are mutab"e. Its "engt$ and content may be c$anged t$roug$ some met$od ca""s. )ere are some o1 t$e met$ods in t$e String9uffer c"ass. P"ease re1er to t$e Ja a API documentation. %tring2u er Methods public int capacit)$% Returns t$e current ca&acity o1 t$is String9uffer obBect. public StringEuffer append$L% A&&ends t$e string re&resentation o1 t$e argument to t$is String9uffer obBect. 8a,es in a sing"e &arameter +$ic$ may be o1 t$ese data ty&es' !oolean& char& char *+& dou!le& float& int& long& 8!<ect& String and String9uffer. %ti"" $as anot$er o er"oaded ersion. public char char,t$int inde2% Returns t$e c$aracter "ocated in t$e s&eci1ied index. public #oid get6hars$int srcEegin0 int src<nd0 char ! dst0 int dstEegin% 5ets t$e c$aracters 1rom t$is obBect starting at t$e src9egin inde= u& to t$e srcEnd inde= and co&ies t$ese c$aracters to t$e dst array starting at t$e dst9egin inde=. public StringEuffer delete$int start0 int end% De"etes t$e c$aracters +it$in t$e s&eci1ied range. public StringEuffer insert$int offset0 L% Inserts t$e string re&resentation o1 t$e second argument at t$e s&eci1ied o11set. An o er"oaded met$od. Possib"e data ty&es 1or t$e second argument' !oolean& char& char *+& dou!le& float& int& long& 8!<ect and String. %ti"" $as anot$er o er"oaded ersion. public int length$% Returns t$e number o1 c$aracters in t$is String9uffer obBect. public StringEuffer replace$int start0 int end0 String str% Re&"aces &art o1 t$is obBect3 as s&eci1ied by t$e 1irst t+o arguments3 +it$ t$e s&eci1ied string str. public String substring$int start0 int end% Returns t$e substring o1 t$is string starting at t$e s&eci1ied start inde= u& to t$e end inde=. public String toString$% 4on erts t$is obBect to its string re&resentation.
,a!le I: Some methods of class String9uffer

Introduction to Programming II

Page 6.

J.E.D.I.

8$e &rogram be"o+ demonstrates t$e use o1 t$ese met$ods. class StringEufferDemo { public static #oid main$String args !% { StringEuffer sb = new StringEuffer$=Ronathan=%" S)stem&out&println$=sb = = ( sb%" 9* initial capacit) is 3S *9 S)stem&out&println$=capacit) of sb: = ( sb&capacit)$%%" S)stem&out&println$=append WQ7WQ to sb: = ( sb&append$=7=%%" S)stem&out&println$=sb = = ( sb%" S)stem&out&println$=>rd character of sb: = ( sb&char,t$4%%" char char,rr ! = =Hi VV=&to6har,rra)$%" 9* -eed to add 3 to the endSrc inde2 of get6hars *9 sb&get6hars$'0 40 char,rr0 >%" S)stem&out&print$=get6hars method: =%" S)stem&out&println$char,rr%" S)stem&out&println$=Bnsert WQ8oWQ at the >rd cell: = ( sb&insert$40 =8o=%%" S)stem&out&println$=Delete WQ8oWQ at the >rd cell: = ( sb&delete$40?%%" S)stem&out&println$=length of sb: = ( sb&length$%%" S)stem&out&println$=replace: = ( sb&replace$>0 M0 = 7ng=%%" 9* -eed to add 3 to the endBnde2 parameter of substring*9 S)stem&out&println$=substring $3st two characters%: = ( sb&substring$'0 >%%" S)stem&out&println$=implicit toString$%: = ( sb%" } } )ereHs t$e out&ut o1 t$e gi en &rogram. Again3 1ee" 1ree to e=&eriment +it$ t$e code since t$e best +ay to "earn t$ese synta= is t$roug$ actua" use. sb = Ronathan capacit) of sb: 4? append Q7Q to sb: Ronathan7 sb = Ronathan7 >rd character of sb: n get6hars method: Hi Ro Bnsert Q8oQ at the >rd cell: Ro8onathan7 Delete Q8oQ at the >rd cell: Ronathan7 length of sb: M replace: Ron 7ng substring $3st two characters%: Ron implicit toString$%: Ron 7ng

Introduction to Programming II

Page 60

J.E.D.I.

4.4 1he 4rapper Classes


Ob ious"y3 t$e &rimiti e data ty&es suc$ as int3 char and long are not obBects. 8$us3 ariab"es o1 t$ese data ty&es cannot access met$ods o1 t$e 8!<ect c"ass. On"y actua" obBects3 +$ic$ are dec"ared to be o1 re1erence data ty&e3 can access met$ods o1 t$e 8!<ect c"ass. 8$ere are cases3 $o+e er3 +$en you need an obBect re&resentation 1or t$e &rimiti e ty&e ariab"es in order to use Ja a bui"tCin met$ods. !or e=am&"e3 you may +ant to add &rimiti e ty&e ariab"es to a -ollection obBect. 8$is is +$ere t$e +ra&&er c"asses comes in. 9ra&&er c"asses are sim&"y obBect re&resentations o1 sim&"e nonCobBect ariab"es. )ereHs t$e "ist o1 t$e +ra&&er c"asses. "ri*itive Data 1)pe boo"ean c$ar byte s$ort int "ong 1"oat doub"e Corresponding 4rapper Class #oo"ean 4$aracter #yte %$ort Integer Fong !"oat Doub"e
,a!le 1": 1rimiti#e data types and their corresponding wrapper class

8$e names o1 t$e di11erent +ra&&er c"asses are -uite easy to remember since t$ey are ery simi"ar to t$e &rimiti e data ty&es. A"so3 note t$at t$e +ra&&er c"asses are Bust ca&ita"i*ed and s&e""ed out ersions o1 t$e &rimiti e data ty&es. )ereHs an e=am&"e o1 using t$e +ra&&er c"ass 1or !oolean. class EooleanDrapper { public static #oid main$String args !% { boolean booleanXar = 3>4" Eoolean boolean7b8 = new Eoolean$=.Kue=%" 9* primiti#e to ob8ect" can also use #alue7f method *9 Eoolean boolean7b84 = new Eoolean$booleanXar%" S)stem&out&println$=booleanXar = = ( booleanXar%" S)stem&out&println$=boolean7b8 = = ( boolean7b8%" S)stem&out&println$=boolean7b84 = = ( boolean7b84%" S)stem&out&println$=compare 4 wrapper ob8ects: = ( boolean7b8&eJuals$boolean7b84%%" 9* ob8ect to primiti#e *9 booleanXar = boolean7b8&booleanXalue$%" S)stem&out&println$=booleanXar = = ( booleanXar%" } } 8$e sam&"e code gi es t$e 1o""o+ing out&ut' booleanXar = false boolean7b8 = true boolean7b84 = false compare 4 wrapper ob8ects: false
Introduction to Programming II Page 6(

J.E.D.I.

booleanXar = true

4.5 1he "rocess and the 9unti*e Class


4.5.1 1he "rocess Class
8$e 1rocess c"ass &ro ides met$ods 1or mani&u"ating &rocesses suc$ as ,i""ing t$e &rocess3 running t$e &rocess and c$ec,ing t$e status o1 t$e &rocess. 8$is c"ass re&resents running &rograms. )ere are some met$ods in t$e c"ass. Process Methods public abstract #oid destro)$% @i""s t$e current &rocess. public abstract int waitAor$% throws Bnterrupted<2ception Does not e=it unti" t$is &rocess terminates.
,a!le 11: Some methods of class 1rocess

4.5.2 1he 9unti*e Class


On t$e ot$er $and3 t$e $untime c"ass re&resents t$e runtime en ironment. 8+o im&ortant met$ods in t$e c"ass are t$e get$untime and t$e exec met$od. Runtime Methods public static Kuntime getKuntime$% Returns t$e runtime en ironment associated +it$ t$e current Ja a a&&"ication. public Process e2ec$String command% throws B7<2ception 4auses t$e s&eci1ied command to be e=ecuted. A""o+s you to e=ecute ne+ &rocesses.
,a!le 1;: Some methods of class $un,ime

4.5.3 Opening the 9egistr) %ditor


8$is &rogram o&ens t$e registry editor +it$out e=&"icit"y ty&ing t$e necessary command 1rom t$e command &rom&t. class KuntimeDemo { public static #oid main$String args !% { Kuntime rt = Kuntime&getKuntime$%" Process proc" tr) { proc = rt&e2ec$=regedit=%" proc&waitAor$%" 99tr) remo#ing this line } catch $<2ception e% { S)stem&out&println$=regedit is an un/nown command&=%" } } }

Introduction to Programming II

Page 66

J.E.D.I.

Figure 2.1: ,he opened registry editor

4.

1he -)ste* Class

8$e %ystem c"ass &ro ides many use1u" 1ie"ds and met$ods suc$ as t$e standard in&ut3 t$e standard out&ut and a uti"ity met$od 1or 1ast co&ying o1 a &art o1 an array. )ere are some interesting met$ods 1rom t$e c"ass. 7ote t$at a"" t$e c"assHs met$ods are static. %ystem Methods public static #oid arra)cop)$7b8ect src0 int srcPos0 7b8ect dest0 int destPos0 int length% 4o&ies length items 1rom t$e source array src starting at src1os to dest starting at inde= dest1os. !aster t$an manua""y &rogramming t$e code 1or t$is yourse"1. public static long current.ime1illis$% Returns t$e di11erence bet+een t$e current time and January 13 1?60 284. 8ime returned is measured in mi""iseconds. public static #oid e2it$int status% @i""s t$e Ja a Virtua" Mac$ine ;JVM> running current"y. A nonC*ero con ention indicates an abnorma" e=it. public static #oid gc$% Runs t$e garbage co""ector3 +$ic$ rec"aims unused memory s&ace 1or recyc"ing. public static #oid setBn$BnputStream in% 4$anges t$e stream associated +it$ System.in3 +$ic$ by de1au"t re1ers to t$e ,eyboard. public static #oid set7ut$PrintStream out% 4$anges t$e stream associated +it$ System.out3 +$ic$ by de1au"t re1ers to t$e conso"e.
,a!le 1A: Some methods of class System

a"ue 1or status by

Introduction to Programming II

Page 66

J.E.D.I.

)ereHs a demo on some o1 t$ese met$ods. import 8a#a&io&*" class S)stemDemo { public static #oid main$String args !% throws B7<2ception { int arr3 ! = new int C''''''!" int arr4 ! = new int C''''''!" long start.ime0 end.ime" 9* initiali:e arr3 *9 for $int i = '" i < arr3&length" i((% { arr3 i! = i ( 3" } 9* cop)ing manuall) *9 start.ime = S)stem&current.ime1illis$%" for $int i = '" i < arr3&length" i((% { arr4 i! = arr3 i!" } end.ime = S)stem&current.ime1illis$%" S)stem&out&println$=.ime for manual cop): = ( $end.imeLstart.ime% ( = ms&=%" 9* using the cop) utilit) pro#ided b) 8a#a N the arra)cop) method *9 start.ime = S)stem&current.ime1illis$%" S)stem&arra)cop)$arr30 '0 arr40 '0 arr3&length%" end.ime = S)stem&current.ime1illis$%" S)stem&out&println$=.ime w9the use of arra)cop): = ( $end.imeLstart.ime% ( = ms&=%" S)stem&gc$%" 99force garbage collector to wor/ S)stem&setBn$new AileBnputStream$=temp&t2t=%%" 9* in -etEeans0 temp&t2t should be located in the pro8ect folder *9 S)stem&e2it$'%" } } 8$e &rogram gi es arying out&ut. It may generate t$e 1o""o+ing sam&"e out&ut' .ime for manual cop): >4 ms& .ime w9the use of arra)cop): >3 ms&

Introduction to Programming II

Page 6/

J.E.D.I.

1 Text62ased A""&ications
5.1 Objectives
In t$is "esson3 a re ie+ on using commandC"ine arguments is 1ound in t$is section. Moreo er3 you +i"" "earn more about using streams to get in&ut 1rom t$e user during runtime and to mani&u"ate 1i"es. A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. 5et in&ut 1rom t$e commandC"ine 2. E=&"ain $o+ to mani&u"ate system &ro&erties 2. Read 1rom t$e standard in&ut 0. Read and +rite to 1i"es

5.2 Co**and-?ine Argu*ents and -)ste* "roperties


As you $a e seen be1ore in your &re ious &rogramming course3 Ba a a""o+s user to in&ut data 1rom t$e command "ine. !or instance3 to &ass t$e arguments 1 and ; to t$e Ba a &rogram named -alculate3 you can ty&e t$e 1o""o+ing "ine on t$e command &rom&t' 8a#a 6alculate 3 4 In t$is e=am&"e3 t$e data 1 is stored in t$e ariab"e args*"+ +$ereas t$e data ; is stored in args*1+. 9it$ t$is3 t$e &ur&ose o1 dec"aring String args*+ as a &arameter in t$e main met$od becomes c"ear. I1 youHre using 7et#eans3 $ere are t$e ste&s 1or &assing commandC"ine arguments. 1. Foo, 1or t$e &roBect name in t$e 1ro<ects &ane" on t$e "e1t. Rig$t c"ic, on t$e &roBect name or icon. 2. %e"ect 1roperties. 8$is is t$e "ast o&tion o1 t$e dro&Cdo+n menu. .. 4"ic, on $un 1rom t$e 4ategories &ane" on t$e "e1t. 0. Enter t$e arguments se&arated by s&ace 1or /rguments te=t 1ie"d. (. 4"ic, on 8? button. 6. 4om&i"e and run t$e &rogram as usua". 8o understand t$ese ste&s more easi"y3 t$e 1o""o+ing screen s$ots are &ro ided'

Introduction to Programming II

Page 6?

J.E.D.I.

Figure D.1: 1assing -ommand%line /rguments with 3et9eans = Steps 1 @ ;

Introduction to Programming II

Page 60

J.E.D.I.

Figure D.;: 1assing -ommand%line /rguments with 3et9eans = Step A

Introduction to Programming II

Page 61

J.E.D.I.

Figure D.A: 1assing -ommand%line /rguments with 3et9eans = Step 2

Introduction to Programming II

Page 62

J.E.D.I.

#esides &assing arguments to t$e main met$od3 you can a"so mani&u"ate system &ro&erties 1rom t$e command "ine. %ystem &ro&erties are -uite simi"ar to en ironment ariab"es but t$e 1ormer not being &"at1ormCde&endent. A &ro&erty is sim&"y a ma&&ing bet+een t$e &ro&erty name to its corres&onding a"ue. 8$is is re&resented in Ja a +it$ t$e 1roperties c"ass. 8$e System c"ass &ro ides a met$ods 1or determining t$e current system &ro&erties3 t$e get1roperties met$od t$at returns a 1roperties obBect. 8$e same c"ass a"so &ro ides 1or t$e get1roperty met$od t$at $as t+o 1orms. public static String getPropert)$String /e)% 8$is ersion returns string a"ue o1 t$e system &ro&erty indicated by t$e s&eci1ied 'ey. It returns nu"" i1 t$ere is no &ro&erty +it$ t$e s&eci1ied 'ey. public static String getPropert)$String /e)0 String def% 8$is ersion a"so returns string a"ue o1 t$e system &ro&erty indicated by t$e s&eci1ied 'ey. It returns def3 a de1au"t a"ue3 i1 t$ere is no &ro&erty +it$ t$e s&eci1ied 'ey.
,a!le 12: get1roperty() methods of class System

9e +i"" no "onger d+e"" on t$e detai"s o1 system &ro&erties but go straig$t to mani&u"ating system &ro&erties a&&"ied. I1 you are interested in "earning more about system &ro&erties3 you can re1er to t$e API documentation. Jou can use t$e CD o&tion +it$ t$e Ba a command 1rom t$e commandC"ine to inc"ude a ne+ &ro&erty. 8a#a LD<name>=#alue !or e=am&"e3 to set t$e system &ro&erty user.home to $a e a t$e 1o""o+ing command' 8a#a LDuser&home=philippines 8o dis&"ay t$e "ist o1 system &ro&erties a ai"ab"e in your system and t$eir corres&onding a"ues3 you can use t$e get1roperties met$od as 1o""o+s' S)stem&getProperties$%&list$S)stem&out%" )ere is a sam&"e "ist o1 system &ro&erties' LL listing properties LL 8a#a&runtime&name=Ra#a$.1% 4 Kuntime <n#ironment0 Stand&&& sun&boot&librar)&path=6:WProgram AilesWRa#aW8d/3&C&'*'SW8re&&& 8a#a&#m&#ersion=3&C&'*'SLb'C 8a#a&#m&#endor=Sun 1icros)stems Bnc& 8a#a&#endor&url=http:998a#a&sun&com9 path&separator=" 8a#a&#m&name=Ra#a HotSpot$.1% 6lient X1 file&encoding&p/g=sun&io user&countr)=@S sun&os&patch&le#el=Ser#ice Pac/ 4 8a#a&#m&specification&name=Ra#a Xirtual 1achine Specification user&dir=6:WDocuments and SettingsWbeccaW-este&&& 8a#a&runtime&#ersion=3&C&'*'SLb'C
Introduction to Programming II Page 6.

a"ue o1 philippines3 use

J.E.D.I.

8a#a&awt&graphicsen#=sun&awt&Din>4Yraphics<n#ironment 8a#a&endorsed&dirs=6:WProgram AilesWRa#aW8d/3&C&'*'SW8re&&& os&arch=2OS 8a#a&io&tmpdir=6:WD76@1<Z3WbeccaW;76,;SZ3W.empW line&separator= 8a#a&#m&specification&#endor=Sun 1icros)stems Bnc& user&#ariant= os&name=Dindows VP sun&8nu&encoding=6p34C4 8a#a&librar)&path=6:WProgram AilesWRa#aW8d/3&C&'*'SW8re&&& 8a#a&specification&name=Ra#a Platform ,PB Specification 8a#a&class&#ersion=?M&' sun&management&compiler=HotSpot 6lient 6ompiler os&#ersion=C&3 user&home=6:WDocuments and SettingsWbecca user&time:one= 8a#a&awt&printer8ob=sun&awt&windows&DPrinterRob file&encoding=6p34C4 8a#a&specification&#ersion=3&C user&name=becca 8a#a&class&path=6:WDocuments and SettingsWbeccaW-este&&& 8a#a&#m&specification&#ersion=3&' sun&arch&data&model=>4 8a#a&home=6:WProgram AilesWRa#aW8d/3&C&'*'SW8re 8a#a&specification&#endor=Sun 1icros)stems Bnc& user&language=en awt&tool/it=sun&awt&windows&D.ool/it 8a#a&#m&info=mi2ed mode0 sharing 8a#a&#ersion=3&C&'*'S 8a#a&e2t&dirs=6:WProgram AilesWRa#aW8d/3&C&'*'SW8re&&& sun&boot&class&path=6:WProgram AilesWRa#aW8d/3&C&'*'SW8re&&& 8a#a&#endor=Sun 1icros)stems Bnc& file&separator=W 8a#a&#endor&url&bug=http:998a#a&sun&com9cgiLbin9bugreport&&& sun&cpu&endian=little sun&io&unicode&encoding=@nicode;ittle sun&des/top=windows sun&cpu&isalist=

5.3 9eading +ro* -tandard (nput


Instead o1 getting user in&ut 1rom t$e commandC"ine3 most users &re1er in&utting data +$en &rom&ted by t$e &rogram +$i"e it is a"ready in e=ecution. One +ay o1 doing t$is is +it$ t$e use o1 streams. A stream is an abstraction o1 a 1i"e or a de ice t$at a""o+s a series o1 items to be read or +ritten. %treams are connected to &$ysica" de ices suc$ as ,eyboards3 conso"es and 1i"es. 8$ere are t+o genera" ,inds o1 streams3 byte streams and c$aracter streams. #yte streams are 1or binary data +$i"e c$aracter streams are 1or 2nicode c$aracters. System.in and System.out are t+o e=am&"es o1 &rede1ined byte streams in Ba a. 8$e 1irst one by de1au"t re1ers to t$e ,eyboard and t$e "atter re1ers to t$e conso"e. 8o read c$aracters 1rom t$e ,eyboard3 you can use t$e System.in byte stream +ar&ed in a #u11eredReader obBect. 8$e 1o""o+ing "ine s$o+s $o+ to do t$is' EufferedKeader br = new EufferedKeader$new BnputStreamKeader$S)stem&in%%"

Introduction to Programming II

Page 60

J.E.D.I.

8$e read met$od o1 t$e #u11eredReader obBect is t$en used to read 1rom t$e in&ut de ice. ch = $int% br&read$%" 8ry out t$is sam&"e code. import 8a#a&io&*" class Aa#orite6haracter { public static #oid main$String args !% throws B7<2ception { S)stem&out&println$=Hi0 whatQs )our fa#orite character5=%" char fa#6har" EufferedKeader br = new EufferedKeader$new BnputStreamKeader$S)stem&in%%" fa#6har = $char% br&read$%" S)stem&out&println$fa#6har ( = is a good choiceI=%" } } Running t$is code +it$ t$e c$aracter a as in&ut generates t$e 1o""o+ing out&ut' Hi0 whatQs )our fa#orite character5 a a is a good choiceI I1 you &re1er reading an entire "ine instead o1 reading one c$aracter at a time3 you can use t$e readFine met$od. str = br&read;ine$%" )ere is a &rogram a"most simi"ar to t$e &receding e=am&"e but reads an entire string instead o1 Bust one c$aracter. import 8a#a&io&*" class Yreet@ser { public static #oid main$String args !% throws B7<2ception { S)stem&out&println$=Hi0 whatQs )our name5=%" String name" EufferedKeader br = new EufferedKeader$new BnputStreamKeader$S)stem&in%%" name = br&read;ine$%" S)stem&out&println$=-ice to meet )ou0 = ( name ( =I :%=%" } } )ere is t$e e=&ected out&ut o1 JreetUser +$en t$e user in&uts re!ecca' Hi0 whatQs )our name5 rebecca -ice to meet )ou0 rebeccaI :% 9$en using streams3 donHt 1orget to im&ort t$e <a#a.io &ac,age as s$o+n be"o+' import 8a#a&io&*" One more reminder3 reading 1rom streams may cause c$ec,ed e=ce&tions to occur. DonHt 1orget to $and"e t$ese e=ce&tions using tryCcatc$ statements or by indicating t$e
Introduction to Programming II Page 6(

99read method returns an integer

J.E.D.I.

e=ce&tion in t$e t$ro+s c"ause o1 t$e met$od.

5.4 ;ile 7andling


In some cases3 data in&uts are stored in 1i"es. Moreo er3 t$ere are a"so instances +$en +e +ant to store t$e out&ut o1 a certain &rogram to a 1i"e. In a com&uteri*ed enro""ment system3 t$e student data t$at may be used as an in&ut to t$e system is most &robab"y stored in a &articu"ar 1i"e. 8$en3 one &ossib"e out&ut o1 t$e system is t$e in1ormation about t$e subBects enro""ed in by t$e students. Again3 t$e out&ut in t$is case may &re1erab"y be stored in a 1i"e. As seen in t$is a&&"ication3 t$ere is a need 1or reading 1rom a 1i"e and +riting to a 1i"e. Jou +i"" "earn about 1i"e in&ut and out&ut in t$is section.

5.4.1 9eading +ro* a ;ile


8o read 1rom a 1i"e3 you can use t$e FileInputStream c"ass. )ere is one o1 t$e constructors o1 t$is c"ass. AileBnputStream$String filename% 8$e constructor creates a connection to an actua" 1i"e +$ose 1i"ename is s&eci1ied as an argument. A File3otFoundException is t$ro+n +$en t$e 1i"e does not e=ist or it cannot be o&ened 1or reading. A1ter creating an in&ut stream3 you can no+ use t$e stream to read 1rom t$e associated 1i"e using t$e read met$od. 8$e read met$od returns an integer and it returns C1 +$en t$e end o1 t$e 1i"e is reac$ed. )ere is an e=am&"e. import 8a#a&io&*" class KeadAile { public static #oid main$String args !% throws B7<2ception { S)stem&out&println$=Dhat is the name of the file to read from5=%" String filename" EufferedKeader br = new EufferedKeader$new BnputStreamKeader$S)stem&in%%" filename = br&read;ine$%" S)stem&out&println$=-ow reading from = ( filename ( =&&&=%" AileBnputStream fis = null" tr) { fis = new AileBnputStream$filename%" } catch $Aile-otAound<2ception e2% { S)stem&out&println$=Aile not found&=%" } tr) { char data" int temp" do { temp = fis&read$%" data = $char% temp" if $temp I= L3% {
Introduction to Programming II Page 66

J.E.D.I.

S)stem&out&print$data%" } } while $temp I= L3%" } catch $B7<2ception e2% { S)stem&out&println$=Problem in reading from the file&=%" }

Assuming temp.txt e=ists and it contains t$e te=t temporary file3 $ere is a sam&"e out&ut o1 t$is &rogram' Dhat is the name of the file to read from5 temp&t2t -ow reading from temp&t2t&&& temporar) file

5.4.2 4riting to a ;ile


!or +riting to a 1i"e3 you can use t$e File8utputStream c"ass. )ere is one o1 t$e constructors you can use. Aile7utputStream$String filename% 8$e constructor "in,s an out&ut stream to an actua" 1i"e to +rite File3otFoundException is t$ro+n +$en t$e 1i"e cannot be o&ened 1or +riting. to. A

Once t$e out&ut stream is created3 you can no+ use t$e stream to +rite to t$e "in,ed 1i"e using t$e write met$od. 8$e met$od $as t$e 1o""o+ing signature' #oid write$int b% 8$e &arameter ! re1ers to t$e data to be +ritten to t$e actua" 1i"e associated to t$e out&ut stream. 8$e 1o""o+ing &rogram demonstrates +riting to a 1i"e. import 8a#a&io&*" class DriteAile { public static #oid main$String args !% throws B7<2ception { S)stem&out&println$=Dhat is the name of the file to be written to5=%" String filename" EufferedKeader br = new EufferedKeader$new BnputStreamKeader$S)stem&in%%" filename = br&read;ine$%" S)stem&out&println$=<nter data to write to = ( filename ( =&&&=%" S)stem&out&println$=.)pe J[ to end&=%" Aile7utputStream fos = null" tr) { fos = new Aile7utputStream$filename%" } catch $Aile-otAound<2ception e2% { S)stem&out&println$=Aile cannot be opened for writing&=%" }
Introduction to Programming II Page 66

J.E.D.I.

tr) { boolean done = false" int data" do { data = br&read$%" if $$char%data == QJQ% { data = br&read$%" if $$char%data == Q[Q% { done = true" } else { fos&write$QJQ%" fos&write$data%" } } else { fos&write$data%" } } while $Idone%" } catch $B7<2ception e2% { S)stem&out&println$=Problem in reading from the file&=%" }

)ere is a sam&"e run o1 KriteFile' Dhat is the name of the file to be written to5 temp&t2t <nter data to write to temp&t2t&&& .)pe J[ to end& what a wonderful world 30 40 step J[ 9$en you o&en temp.txt3 it s$ou"d contain t$e 1o""o+ing' what a wonderful world 30 40 step

Introduction to Programming II

Page 6/

J.E.D.I.

5.5 %5ercises
5.5.1 -paces to 8nderscore
4reate a &rogram t$at ta,es in t+o strings as arguments R t$e source and destination 1i"enames3 res&ecti e"y. 8$en3 read 1rom t$e source 1i"e and +rite its content to t$e destination 1i"e +it$ a"" occurrences o1 s&aces ;H H> con erted to underscores ;HTH>.

5.5.2 Dra3 1riangle


4reate a &rogram t$at ta,es in t+o arguments R an integer and a 1i"ename3 res&ecti e"y. Dra+ a triang"e based on t$e in&ut integer and out&ut it to t$e in&ut 1i"e. %am&"e Run' AO &assed arguments' 0 tri.t=t OA * * * * * * * * * *

Introduction to Programming II

Page 6?

J.E.D.I.

, %orting A&gorithms
.1 Objectives
%orting is t$e tas, o1 arranging e"ements in a &articu"ar order and it is im&"emented in a ariety o1 a&&"ications. 4onsider a ban,ing a&&"ication3 +$ic$ dis&"ays t$e "ist o1 acti e c"ient accounts3 1or instance. 2sers o1 t$is system most &robab"y &re1er $a ing t$e "ist in an ascending order 1or con enience. %e era" sorting a"gorit$ms $a e been in ented because t$e tas, is so 1undamenta" and a"so 1re-uent"y used. !or t$ese reasons3 e=amining e=isting a"gorit$ms +ou"d be ery bene1icia". A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. E=&"ain t$e a"gorit$ms used in insertion sort3 se"ection sort3 merge sort and -uic,sort 2. 5i e your o+n im&"ementation o1 t$ese a"gorit$ms

.2 (nsertion -ort
One o1 t$e sim&"est a"gorit$ms de e"o&ed is t$e insertion sort. 8$e idea 1or t$e a"gorit$m is -uite intuiti e and is ana"agous to a +ay o1 arranging a co""ection o1 cards. 8$e 1o""o+ing scenario describes $o+ insertion sort +or,s 1or arranging a set o1 cards. %ay you +ant to arrange a standard dec, o1 cards 1rom "o+est to $ig$est ran,. A"" cards are initia""y "aid on a tab"e3 ca"" t$is 1st tab"e3 1ace u& in an order"y 1as$ion 1rom "e1t to rig$t3 to& to bottom. 9e $a e anot$er tab"e3 ca"" t$is 2 nd tab"e3 +$ere t$e arranged cards +ou"d be &ositioned. Pic, t$e 1irst a ai"ab"e card 1rom u&&er "e1t corner o1 t$e 1st tab"e and &"ace t$is card in its &ro&er ;i.e.3 sorted> &osition on t$e 2nd tab"e. Pic, t$e ne=t a ai"ab"e card 1rom t$e 1st tab"e and com&ared t$is +it$ t$e cards on t$e 2nd tab"e and &"ace it in its &ro&er &osition. 8$e &rocess continues unti" a"" cards are &"aced on t$e 2nd tab"e. 8$e insertion sort a"gorit$m basica""y di ides t$e data e"ements to be sorted into t+o grou&s3 t$e unsorted ;ana"ogous to t$e 1st tab"e> and t$e sorted ;ana"ogous to t$e 2nd tab"e> sections. 8$e 1irst a ai"ab"e e"ement is se"ected 1rom t$e unsorted section o1 t$e array and it is &ro&er"y &ositioned in t$e sorted section o1 t$e array. 8$is ste& is re&eated unti" t$ere are no more e"ements "e1t in t$e unsorted &art o1 t$e array.

.2.1 1he Algorith*


#oid insertionSort$7b8ect arra) !0 int startBd20 int endBd2% { for $int i = startBd2" i < endBd2" i((% { int / = i" for $int 8 = i ( 3" 8 < endBd2" 8((% { if $$$6omparable% arra) /!%&compare.o$arra) 8!%>'% { / = 8" } } swap$arra) i!0 arra) /!%" } }

Introduction to Programming II

Page /0

J.E.D.I.

.2.2 An %5a*ple
.iven Mango A&&"e Peac$ Orange #anana 1st "ass Mango A&&"e Peac$ Orange #anana 2nd "ass A&&"e Mango Peac$ Orange #anana 3rd "ass A&&"e Mango Orange Peac$ #anana 4th "ass A&&"e #anana Mango Orange Peac$

Figure E.1: Insertion sort example

At t$e end o1 t$is modu"e3 you +i"" be as,ed to gi e your o+n Ja a im&"ementation o1 t$e di11erent sorting a"gorit$ms discussed in t$is section.

.3 -election -ort
I1 you +ere assigned to in ent your o+n sorting a"gorit$m3 you +ou"d &robab"y come u& +it$ an a"gorit$m simi"ar to t$e se"ection sort a"gorit$m. Fi,e t$e insertion sort a"gorit$m3 t$is a"gorit$m is ery intuiti e and easy to im&"ement. Again3 "et us obser e $o+ t$is a"gorit$m +ou"d +or, on a standard dec, o1 cards. Assume t$at t$e cards are to be arranged in ascending order. Initia""y3 t$e set o1 cards are arranged "inear"y on t$e tab"e 1rom "e1t to rig$t and to& to bottom. 4$ec, t$e ran, o1 eac$ card and se"ect t$e card +it$ t$e "o+est ran,. E=c$ange t$e &osition o1 t$is card +it$ t$e &osition o1 t$e 1irst card on t$e u&&er "e1t corner. 7e=t3 1ind t$e card +it$ t$e "o+est ran, among t$e remaining cards e=c"uding t$e 1irst c$osen card. %+a& t$e ne+"y se"ected card +it$ t$e card in t$e second &osition. Re&eat t$e same ste& unti" t$e second to t$e "ast &osition on t$e tab"e is c$a""enged and may be s+a&&ed by a card +it$ a "o+er a"ue. 8$e main idea be$ind t$e se"ection sort a"gorit$m is to se"ect t$e e"ement +it$ t$e "o+est a"ue and t$en s+a& t$e c$osen e"ement +it$ t$e e"ement in t$e it$ &osition. 8$e a"ue o1 i starts 1rom 1 to n3 +$ere n is t$e tota" number o1 e"ements minus 1.

.3.1 1he Algorith*


#oid selectionSort$7b8ect arra) !0 int startBd20 int endBd2% { int min" for $int i = startBd2" i < endBd2" i((% { min = i" for $int 8 = i ( 3" 8 < endBd2" 8((% { if $$$6omparable% arra) min!%&compare.o$arra) 8!%>'% { min = 8" } } swap$arra) min!0 arra) i!%" } }

Introduction to Programming II

Page /1

J.E.D.I.

.3.2 An %5a*ple
.iven 0aricar Vanessa Margau= Hannah Ro+ena 1st "ass )anna$ >anessa 0argaux Maricar Ro+ena 2nd "ass )anna$ Margau= >anessa 0aricar Ro+ena 3rd "ass )anna$ Margau= Maricar >anessa $owena 4th "ass )anna$ Margau= Maricar Ro+ena Vanessa

Figure E.;: Selection sort example

.4 Merge -ort
#e1ore e=amining t$e Merge sort a"gorit$m3 "et us 1irst $a e a -uic, "oo, at t$e di ideC andCcon-uer &aradigm since Merge sort c"ose"y 1o""o+s t$is a&&roac$.

.4.1 Divide-and-Con>uer "aradig*


%e era" a"gorit$ms use recursion to so" e a gi en &rob"em. 8$e origina" &rob"em is s&"it into sub&rob"ems3 t$en t$e so"utions to t$e sub&rob"ems "ead to t$e so"ution o1 t$e main &rob"em. 8$is ty&e o1 a"gorit$ms ty&ica""y 1o""o+s t$e di ideCandCcon-uer &aradigm. At eac$ "e e" o1 recursion3 t$e &aradigm consists o1 t$ree ste&s. 1. Di ide Di ide t$e main &rob"em into sub&rob"ems. 2. 4on-uer 4on-uer t$e sub&rob"ems by recursi e"y so" ing t$em. In t$e case t$at t$e su&rob"ems are sim&"e and sma"" enoug$3 a straig$t1or+ard manner o1 so" ing t$em +ou"d be better. .. 4ombine 4ombine t$e so"utions to t$e su&rob"ems3 +$ic$ +ou"d "ead to t$e so"ution o1 t$e main &rob"em.

.4.2 8nderstanding Merge -ort


As &re ious"y mentioned3 Merge sort uses t$e di ideCandCcon-uer tec$ni-ue. 8$us3 t$e descri&tion o1 its a"gorit$m is &atterned a1ter t$e t$ree ste&s in t$e di ideCandCcon-uer &aradigm. )ere is $o+ Merge sort +or,s. 1. Di ide Di ide t$e se-uence o1 data e"ements into t+o $a" es. 2. 4on-uer 4on-uer eac$ $a"1 by recursi e"y ca""ing t$e Merge sort &rocedure. .. 4ombine 4ombine or merge t$e t+o $a" es recursi e"y to come u& +it$ t$e sorted se-uence. Recursion sto&s +$en t$e base case is reac$ed. 8$is is t$e case +$erein t$e $a"1 to be
Introduction to Programming II Page /2

J.E.D.I.

sorted $as e=act"y one e"ement. %ince on"y one e"ement is "e1t to be sorted3 t$is $a"1 is a"ready arranged in its &ro&er se-uence.

.4.3 1he Algorith*


#oid mergeSort$7b8ect arra) !0 int startBd20 int endBd2% { if $arra)&length I= 3% { Di#ide the arra) into two hal#es0 left,rr and right,rr mergeSort$left,rr0 startBd20 midBd2%" mergeSort$right,rr0 midBd2(30 endBd2%" combine$left,rr0 right,rr%" } }

.4.4 An %5a*ple
5i en'

6 2 ( 6
Di ide gi en array into t+o' 6eft/rr $ight/rr

7 2

5 6

Introduction to Programming II

Page /.

J.E.D.I.

Di ide 6eft/rr o1 gi en into t+o' 6eft/rr $ight/rr

Introduction to Programming II

Page /0

J.E.D.I.

4ombine

2 6
Di ide $ight/rr o1 gi en into t+o' 6eft/rr $ight/rr

Introduction to Programming II

Page /(

J.E.D.I.

4ombine

( 6
4ombine 6eft/rr and $ight/rr o1 t$e gi en.

2 ( 6 6
Figure E.A: 0erge sort example

.5 =uic#sort
Euic,sort +as in ented by 4.A.R. )oare. Fi,e merge sort3 t$is a"gorit$m is a"so based on t$e di ideCandCcon-uer &aradigm. #ut instead o1 $a ing t$ree &$ases3 it in o" es t$e 1o""o+ing &$ases on"y' 1. Di ide Partition t$e array into t+o subarrays AU&...-C1V and AU-S1...rV suc$ t$at eac$ e"ement in AU&...-C1V is "ess t$an or e-ua" to AU-V and eac$ e"ement in AU-S1...rV is greater t$an or e-ua" to AU-V. AU-V is ca""ed t$e &i ot. 4om&utation o1 - is &art o1 t$e &artitioning &rocedure. 2. 4on-uer %ort t$e subarrays by recursi e"y ca""ing t$e Cuic'Sort met$od. 8$ere is no "onger any I4ombineI &$ase since t$e subarrays are sorted in &"ace.

.5.1 1he Algorith*


#oid Juic/Sort$7b8ect arra) !0 int leftBd20 int rightBd2% { int pi#otBd2" 9* .ermination conditionI *9 if $rightBd2 > leftBd2% { pi#otBd2 = partition$arra)0 leftBd20 rightBd2%" Juic/Sort$arra)0 leftBd20 pi#otBd2L3%" Juic/Sort$arra)0 pi#otBd2(30 rightBd2%" } }

.5.2 An %5a*ple
5i en array'

Introduction to Programming II

Page /6

J.E.D.I.

4$oose t$e 1irst e"ement to be t$e &i ot P .. 4 1 0 1 ( ?

Initia"i*e "e1t to &oint to t$e second e"ement and rig$t to &oint to t$e "ast e"ement. "e1t rig$t 4 1 0 1 ( ? 2 6 ( . ( /

Mo e t$e "e1t &ointer to t$e rig$t direction unti" +e 1ind a a"ue "arger t$an t$e &i ot. Mo e t$e rig$t &ointer to t$e "e1t direction unti" +e 1ina a"ue not "arger t$an t$e &i ot. "e1t rig$t 4 1 0 1 ( ? 2 6 ( . ( /

%+a& e"ements re1erred to by t$e "e1t and rig$t &ointers. "e1t 4 1 . 1 ( ? 2 6 (

rig$t 0 ( /

Mo e t$e "e1t and rig$t &ointers again. "e1t 4 1 . 1 ( ?

rig$t 2 6 ( 0 ( /

%+a& e"ements. "e1t 4 1 . 1 2 ? rig$t ( 6 ( 0 ( /

Mo e t$e "e1t and rig$t &ointers again. rig$t "e1t 4 1 . 1 2 ? ( 6 ( 0 ( /

Obser e t$at t$e "e1t and rig$t &ointers $a e crossed suc$ t$at rig$t W "e1t. In t$is case3 s+a& &i ot +it$ rig$t. &i ot 0 1 . 1 4 ? ( 6 ( 0 ( /

Figure E.2: Buic'sort example

Pi oting is no+ com&"ete. Recursi e"y sort subarrays on eac$ side o1 t$e &i ot.

Introduction to Programming II

Page /6

J.E.D.I.

7 Abstract !indowing Too&$it and %wing


!.1 Objectives
9it$out "earning about gra&$ica" user inter1ace ;52I> APIs3 you +ou"d sti"" be ab"e to create -uite a descent range o1 di11erent &rograms. )o+e er3 your a&&"ications are ery "i,e"y to be b"and and una&&ea"ing to t$e users. )a ing a good 52I a11ects t$e usage o1 your a&&"ication. 8$is resu"ts in ease o1 use and enBoyment o1 use 1or t$e users o1 your &rogram. Ja a &ro ides too"s "i,e Abstract 9indo+ing 8oo",it ;A98> and %+ing to de e"o& interacti e 52I a&&"ications. A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. E=&"ain simi"arities and di11erences bet+een A98 and %+ing 2. Di11erentiate bet+een com&onents and containers .. Design 52I a&&"ications using A98 0. Design 52I a&&"ications using %+ing (. Describe $o+ 1"o+ "ayout3 border "ayout and grid "ayout &osition 52I com&onents 6. 4reate com&"e= "ayouts in designing 52I a&&""ications

!.2 Abstract 4indo3ing 1ool#it @A41A vs. -3ing


8$e Ja a !oundation 4"asses ;J!4s>3 +$ic$ is an im&ortant &art o1 t$e Ja a %D@3 re1ers to a co""ection o1 APIs t$at sim&"i1ies t$e de e"o&ment Ja a 52I a&&"ications. It &rimari"y consists o1 1i e APIs inc"uding A98 and %+ing. 8$e t$ree ot$er APIs are Ja a2D3 Accessibi"ity3 and Drag and Dro&. A"" t$ese APIs assist de e"o&ers in designing and im&"ementing isua""yCen$anced a&&"ications. #ot$ A98 and %+ing &ro ides 52I com&onents t$at can be used in creating Ja a a&&"ications and a&&"ets. Jou +i"" "earn about a&&"ets in a "atter section. 2n"i,e some A98 com&onents t$at use nati e code3 %+ing is +ritten entire"y using t$e Ja a &rogramming "anguage. As a resu"t3 %+ing &ro ides a &"at1ormCinde&endent im&"ementation ensuring t$at a&&"ications de&"oyed across di11erent &"at1orms $a e t$e same a&&earance. A983 $o+e er3 does ensure t$at t$e "oo, and 1ee" o1 an a&&"ication run on t+o di11erent mac$ines be com&arab"e. 8$e %+ing API is bui"t around a number o1 APIs t$at im&"ement arious &arts o1 t$e A98. As a resu"t3 A98 com&onents can sti"" be used +it$ %+ing com&onents.

!.3 A41 .8( Co*ponents


!.3.1 ;unda*ental 4indo3 Classes
In de e"o&ing 52I a&&"ications3 t$e 52I com&onents suc$ as buttons or te=t 1ie"ds are &"aced in containers. 8$ese are t$e "ist o1 im&ortant container c"asses &ro ided in t$e A98.

Introduction to Programming II

Page //

J.E.D.I.

A41 Class 4om&onent 4ontainer Pane" 9indo+ !rame

Description An abstract c"ass 1or obBects t$at can be dis&"ayed on t$e conso"e and interact +it$ t$e user. 8$e root o1 a"" ot$er A98 c"asses. An abstract subc"ass o1 t$e -omponent c"ass. A com&onent t$at can contain ot$er com&onents. E=tends t$e -ontainer c"ass. A 1rame or +indo+ +it$out t$e tit"ebar3 t$e menubar nor t$e border. %u&erc"ass o1 t$e /pplet c"ass. A"so e=tends -ontainer c"ass. A to&C"e e" +indo+3 +$ic$ means t$at it cannot be contained in any ot$er obBect. )as no borders and no menubar. E=tends t$e Kindow c"ass. A +indo+ +it$ a tit"e3 menubar3 border3 and resi*ing corners. )as 1our constructors3 t+o o1 +$ic$ $a e t$e 1o""o+ing signatures' Arame$% Arame$String title%
,a!le 1D: /K, -ontainer classes

8o set t$e si*e o1 t$e +indo+3 t$e o er"oaded set%i*e met$od is used. #oid setSi:e$int width0 int height% Resi*es t$is com&onent to t$e width and height &ro ided as &arameters. #oid setSi:e$Dimension d% Resi*es t$is com&onent to d.width and d.height based on t$e :imension d s&eci1ied. A +indo+ by de1au"t is not isib"e un"ess you set its 1or t$e set>isi!le met$od. #oid setXisible$boolean b% isibi"ity to true. )ere is t$e synta=

In designing 52I a&&"ications3 Frame obBects are usua""y used. )ereHs an e=am&"e o1 $o+ to create suc$ an a&&"ication. import 8a#a&awt&*" public class SampleArame e2tends Arame { public static #oid main$String args !% { SampleArame sf = new SampleArame$%" sf&setSi:e$3''0 3''%" 99.r) remo#ing this line sf&setXisible$true%" 99.r) remo#ing this line } } )ere is t$e e=&ected out&ut 1or running SampleFrame'

Figure F.1: $unning SampleFrame

7ote t$at t$e c"ose button o1 t$e 1rame doesnHt +or, yet because no e ent $and"ing
Introduction to Programming II Page /?

J.E.D.I.

mec$anism $as been added to t$e &rogram yet. JouH"" "earn about e ent $and"ing in t$e ne=t modu"e.

!.3.2 .raphics
%e era" gra&$ics met$od are 1ound in t$e Jraphics c"ass. )ere is t$e "ist o1 some o1 t$ese met$ods. dra+Fine;> 1i""Rect;> dra+Rect;> c"earRect;> dra+Po"y"ine;> dra+Po"ygon;> 1i""Po"ygon;> get4o"or;> set4o"or;> get!ont;> set!ont;> dra+%tring;>

,a!le 1E: Some methods of class Jraphics

Re"ated to t$is c"ass is t$e -olor c"ass3 +$ic$ $as t$ree constructors. Constructor ;or*at 4o"or;int r3 int g3 int b> 4o"or;int rgbVa"ue> Description Integer a"ue is 1rom 0 to 2((. Va"ue range 1rom 0 to 220C1 ;b"ac, to +$ite>. Red' bits 16C2. 5reen' bits /C1( #"ue' bits 0C6
,a!le 1F: -olor constructors

4o"or;1"oat r3 1"oat g3 1"oat b> !"oat a"ue is 1rom 0.0 to 1.0.

)ere is a sam&"e &rogram t$at uses some o1 t$e met$ods in t$e Jraphics c"ass. import 8a#a&awt&*" public class YraphicsPanel e2tends Panel { YraphicsPanel$% { setEac/ground$6olor&blac/%" 99constant in 6olor class } public #oid paint$Yraphics g% { g&set6olor$new 6olor$'04CC0'%%" 99green g&setAont$new Aont$=Hel#etica=0Aont&P;,B-03S%%" g&drawString$=Hello Y@B DorldI=0 >'0 3''%" g&set6olor$new 6olor$3&'f0'0'%%" 99red g&fillKect$>'0 3''0 3C'0 3'%" } public static #oid main$String args !% { Arame f = new Arame$=.esting Yraphics Panel=%" YraphicsPanel gp = new YraphicsPanel$%" f&add$gp%" f&setSi:e$S''0 >''%" f&setXisible$true%" } }
Introduction to Programming II Page ?0

J.E.D.I.

!or a &ane" to become isib"e3 it s$ou"d be &"aced inside a isib"e +indo+ "i,e a 1rame. Running t$e gi en code gi es t$e 1o""o+ing e=&ected out&ut'

Figure F.;: $unning Jraphics1anel

Introduction to Programming II

Page ?1

J.E.D.I.

!.3.3 More A41 Co*ponents


)ere is a "ist o1 A98 contro"s. 4ontro"s are com&onents suc$ as buttons or te=t 1ie"ds t$at a""o+ t$e user to interact +it$ a 52I a&&"ication. 8$ese are a"" subc"asses o1 t$e -omponent c"ass. Fabe" 8e=t!ie"d 8e=tArea #utton 4$ec,bo= 4$ec,bo=5rou&
,a!le 1H: /K, -omponents

4$oice Fist %cro""bar

8$e 1o""o+ing &rogram creates a 1rame +it$ contro"s contained in it. import 8a#a&awt&*" class ArameD6ontrols e2tends Arame { public static #oid main$String args !% { ArameD6ontrols fwc = new ArameD6ontrols$%" fwc&set;a)out$new Alow;a)out$%%" 99more on this later fwc&setSi:e$S''0 S''%" fwc&add$new Eutton$=.est 1eI=%%" fwc&add$new ;abel$=;abe=%%" fwc&add$new .e2tAield$%%" 6hec/bo2Yroup cbg = new 6hec/bo2Yroup$%" fwc&add$new 6hec/bo2$=ch/3=0 cbg0 true%%" fwc&add$new 6hec/bo2$=ch/4=0 cbg0 false%%" fwc&add$new 6hec/bo2$=ch/>=0 cbg0 false%%" ;ist list = new ;ist$>0 false%" list&add$=1.X=%" list&add$=X=%" fwc&add$list%" 6hoice chooser = new 6hoice$%" chooser&add$=,#ril=%" chooser&add$=1onica=%" chooser&add$=Eritne)=%" fwc&add$chooser%" fwc&add$new Scrollbar$%%" fwc&setXisible$true%" } }

Introduction to Programming II

Page ?2

J.E.D.I.

)ere is a sam&"e screen s$ot o1 running FrameK-ontrols'

Introduction to Programming II

Page ?.

J.E.D.I.

Figure F.A: $unning FrameK-ontrols

Introduction to Programming II

Page ?0

J.E.D.I.

!.4 ?a)out Managers


8$e &osition and si*e o1 t$e com&onents +it$in eac$ container is determined by t$e "ayout manager. 8$e "ayout managers go erns t$e "ayout o1 t$e com&onents in t$e container. 8$ese are some o1 t$e "ayout managers inc"uded in Ja a. 1. !"o+Fayout 2. #orderFayout .. 5ridFayout 0. 5rid#agFayout (. 4ardFayout 6. 8$e "ayout manager can be set using t$e set6ayout met$od o1 t$e -ontainer c"ass. 8$e met$od $as t$e 1o""o+ing signature. #oid set;a)out$;a)out1anager mgr% I1 you &re1er not to use any "ayout manager at a""3 you &ass nu"" as an argument to t$is met$od. #ut t$en3 you +ou"d $a e to &osition t$e e"ements manua""y +it$ t$e use o1 t$e set9ounds met$od o1 t$e -omponent c"ass. public #oid setEounds$int 20 int )0 int width0 int height% 8$e met$od contro"s t$e &osition based on t$e arguments x and y3 and t$e si*e based on t$e s&eci1ied width and height. 8$is +ou"d be -uite di11icu"t and tedious to &rogram i1 you $a e se era" -omponent obBects +it$in t$e -ontainer obBect. JouH"" $a e to ca"" t$is met$od 1or eac$ com&onent. In t$is section3 youH"" "earn about t$e 1irst t$ree "ayout managers.

!.4.1 1he ;lo3?a)out Manager


8$e Flow6ayout is t$e de1au"t manager 1or t$e 1anel c"ass and its subc"asses3 inc"uding t$e /pplet c"ass. It &ositions t$e com&onents in a "e1t to rig$t and to& to bottom manner3 starting at t$e u&&erC"e1t$and corner. Imagine $o+ you ty&e using a &articu"ar +ord editor. 8$is is $o+ t$e Flow6ayout manager +or,s. It $as t$ree constructors +$ic$ are as "isted be"o+. ;lo3?a)out Constructors Alow;a)out$% 4reates a ne+ !"o+Fayout obBect +it$ t$e center a"ignment and (Cunit $ori*onta" and ertica" ga& a&&"ied to t$e com&onents by de1au"t. Alow;a)out$int align% 4reates a ne+ !"o+Fayout obBect +it$ t$e s&eci1ied a"ignment and t$e de1au"t (Cunit $ori*onta" and ertica" ga& a&&"ied to t$e com&onents. Alow;a)out$int align0 int hgap0 int #gap% 4reates a ne+ !"o+Fayout obBect +it$ t$e 1irst argument as t$e a"ignment a&&"ied and t$e hgapCunit $ori*onta" and gapCunit ertica" ga& a&&"ied to t$e com&onents.
,a!le 1I: Flow6ayout constructors

8$e ga& re1ers to t$e s&acing bet+een t$e com&onents and is measured in &i=e"s. 8$e
Introduction to Programming II Page ?(

J.E.D.I.

a"ignment argument s$ou"d be one o1 t$e 1o""o+ing' 1. !"o+Fayout.FE!8 2. !"o+Fayout.4E78ER .. !"o+Fayout.RI5)8 9$at is t$e e=&ected out&ut o1 t$e 1o""o+ing &rogramD import 8a#a&awt&*" class Alow;a)outDemo e2tends Arame { public static #oid main$String args !% { Alow;a)outDemo fld = new Alow;a)outDemo$%" fld&set;a)out$new Alow;a)out$Alow;a)out&KBYH.0 3'0 3'%%" fld&add$new Eutton$=7-<=%%" fld&add$new Eutton$=.D7=%%" fld&add$new Eutton$=.HK<<=%%" fld&setSi:e$3''0 3''%" fld&setXisible$true%" } } %$o+n be"o+ is a sam&"e out&ut running on 9indo+s &"at1orm.

Figure F.2: $unning Flow6ayout:emo

Introduction to Programming II

Page ?6

J.E.D.I.

!.4.2 1he <order?a)out Manager


8$e #orderFayout di ides t$e -ontainer into 1i e &artsC nort$3 sout$3 east3 +est and t$e center. Eac$ com&onents is added to a s&eci1ic region. 8$e nort$ and sout$ regions stretc$ $ori*onta""y +$ereas t$e east and +est regions adBust ertica""y. 8$e center region3 on t$e ot$er $and3 adBusts in bot$ $ori*onta""y and ertica""y. 8$is "ayout is t$e de1au"t 1or Kindow obBects3 inc"uding obBects o1 KindowHs subc"asses Frame and :ialog ty&e. <order?a)out Constructors Eorder;a)out$% 4reates a ne+ #orderFayout obBect +it$ no s&acing a&&"ied among t$e di11erent com&onents. Eorder;a)out$int hgap0 int #gap% 4reates a ne+ #orderFayout obBect +it$ hgapCunit $ori*onta" and #gapCunit s&acing a&&"ied among t$e di11erent com&onents.
,a!le ;": 9order6ayout constructors

Fi,e in t$e Flow6ayout manager3 t$e &arameters hgap and #gap $ere a"so re1ers to t$e s&acing bet+een t$e com&onents +it$in t$e container. 8o add a com&onent to a s&eci1ied region3 use t$e add met$od and &ass t+o arguments' t$e com&onent to add and t$e region +$ere t$e com&onent is to be &ositioned. 7ote t$at on"y one com&onent can be &"aced in one region. Adding more t$an one com&onent to a &articu"ar container resu"ts in dis&"aying on"y t$e "ast com&onent added. 8$e 1o""o+ing "ist gi es t$e a"id regions are &rede1ined 1ie"ds in t$e 9order6ayout c"ass. 1. 2. .. 0. (. #orderFayout.7OR8) #orderFayout.%O28) #orderFayout.EA%8 #orderFayout.9E%8 #orderFayout.4E78ER

)ere is a sam&"e &rogram demonstrating $o+ t$e 9order6ayout +or,s. import 8a#a&awt&*" class Eorder;a)outDemo e2tends Arame { public static #oid main$String args !% { Eorder;a)outDemo bld = new Eorder;a)outDemo$%" bld&set;a)out$new Eorder;a)out$3'0 3'%%" 99ma) remo#e bld&add$new Eutton$=-7K.H=%0 Eorder;a)out&-7K.H%" bld&add$new Eutton$=S7@.H=%0 Eorder;a)out&S7@.H%" bld&add$new Eutton$=<,S.=%0 Eorder;a)out&<,S.%" bld&add$new Eutton$=D<S.=%0 Eorder;a)out&D<S.%" bld&add$new Eutton$=6<-.<K=%0 Eorder;a)out&6<-.<K%" bld&setSi:e$4''0 4''%" bld&setXisible$true%" } } )ere is a sam&"e out&ut o1 t$is &rogram. 8$e second 1igure s$o+s t$e e11ect o1 resi*ing
Introduction to Programming II Page ?6

J.E.D.I.

t$e 1rame.

Introduction to Programming II

Page ?/

J.E.D.I. Figure F.D: $unning 9order6ayout:emo

!.4.3 1he .rid?a)out Manager


9it$ t$e Jrid6ayout manager3 com&onents are a"so &ositioned 1rom "e1t to rig$t and to& to bottom as in t$e Flow6ayout manager. In addition to t$is3 t$e Jrid6ayout manager di ides t$e container into a number o1 ro+s and co"umns. A"" t$ese regions are e-ua""y si*ed. It a"+ays ignores t$e com&onentHs &re1erred si*e. 8$e 1o""o+ing is t$e a ai"ab"e constructors 1or t$e Jrid6ayout c"ass. .rid?a)out Constructors Yrid;a)out$% 4reates a ne+ 5ridFayout obBect +it$ a sing"e ro+ and a sing"e co"umn by de1au"t. Yrid;a)out$int rows0 int cols% 4reates a ne+ 5ridFayout obBect +it$ t$e s&eci1ied number o1 ro+s and co"umns. Yrid;a)out$int rows0 int cols0 int hgap0 int #gap% 4reates a ne+ 5ridFayout obBect +it$ t$e s&eci1ied number o1 ro+s and co"umns. hgapC unit $ori*onta" and gapCunit ertica" s&acings are a&&"ied to t$e com&onents.
,a!le ;1: Jrid6ayout constructors

8ry out t$is &rogram. import 8a#a&awt&*" class Yrid;a)outDemo e2tends Arame { public static #oid main$String args !% { Yrid;a)outDemo gld = new Yrid;a)outDemo$%" gld&set;a)out$new Yrid;a)out$40 >0 ?0 ?%%" gld&add$new Eutton$=7-<=%%" gld&add$new Eutton$=.D7=%%" gld&add$new Eutton$=.HK<<=%%" gld&add$new Eutton$=A7@K=%%" gld&add$new Eutton$=ABX<=%%" gld&setSi:e$4''0 4''%" gld&setXisible$true%" } } 8$is is t$e out&ut o1 t$e &rogram. Obser e t$e e11ect o1 resi*ing t$e 1rame.

Introduction to Programming II

Page ??

J.E.D.I.

Figure F.E: $unning Jrid6ayout:emo

!.4.4 "anels and Co*ple5 ?a)outs


8o create more com&"e= "ayouts3 you can combine t$e di11erent "ayout managers +it$ t$e use o1 &ane"s. Remember t$at a 1anel is a -ontainer and a -omponent at t$e same time. Jou can insert -omponents into t$e 1anel and t$en add t$e 1anel to a s&eci1ied region in t$e -ontainer.

Obser e t$e tec$ni-ue used in t$e 1o""o+ing e=am&"e. import 8a#a&awt&*" class 6omple2;a)out e2tends Arame { public static #oid main$String args !% { 6omple2;a)out cl = new 6omple2;a)out$%" Panel panel-orth = new Panel$%" Panel panel6enter = new Panel$%" Panel panelSouth = new Panel$%" 9* -orth Panel *9 99Panels use Alow;a)out b) default panel-orth&add$new Eutton$=7-<=%%" panel-orth&add$new Eutton$=.D7=%%" panel-orth&add$new Eutton$=.HK<<=%%" 9* 6enter Panel *9 panel6enter&set;a)out$new Yrid;a)out$?0?%%" panel6enter&add$new .e2tAield$=3st=%%" panel6enter&add$new .e2tAield$=4nd=%%" panel6enter&add$new .e2tAield$=>rd=%%" panel6enter&add$new .e2tAield$=?th=%%" 9* South Panel *9 panelSouth&set;a)out$new Eorder;a)out$%%"
Introduction to Programming II Page 100

J.E.D.I.

panelSouth&add$new 6hec/bo2$=6hoose meI=%0 Eorder;a)out&6<-.<K%" panelSouth&add$new 6hec/bo2$=BQm hereI=%0 Eorder;a)out&<,S.%" panelSouth&add$new 6hec/bo2$=Pic/ meI=%0 Eorder;a)out&D<S.%" 9* ,dding the Panels to the Arame container *9 99Arames use Eorder;a)out b) default cl&add$panel-orth0 Eorder;a)out&-7K.H%" cl&add$panel6enter0 Eorder;a)out&6<-.<K%" cl&add$panelSouth0 Eorder;a)out&S7@.H%" cl&setSi:e$>''0>''%" cl&setXisible$true%"

)ere is t$e out&ut o1 t$e &rogram.

Introduction to Programming II

Page 101

J.E.D.I. Figure F.F: $unning -omplex6ayout

!.5 -3ing .8( Co*ponents


Fi,e t$e A98 &ac,age3 t$e %+ing &ac,age &ro ides c"asses 1or creating 52I a&&"ications. 8$e &ac,age is 1ound in <a#ax.swing. 8$e main di11erence bet+een t$ese t+o is t$at %+ing com&onents are +ritten entire"y using Ja a +$ereas t$e "atter is not. As a resu"t3 52I &rograms +ritten using c"asses 1rom t$e %+ing &ac,age $a e t$e same "oo, and 1ee" e en +$en e=ecuted on di11erent &"at1orms. Moreo er3 %+ing &ro ides more interesting com&onents suc$ as t$e co"or c$ooser and t$e o&tion &ane. 8$e names o1 t$e %+ing 52I com&onents are a"most simi"ar to t$at o1 t$e A98 52I com&onents. An ob ious di11erence is in t$e naming con entions o1 t$e com&onents. #asica""y3 t$e name o1 %+ing com&onents are Bust t$e name o1 A98 com&onents but +it$ an additiona" &re1i= o1 J. !or e=am&"e3 one com&onent in A98 is t$e 9utton c"ass. 8$e corres&onding com&onent 1or t$is in t$e %+ing &ac,age is t$e G9utton c"ass. Pro ided be"o+ is t$e "ist o1 some o1 t$e %+ing 52I com&onents.

-3ing Co*ponent J4om&onent J#utton J4$ec,#o= J!i"e4$ooser J8e=t!ie"d J!rame

Description 8$e root c"ass 1or a"" %+ing com&onents3 e=c"uding to&C"e e" containers. A I&us$I button. 4orres&onds to t$e 9utton c"ass in t$e A98 &ac,age. An item t$at can be se"ected or dese"ected by t$e user. 4orres&onds to t$e -hec'!ox c"ass in t$e A98 &ac,age. A""o+s user to se"ect a 1i"e. 4orres&onds to t$e File-hooser c"ass in t$e A98 &ac,age. A""o+s 1or editing o1 a sing"eC"ine te=t. 4orres&onds to ,extField c"ass in t$e A98 &ac,age. E=tends and corres&onds to t$e Frame c"ass in t$e A98 &ac,age but t$e t+o are s"ig$t"y incom&atib"e in terms o1 adding com&onents to t$is container. 7eed to get t$e current content &ane be1ore adding a com&onent. E=tends G-omponent. A sim&"e container c"ass but not to&C"e e". 4orres&onds to 1anel c"ass in t$e A98 &ac,age.

JPane"

Introduction to Programming II

Page 102

J.E.D.I.

-3ing Co*ponent JA&&"et

Description E=tends and corres&onds to t$e /pplet c"ass in t$e A98 &ac,age. A"so s"ig$t"y incom&atib"e +it$ t$e /pplet c"ass in terms o1 adding com&onents to t$is container. E=tends G-omponent. Pro ides an easy +ay o1 dis&"aying &o&Cu& dia"og bo=. E=tends and corres&onds to t$e :ialog c"ass in t$e A98 &ac,age. 2sua""y used to in1orm t$e user o1 somet$ing or &rom&t t$e user 1or an in&ut.

JO&tionPane JDia"og

J4o"or4$ooser E=tends G-omponent. A""o+ t$e user to se"ect a co"or.


,a!le ;;: Some Swing components

!or t$e com&"ete "ist o1 %+ing com&onents3 &"ease re1er to t$e API documentation.

!.5.1 -etting 8p 1op-?evel Containers


As mentioned3 t$e to&C"e e" containers "i,e GFrame and G/pplet in %+ing are s"ig$t"y incom&atib"e +it$ t$ose in A98. 8$is is in terms o1 adding com&onents to t$e container. Instead o1 direct"y adding a com&onent to t$e container as in A98 containers3 you $a e to 1irst get t$e content &ane o1 t$e container. 8o do t$is3 youH"" $a e to use t$e get-ontent1ane met$od o1 t$e container.

!.5.2 A ,;ra*e %5a*ple


import 8a#a2&swing&*" import 8a#a&awt&*" class SwingDemo { RArame frame" RPanel panel" R.e2tAield te2tAield" REutton button" 6ontainer contentPane" #oid launchArame$% { 9* initiali:ation *9 frame = new RArame$=1) Airst Swing ,pplication=%" panel = new RPanel$%" te2tAield = new R.e2tAield$=Default te2t=%" button = new REutton$=6lic/ meI=%" contentPane = frame&get6ontentPane$%" 9* add components to panelN uses Alow;a)out b) default *9 panel&add$te2tAield%" panel&add$button%" 9* add components to contentPaneN uses Eorder;a)out *9 contentPane&add$panel0 Eorder;a)out&6<-.<K%" frame&pac/$%" 99causes si:e of frame to be based on the components frame&setXisible$true%" } public static #oid main$String args !% {
Introduction to Programming II Page 10.

J.E.D.I.

SwingDemo sd = new SwingDemo$%" sd&launchArame$%"

7ote t$at t$e <a#a.awt &ac,age is sti"" im&orted because t$e "ayout managers in use are de1ined in t$is &ac,age. A"so3 gi ing a tit"e to t$e 1rame and &ac,ing t$e com&onents +it$in t$e 1rame is a&&"icab"e 1or A98 1rames too. Coding .uidelines/ 8!ser#e the coding style applied in this example as opposed to the examples for /K,. ,he components are declared as fields& a launchFrame method is defined& and initiali5ation and addition of components are all done in the launchFrame method. Ke no longer <ust extend the Frame class. ,he ad#antage of using this style would !ecome apparent when we get to e#ent handling. )ere is a sam&"e out&ut.

Figure F.H: $unning Swing:emo

!.5.3 A ,Option"ane %5a*ple


import 8a#a2&swing&*" class R7ptionPaneDemo { R7ptionPane optionPane" #oid launchArame$% { optionPane = new R7ptionPane$%" String name = optionPane&showBnputDialog$=Hi0 whatQs )our name5=%" optionPane&show1essageDialog$null0 =-ice to meet )ou0 = ( name ( =&=0 =Yreeting&&&=0 optionPane&P;,B-*1<SS,Y<%" S)stem&e2it$'%" } public static #oid main$String args !% { new R7ptionPaneDemo$%&launchArame$%" } } %ee $o+ easy it is as, in&ut 1rom t$e user. )ere is t$e sam&"e out&ut 1or t$e gi en &rogram.

Introduction to Programming II

Page 100

J.E.D.I.

Figure F.I: $unning G8ption1ane:emo

Introduction to Programming II

Page 10(

J.E.D.I.

+ 89I E(ent Hand&ing


$.1 Objectives
In t$is modu"e3 you +i"" "earn $o+ to $and"e e ents triggered +$en t$e user interacts +it$ your 52I a&&"ication. A1ter com&"eting t$is modu"e3 youH"" be ab"e to de e"o& 52I a&&"ications t$at res&onds to user interaction. A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. Enumerate t$e de"egation e ent mode" com&onents 2. E=&"ain $o+ t$e de"egation e ent mode" +or,s .. 4reate 52I a&&"ications t$at interact +it$ t$e user 0. Discuss bene1its o1 ada&ter c"asses (. Discuss ad antages o1 using inner and anonymous c"asses

$.2 1he Delegation %vent Model


8$e De"egation e ent mode" describes $o+ your &rogram can res&ond to user interaction. 8o understand t$e mode"3 "et us 1irst study its t$ree im&ortant com&onents. 1. E ent %ource 8$e e ent source re1ers to t$e 52I com&onent t$at generates t$e e ent. !or e=am&"e3 i1 t$e user &resses a button3 t$e e ent source in t$is case is t$e button. 2. E ent FistenerA)and"er 8$e e ent "istener recei es ne+s o1 e ents and &rocesses userHs interaction. 9$en a button is &ressed3 t$e "istener may $and"e t$is by dis&"aying an in1ormation use1u" to t$e user. .. E ent ObBect 9$en an e ent occurs ;i.e.3 +$en t$e user interacts +it$ a 52I com&onent>3 an e ent obBect is created. 8$e obBect contains a"" t$e necessary in1ormation about t$e e ent t$at $as occurred. 8$e in1ormation inc"udes t$e ty&e o1 e ent t$at $as occurred3 say3 t$e mouse +as c"ic,ed. 8$ere are se era" e ent c"asses 1or t$e di11erent categories o1 user action. An e ent obBect $as a data ty&e o1 one o1 t$ese c"asses.

Introduction to Programming II

Page 106

J.E.D.I.

)ere no+ is t$e de"egation e ent mode".

Figure H.1: :elegation E#ent 0odel

Initia""y3 a "istener s$ou"d be registered +it$ a source so t$at it can recei e in1ormation about e ents t$at occur at t$e source. On"y registered "isteners can recei e noti1ications o1 e ents. Once registered3 a "istener sim&"y +aits unti" an e ent occurs. 9$en somet$ing $a&&ens at t$e e ent source3 an e ent obBect describing t$e e ent is created. 8$e e ent is t$en 1ired by t$e source to t$e registered "isteners. Once t$e "istener recei es an e ent obBect ;i.e.3 a noti1ication> 1rom t$e source3 it goes to +or,. It deci&$ers t$e noti1ication and &rocesses t$e e ent t$at occurred.

$.2.1 9egistration o+ ?isteners


8$e e ent source registers a "istener t$roug$ t$e add<,ype 6istener met$ods. #oid add<.)pe>;istener$<.)pe>;istener listener7b8% <,ype de&ends on t$e ty&e o1 e ent source. It can be ?ey3 0ouse3 Focus3 -omponent3 /ction and ot$ers. %e era" "isteners can register +it$ one e ent source to recei e e ent noti1ications.
Introduction to Programming II Page 106

J.E.D.I.

A registered "istener can a"so be unregistered using t$e remo#e<,ype 6istener met$ods. #oid remo#e<.)pe>;istener$<.)pe>;istener listener7b8%

$.3 %vent Classes


An e ent obBect $as an e ent c"ass as its re1erence data ty&e. At t$e root o1 e ent c"ass $eirarc$y is t$e E#ent8!<ect c"ass3 +$ic$ is 1ound in t$e <a#a.util &ac,age. An immediate subc"ass o1 t$e E#ent8!<ect c"ass is t$e /K,E#ent c"ass. 8$e /K,E#ent c"ass is de1ined in Ba a.a+t &ac,age. It is t$e root o1 a"" A98Cbased e ents. )ere are some o1 t$e A98 e ent c"asses.

%vent Class

Description

4om&onentE ent E=tends /K,E#ent. Instantiated +$en a com&onent is mo ed3 resi*ed3 made isib"e or $idden. In&utE ent ActionE ent ItemE ent @eyE ent MouseE ent E=tends -omponentE#ent. 8$e abstract root e ent c"ass 1or a"" com&onentC"e e" in&ut e ent c"asses. E=tends /K,E#ent. Instantiated +$en a button is &ressed3 a "ist item is doub"eCc"ic,ed3 or a menu item is se"ected. E=tends /K,E#ent. Instantiated +$en an item is se"ected or dese"ected by t$e user3 suc$ as in a "ist or a c$ec,bo=. E=tends InputE#ent. Instantiated +$en a ,ey is &ressed3 re"eased or ty&ed. E=tends InputE#ent. Instantiated +$en a mouse button is &ressed3 re"eased3 or c"ic,ed ;&ressed and re"eased>3 or +$en a mouse cursor enteres or e=its a isib"e &art o1 a com&onent. E=tends /K,E#ent. Instantiated +$en t$e te=t area is c$anged. a"ue o1 a te=t 1ie"d or a

8e=tE ent 9indo+E ent

E=tends -omponentE#ent. Instantiated +$en a Kindow obBect is o&ened3 c"osed3 acti ated3 deacti ated3 iconi1ied3 deiconi1ied3 or +$en 1ocus is trans1erred into or out o1 t$e +indo+.
,a!le ;A: E#ent classes

8a,e note t$at a"" /K,E#ent subc"asses 1o""o+ t$is naming con ention' <.)pe><#ent

Introduction to Programming II

Page 10/

J.E.D.I.

$.4 %vent ?isteners


E ent "isteners are Bust c"asses t$at im&"ement t$e <,ype 6istener inter1aces. 8$e 1o""o+ing tab"e s$o+s some o1 t$e "istener inter1aces common"y used. %vent ?isteners ActionFistener MouseFistener MouseMotionFistener 9indo+Fistener Recei es action e ents. Recei es mouse e ents. Recei es mouse motion e ents3 +$ic$ inc"ude dragging and mo ing t$e mouse. Recei es +indo+ e ents.
,a!le ;2: E#ent 6isteners

Description

$.4.1 Action?istener Method


8$e ActionFistener inter1ace contains on"y one met$od. Action?istener Method public #oid actionPerformed$,ction<#ent e% 4ontains t$e $and"er 1or t$e /ctionE#ent e t$at occurred.
,a!le ;D: ,he /ction6istener method

$.4.2 Mouse?istener Methods


8$ese are t$e 0ouse6istener met$ods t$at s$ou"d be o erriden by t$e im&"ementing c"ass. Mouse?istener Methods public #oid mouse6lic/ed$1ouse<#ent e% 4ontains t$e $and"er 1or t$e e ent +$en t$e mouse is c"ic,ed ;i.e.3 &ressed and re"eased>. public #oid mouse<ntered$1ouse<#ent e% 4ontains t$e code 1or $and"ing t$e case +$erein t$e mouse enters a com&onent. public #oid mouse<2ited$1ouse<#ent e% 4ontains t$e code 1or $and"ing t$e case +$erein t$e mouse e=its a com&onent. public #oid mousePressed$1ouse<#ent e% In o,ed +$en t$e mouse button is &ressed on a com&onent. public #oid mouseKeleased$1ouse<#ent e% In o,ed +$en t$e mouse button is re"eased on a com&onent.
,a!le ;E: ,he 0ouse6istener methods

Introduction to Programming II

Page 10?

J.E.D.I.

$.4.3 MouseMotion?istener Methods


8$e 0ouse0otion6istener $as t+o met$ods to be im&"emented. Mouse?istener Methods public #oid mouseDragged$1ouse<#ent e% 4ontains t$e code 1or $and"ing t$e case +$erein t$e mouse button is &ressed on a com&onent and dragged. 4a""ed se era" times as t$e mouse is dragged. public #oid mouse1o#ed$1ouse<#ent e% 4ontains t$e code 1or $and"ing t$e case +$erein t$e mouse cursor is mo ed onto a com&onent3 +it$out t$e mouse button being &ressed. 4a""ed mu"ti&"e times as t$e mouse is mo ed.
,a!le ;F: ,he 0ouse0otion6istener methods

$.4.4 4indo3?istener Methods


8$ese are t$e met$ods o1 t$e Kindow6istener inter1ace. 4indo3?istener Methods public #oid window7pened$Dindow<#ent e% 4ontains t$e code 1or $and"ing t$e case +$en t$e Kindow obBect is o&ened ;i.e.3 made isib"e 1or t$e 1irst time>. public #oid window6losing$Dindow<#ent e% 4ontains t$e code 1or $and"ing t$e case +$en t$e user attem&ts to c"ose Kindow obBect 1rom t$e obBectHs system menu. public #oid window6losed$Dindow<#ent e% 4ontains t$e code 1or $and"ing t$e case +$en t$e Kindow obBect +as c"osed a1ter ca""ing dis&ose ;i.e.3 re"ease o1 resources used by t$e source> on t$e obBect. public #oid window,cti#ated$Dindow<#ent e% In o,ed +$en a Kindow obBect is t$e acti e +indo+ ;i.e.3 t$e +indo+ in use>. public #oid windowDeacti#ated$Dindow<#ent e% In o,ed +$en a Kindow obBect is no "onger t$e acti e +indo+. public #oid windowBconified$Dindow<#ent e% 4a""ed +$en a Kindow obBect is minimi*ed. public #oid windowDeiconified$Dindow<#ent e% 4a""ed +$en a Kindow obBect re erts 1rom a minimi*ed to a norma" state.
,a!le ;H: ,he Kindow6istener methods

$.4.5 .uidelines +or Creating Applications 7andling .8( %vents


8$ese are t$e ste&s you need to remember +$en creating a 52I a&&"ication +it$ e ent $and"ing.
Introduction to Programming II Page 110

J.E.D.I.

1. 4reate a c"ass t$at describes and dis&"ays t$e a&&earance o1 your 52I a&&"ication. 2. 4reate a c"ass t$at im&"ements t$e a&&ro&riate "istener inter1ace. 8$is c"ass may re1er to t$e same c"ass as in t$e 1irst ste&. .. In t$e im&"ementing c"ass3 o erride AFF met$ods o1 t$e a&&ro&riate "istener inter1ace. Describe in eac$ met$od $o+ you +ou"d "i,e t$e e ent to be $and"ed. Jou may gi e em&ty im&"ementations 1or met$ods you donHt +ant to $and"e. 0. Register t$e "istener obBect3 t$e instantiation o1 t$e "istener c"ass in ste& 23 +it$ t$e source com&onent using t$e add<,ype 6istener met$od.

$.4.

Mouse %vents %5a*ple

import 8a#a&awt&*" import 8a#a&awt&e#ent&*" public class 1ouse<#entsDemo e2tends Arame implements 1ouse;istener0 1ouse1otion;istener { .e2tAield tf" public 1ouse<#entsDemo$String title%{ super$title%" tf = new .e2tAield$S'%" add1ouse;istener$this%" } public #oid launchArame$% { 9* ,dd components to the frame *9 add$tf0 Eorder;a)out&S7@.H%" setSi:e$>''0>''%" setXisible$true%" } public #oid mouse6lic/ed$1ouse<#ent me% { String msg = =1ouse clic/ed&=" tf&set.e2t$msg%" } public #oid mouse<ntered$1ouse<#ent me% { String msg = =1ouse entered component&=" tf&set.e2t$msg%" } public #oid mouse<2ited$1ouse<#ent me% { String msg = =1ouse e2ited component&=" tf&set.e2t$msg%" } public #oid mousePressed$1ouse<#ent me% { String msg = =1ouse pressed&=" tf&set.e2t$msg%" } public #oid mouseKeleased$1ouse<#ent me% { String msg = =1ouse released&=" tf&set.e2t$msg%" } public #oid mouseDragged$1ouse<#ent me% { String msg = =1ouse dragged at = ( me&getV$% ( =0= ( me&getP$%" tf&set.e2t$msg%" } public #oid mouse1o#ed$1ouse<#ent me% { String msg = =1ouse mo#ed at = ( me&getV$% ( =0= ( me&getP$%" tf&set.e2t$msg%"
Introduction to Programming II Page 111

J.E.D.I.

} public static #oid main$String args !% { 1ouse<#entsDemo med = new 1ouse<#entsDemo$=1ouse <#ents Demo=%" med&launchArame$%" }

)ere are some screen s$ots o1 0ouseE#ents:emo'

Figure H.;: $unning 0ouseE#ents:emo

Figure H.A: $unning 0ouseE#ents:emo: 0ouse enters the Frame Introduction to Programming II Page 112

J.E.D.I.

Figure H.2: $unning 0ouseE#ents:emo: 0ouse exits the Frame

Introduction to Programming II

Page 11.

J.E.D.I.

$.4.! Close 4indo3 %5a*ple


import 8a#a&awt&*" import 8a#a&awt&e#ent&*" class 6loseArame e2tends Arame implements Dindow;istener { ;abel label" 6loseArame$String title% { super$title%" label = new ;abel$=6lose the frame&=%" this&addDindow;istener$this%" } #oid launchArame$% { setSi:e$>''0>''%" setXisible$true%" } public #oid window,cti#ated$Dindow<#ent e% { } public #oid window6losed$Dindow<#ent e% { } public #oid window6losing$Dindow<#ent e% { setXisible$false%" S)stem&e2it$'%" } public #oid windowDeacti#ated$Dindow<#ent e% { } public #oid windowDeiconified$Dindow<#ent e% { } public #oid windowBconified$Dindow<#ent e% { } public #oid window7pened$Dindow<#ent e% { } public static #oid main$String args !% { 6loseArame cf = new 6loseArame$=6lose Dindow <2ample=%" cf&launchArame$%" } }

Introduction to Programming II

Page 110

J.E.D.I.

Running t$is &rogram sim&"y dis&"ays a 1rame "i,e t$e 1o""o+ing screen s$ot'

Figure H.D: $unning -loseFrame

Introduction to Programming II

Page 11(

J.E.D.I.

$.5 Adapter Classes


Im&"ementing a"" met$ods o1 an inter1ace ta,es a "ot o1 +or,. More o1ten t$an not3 you are interested in im&"ementing some met$ods o1 t$e inter1ace on"y. !ortunate"y3 Ja a &ro ides us +it$ ada&ter c"asses t$at im&"ement a"" met$ods o1 eac$ "istener inter1ace +it$ more t$an one met$od. 8$e im&"ementations o1 t$e met$ods are a"" em&ty.

$.5.1 Close 4indo3 %5a*ple


import 8a#a&awt&*" import 8a#a&awt&e#ent&*" class 6loseArame e2tends Arame{ ;abel label" 6A;istener w = new 6A;istener$this%" 6loseArame$String title% { super$title%" label = new ;abel$=6lose the frame&=%" this&addDindow;istener$w%" } #oid launchArame$% { setSi:e$>''0>''%" setXisible$true%" } public static #oid main$String args !% { 6loseArame cf = new 6loseArame$=6lose Dindow <2ample=%" cf&launchArame$%" }

class 6A;istener e2tends Dindow,dapter{ 6loseArame ref" 6A;istener$ 6loseArame ref %{ this&ref = ref" } public #oid window6losing$Dindow<#ent e% { ref&dispose$%" S)stem&e2it$3%"

Introduction to Programming II

Page 116

J.E.D.I.

$.

(nner Classes and Anon)*ous (nner Classes

8$is section gi es you a re ie+ o1 a conce&t youH e a"ready "earned in your 1irst &rogramming course. Inner c"asses and anonymous inner c"asses are ery use1u" in 52I e ent $and"ing.

$. .1 (nner Classes
)ere is a brie1 re1res$er on inner c"asses. An inner c"ass3 as its name im&"ies3 is a c"ass dec"ared +it$in anot$er c"ass. 8$e use o1 inner c"asses +ou"d $e"& you sim&"i1y your &rograms3 es&ecia""y in e ent $and"ing as s$o+n in t$e succeeding e=am&"e.

$. .2 Close 4indo3 %5a*ple


import 8a#a&awt&*" import 8a#a&awt&e#ent&*" class 6loseArame e2tends Arame{ ;abel label" 6loseArame$String title% { super$title%" label = new ;abel$=6lose the frame&=%" this&addDindow;istener$new 6A;istener$%%" } #oid launchArame$% { setSi:e$>''0>''%" setXisible$true%" } class 6A;istener e2tends Dindow,dapter { public #oid window6losing$Dindow<#ent e% { dispose$%" S)stem&e2it$3%" } } public static #oid main$String args !% { 6loseArame cf = new 6loseArame$=6lose Dindow <2ample=%" cf&launchArame$%" }

Introduction to Programming II

Page 116

J.E.D.I.

$. .3 Anon)*ous (nner Classes


7o+3 anonymous inner c"asses are unnamed inner c"asses. 2se o1 anonymous inner c"asses +ou"d 1urt$er sim&"i1y your codes. )ere is a modi1ication o1 t$e e=am&"e in t$e &receding section.

$. .4 Close 4indo3 %5a*ple


import 8a#a&awt&*" import 8a#a&awt&e#ent&*" class 6loseArame e2tends Arame{ ;abel label" 6loseArame$String title% { super$title%" label = new ;abel$=6lose the frame&=%" this&addDindow;istener$new Dindow,dapter$% { public #oid window6losing$Dindow<#ent e%{ dispose$%" S)stem&e2it$3%" } }%" } #oid launchArame$% { setSi:e$>''0>''%" setXisible$true%" } public static #oid main$String args !% { 6loseArame cf = new 6loseArame$=6lose Dindow <2ample=%" cf&launchArame$%" }

Introduction to Programming II

Page 11/

J.E.D.I.

: Threads
&.1 Objectives
JouH e been accustomed to &rograms t$at e=ecute se-uentia""y. A se-uentia" &rogram re1ers to a &rogram t$at $as one 1"o+ o1 e=ecution. It $as a a starting &oint o1 e=ecution3 an e=ecution se-uence3 and an end. During runtime3 t$ere is e=act"y a sing"e &rocess being e=ecuted. )o+e er3 in rea" +or"d situations3 t$ere is a need to $and"e concurrent &rocesses. 8$ese are &rocesses running at t$e same time. 8$is is +$ere t$reads come in. A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. De1ine +$at t$reads are 2. Enumerate t$e di11erent t$read states .. E=&"ain t$e conce&t o1 &riorities in t$reads 0. 2se t$e met$ods in t$e ,hread c"ass 0. 4reate your o+n t$reads (. 2se sync$roni*ation 1or concurrent"y running t$reads t$at are de&endent on eac$ ot$er 6. A""o+ t$reads to communicate +it$ ot$er concurrent"y running t$reads 6. 2se t$e concurrency uti"ities

&.2 1hread De+inition and <asics


&.2.1 1hread De+inition
A t$read re1ers to a sing"e se-uentia" 1"o+ o1 contro" +it$in a &rogram. !or sim&"icity3 t$in, o1 t$reads as &rocesses being e=ecuted +it$in t$e conte=t o1 a certain &rogram. 4onsider modern o&erating systems t$at a""o+ you to run mu"ti&"e &rograms at once. 9$i"e ty&ing a document on your com&uter using a te=t editor3 you can "isten to music at t$e same time and sur1 t$roug$ t$e net on your P4. 8$e o&erating system insta""ed in your com&uter a""o+s mu"titas,ing. Fi,e+ise3 a &rogram ;ana"ogous to your P4> can a"so e=ecute se era" &rocesses ;ana"ogous to t$e di11erent a&&"ications you run on your P4> simu"taneous"y. An e=am&"e o1 suc$ an a&&"ication is t$e )otJa a +eb bro+ser3 +$ic$ a""o+s you to bro+se t$roug$ a &age +$i"e do+n"oading some obBect suc$ as an image3 or &"ay animation and a"so audio 1i"es at t$e same time.

Introduction to Programming II

Page 11?

J.E.D.I. Figure I.1: ,hreads

&.2.2 1hread -tates


A t$read can in one o1 se era" &ossib"e states' 1. Running 8$e t$read is current"y being e=ecuted and is in contro" o1 t$e 4P2. 2. Ready to run 8$e t$read can no+ be e=ecuted but is not yet gi en t$e c$ance to do so. .. Resumed A1ter being &re ious"y b"oc,edAsus&ended3 t$e state is no+ ready to run. 0. %us&ended A t$read o"untari"y gi es u& contro" o er t$e 4P2 to a""o+ ot$er t$reads to run. (. #"oc,ed A b"oc,ed t$read is one t$at is not ab"e to run because it is +aiting 1or a resource to be a ai"ab"e or an e ent to $a&&en.

&.2.3 "riorities
8o determine +$ic$ t$read recei es 4P2 contro" and gets to be e=ecuted 1irst3 eac$ t$read is assigned a &riority. A &riority is an integer a"ue ranging 1rom 1 to 10. 8$e $ig$er t$e t$read &riority3 t$e "arger c$ance t$at t$e t$read gets to be e=ecuted 1irst. !or instance3 assume t$at t$ere are t+o t$reads and bot$ are ready to run. 8$e 1irst t$read is assigned a &riority o1 ( +$i"e t$e second t$read $as a &riority o1 10. %ay t$at t$e 1irst t$read is a"ready running +$en t$e second t$read comes in. 8$en3 t$e second t$read +ou"d recei e contro" o1 t$e 4P2 and gets to be e=ecuted since it $as a $ig$er &riority com&ared to t$e current"y running t$read. 8$is scenario is an e=am&"e o1 a conte=t s+itc$. A conte=t s+itc$ occurs +$en a t$read snatc$es t$e contro" o1 4P2 1rom anot$er t$read. 8$ere are se era" +ays on $o+ a conte=t s+itc$ may occur. One scenario is +$en a running t$read o"untari"y re"in-uis$es 4P2 contro" to gi e ot$er t$reads o&&ortunities to run. In t$is case3 t$e $ig$est &riority t$read t$at is ready to run recei es 4P2 contro". Anot$er +ay 1or conte=t s+itc$ to occur is +$en a running t$read is &reem&ted by a $ig$er &riority t$read as seen in t$e e=am&"e t$at +as Bust gi en. It may a"so be &ossib"e t$at +$en t$e 4P2 becomes a ai"ab"e3 t$ere is more t$an one $ig$est &riority t$read t$at is ready to run. !or deciding +$ic$ o1 t+o t$reads +it$ t$e same &riority recei es 4P2 contro" de&ends on t$e o&erating system. 9indo+s ?(A?/A78 uses timeCs"iced roundCrobin to $and"e t$is case. Eac$ t$read o1 same &riority is gi en a "imited amount o1 time to e=ecute be1ore &assing t$e 4P2 contro" to ot$er t$reads o1 e-ua" &riority. On t$e ot$er $and3 %o"aris a""o+s a t$read to e=ecute unti" it com&"etes its +or, or unti" it o"untari"y re"in-uis$es 4P2 contro".

Introduction to Programming II

Page 120

J.E.D.I.

&.3 1he 1hread Class


&.3.1 Constructor
8$e t$read $as eig$t constructors. Fet us $a e a -uic, "oo, at some o1 t$ese constructors. 1hread Constructors .hread$% 4reates a ne+ ,hread obBect. .hread$String name% 4reates a ne+ ,hread obBect +it$ t$e s&eci1ied name. .hread$Kunnable target% 4reates a ne+ ,hread obBect based on a $unna!le obBect. target re1ers to t$e obBect +$ose run met$od is ca""ed. .hread$Kunnable target0 String name% 4reates a ne+ ,hread obBect +it$ t$e s&eci1ied name and based on a $unna!le obBect.
,a!le ;I: ,hread constructors

&.3.2 Constants
8$e ,hread c"ass a"so &ro ides constants 1or &riority 1ie"d summary o1 t$e ,hread c"ass. 1hread Constants public final static int 1,V*PKB7KB.P 8$e ma=imum &riority a"ue3 10. public final static int 1B-*PKB7KB.P 8$e minimum &riority a"ue3 1. public final static int -7K1*PKB7KB.P 8$e de1au"t &riority a"ue3 (.
,a!le A": ,hread constants

a"ues. 8$e 1o""o+ing tab"e gi es a

&.3.3 Methods
7o+3 t$ese are some o1 t$e met$ods &ro ided in t$e ,hread c"ass. 1hread Methods public static .hread current.hread$% Returns a re1erence to t$e t$read t$at is current"y running. public final String get-ame$% Returns t$e name o1 t$is t$read. public final #oid set-ame$String name%
Introduction to Programming II Page 121

J.E.D.I.

1hread Methods Renames t$e t$read to t$e s&eci1ied argument name. May t$ro+ SecurityException. public final int getPriorit)$% Returns t$e &riority assigned to t$is t$read. public final boolean is,li#e$% Indicates +$et$er t$is t$read is running or not. public final #oid 8oin$ long millis0 int nanos!!% An o er"oaded met$od. 8$e current"y running t$read +ou"d $a e to +ait unti" t$is t$read dies ;i1 no &arameter is s&eci1ied>3 or unti" t$e s&eci1ied time is u&. public static #oid sleep$long millis% %us&ends t$e t$read 1or millis amount o1 time. May t$ro+ InterruptedException. public #oid run$% 8$read e=ecution begins +it$ t$is met$od. public #oid start$% 4auses t$read e=ecution to begin by ca""ing t$e run met$od.
,a!le A1: ,hread methods

&.3.4 A 1hread %5a*ple


Jour 1irst t$read e=am&"e is a sim&"e counter. import 8a#a2&swing&*" import 8a#a&awt&*" class 6ountDownY@B e2tends RArame { R;abel label" 6ountDownY@B$String title% { super$title%" label = new R;abel$=Start countI=%" setDefault6lose7peration$RArame&<VB.*7-*6;7S<%" get6ontentPane$%&add$new Panel$%0 Eorder;a)out&D<S.%" get6ontentPane$%&add$label%" setSi:e$>''0>''%" setXisible$true%" } #oid start6ount$% { tr) { for $int i = 3'" i > '" iLL% { .hread&sleep$3'''%" label&set.e2t$i ( ==%" } .hread&sleep$3'''%" label&set.e2t$=6ount down complete&=%" .hread&sleep$3'''%" } catch $Bnterrupted<2ception ie% { } label&set.e2t$.hread&current.hread$%&toString$%%" } public static #oid main$String args !% { 6ountDownY@B cdg = new 6ountDownY@B$=6ount down Y@B=%"
Introduction to Programming II Page 122

J.E.D.I.

cdg&start6ount$%"

8$e -ount:ownJui &rogram sim&"y counts do+n 1rom 10 to 1 and t$en &rints in1ormation about t$e current"y running t$read. )ere are some screen s$ots 1rom running t$e code.

Figure I.;: -ount:ownJui Screen shots

&.4 Creating 1hreads


8$reads can eit$er be created by e=tending t$e ,hread c"ass or by im&"ementing t$e $unna!le inter1ace.

Introduction to Programming II

Page 12.

J.E.D.I.

&.4.1 %5tending the 1hread Class


8$e ne=t e=am&"e is a userCde1ined ,hread c"ass t$at &rints t$e name o1 a t$read obBect 1or 100 times. class Print-ame.hread e2tends .hread { Print-ame.hread$String name% { super$name%" start$%" 99runs the thread once instantiated } public #oid run$% { String name = get-ame$%" for $int i = '" i < 3''" i((% { S)stem&out&print$name%" } } } class .est.hread { public static #oid Print-ame.hread Print-ame.hread Print-ame.hread Print-ame.hread } } main$String args !% { pnt3 = new Print-ame.hread$=,=%" pnt4 = new Print-ame.hread$=E=%" pnt> = new Print-ame.hread$=6=%" pnt? = new Print-ame.hread$=D=%"

Obser e t$at t$e re1erence ariab"es pnt13 pnt;3 pntA3 and pnt2 are sim&"y used once. !or t$is a&&"ication3 t$ere is rea""y no need to use ariab"es to re1er to eac$ t$read. Jou can re&"ace t$e body o1 t$e main met$od +it$ t$e 1o""o+ing statements' new new new new Print-ame.hread$=,=%" Print-ame.hread$=E=%" Print-ame.hread$=6=%" Print-ame.hread$=D=%"

8$e &rogram &roduces di11erent out&uts 1or eac$ run. )ere is a sam&"e out&ut. ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,E6D,E6D,E6D,E6D,E6D,E6D, E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D ,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6D,E6 D,E6D,E6D,E6D,E6D,E6D,E6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6 DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6DE6 DE6DE6DE6DE6DE6DE6DE6DE6D

&.4.2 (*ple*enting the 9unnable (nter+ace


Anot$er +ay o1 creating userCde1ined t$reads is to im&"ement t$e $unna!le inter1ace. 8$e on"y met$od t$at t$e $unna!le inter1ace re-uires you to im&"ement is t$e run met$od. 8$in, o1 t$e run met$od as t$e main met$od o1 t$e t$reads you create. 8$e 1o""o+ing e=am&"e is simi"ar to t$e "ast e=am&"e you studies but uses t$e second +ay o1 creating t$reads instead. class Print-ame.hread implements Kunnable { .hread thread" Print-ame.hread$String name% { thread = new .hread$this0 name%" thread&start$%"
Introduction to Programming II Page 120

J.E.D.I.

} public #oid run$% { String name = thread&get-ame$%" for $int i = '" i < 3''" i((% { S)stem&out&print$name%" } }

class .est.hread { public static #oid main$String args !% { new Print-ame.hread$=,=%" new Print-ame.hread$=E=%" new Print-ame.hread$=6=%" new Print-ame.hread$=D=%" } }

&.4.3 %5tending vs. (*ple*enting


O1 t$e t+o +ays o1 creating t$reads3 c$oosing bet+een t$ese t+o is a matter o1 taste. Im&"ementing t$e $unna!le inter1ace may ta,e more +or, since +e sti"" $a e to dec"are a ,hread obBect and ca"" t$e ,hread met$ods on t$is obBect. E=tending t$e ,hread c"ass3 $o+e er3 +ou"d mean t$at your c"ass can no "onger e=tend any ot$er c"ass since Ja a &ro$ibits mu"ti&"e in$eritance. A tradeCo11 bet+een ease o1 im&"ementation and &ossibi"ity o1 e=tending t$e c"ass is made +it$ t$e sty"e you se"ected. 9eig$ out +$ic$ is more im&ortant to you because t$e c$oice is yours.

Introduction to Programming II

Page 12(

J.E.D.I.

&.4.4 An %5a*ple 8sing the join Method


7o+ t$at youH e "earned $o+ to create t$reads3 "etHs see $o+ t$e <oin met$od +or,s. 8$e e=am&"e be"o+ uses t$e ersion o1 t$e <oin met$od +it$out any argument. As a re ie+3 t$e met$od ;+$en ca""ed +it$ no argument> causes t$e current"y running t$read to +ait unti" t$e t$read t$at ca""s t$is met$od 1inis$es e=ecution. class Print-ame.hread implements Kunnable { .hread thread" Print-ame.hread$String name% { thread = new .hread$this0 name%" thread&start$%" } public #oid run$% { String name = thread&get-ame$%" for $int i = '" i < 3''" i((% { S)stem&out&print$name%" } } } class .est.hread { public static #oid main$String args !% { Print-ame.hread pnt3 = new Print-ame.hread$=,=%" Print-ame.hread pnt4 = new Print-ame.hread$=E=%" Print-ame.hread pnt> = new Print-ame.hread$=6=%" Print-ame.hread pnt? = new Print-ame.hread$=D=%" S)stem&out&println$=Kunning threads&&&=%" tr) { pnt3&thread&8oin$%" pnt4&thread&8oin$%" pnt>&thread&8oin$%" pnt?&thread&8oin$%" } catch $Bnterrupted<2ception ie% { } S)stem&out&println$=Wn.hreads /illed&=%" 99printed lastI } } 8ry running t$is &rogram yourse"1. 9$at $a e you noticedD 8$roug$ t$e <oin met$od ca""s3 +e are assured t$at t$e "ast statement is e=ecuted at t$e "ast &art. )ere is a sam&"e out&ut o1 running t$e code' Running t$reads... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA############################## ############################################################4D#4D #4D#4D#4#4#4#4#4#4D#DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD4444 4444444444444444444444444444444444444444444444444444444444444444 4444444444444444444444 8$reads ,i""ed. 7o+3 comment out t$e tryCcatch b"oc, +$ere t$e Boin met$od +as in o,ed. Is t$ere any di11erence in t$e &rogram out&utD

Introduction to Programming II

Page 126

J.E.D.I.

&.5 -)nchroniBation
%o 1ar3 youH e seen e=am&"es o1 t$reads t$at are running concurrent"y but are inde&endent o1 eac$ ot$er. 8$at is3 t$reads run at t$eir o+n &ace +it$out concern 1or t$e status and acti ities o1 t$e ot$er concurrent"y running t$reads. In t$is instances3 eac$ t$read do not re-uire any outside resources or met$ods and as a resu"t3 does not need to communicate +it$ ot$er t$reads. In many interesting situations3 $o+e er3 concurrent"y running t$reads may re-uire outside resources or met$ods. 8$us3 t$ere is a need to communicate +it$ ot$er concurrent"y running t$reads to ,no+ t$ere status and acti ities. A &o&u"ar e=am&"e on t$is scenario is t$e ProducerC4onsumer &rob"em. 8$e &rob"em in o" es t+o main obBects3 t$e &roducer and t$e consumer. 8$e +or, o1 t$e &roducer is to generate a"ues or streams o1 data t$at t$e consumer in turn +ou"d recei e or consume.

&.5.1 An 8ns)nchroniBed %5a*ple


Fet us 1irst consider a sim&"e code t$at sim&"y &rints out a se-uence o1 strings in a &articu"ar order. )ere is t$e &rogram. class .woStrings { static #oid print$String str30 String str4% { S)stem&out&print$str3%" tr) { .hread&sleep$C''%" } catch $Bnterrupted<2ception ie% { } S)stem&out&println$str4%" } } class PrintStrings.hread implements Kunnable { .hread thread" String str30 str4" PrintStrings.hread$String str30 String str4% { this&str3 = str3" this&str4 = str4" thread = new .hread$this%" thread&start$%" } public #oid run$% { .woStrings&print$str30 str4%" } } class .est.hread { public static #oid main$String args !% { new PrintStrings.hread$=Hello =0 =there&=%" new PrintStrings.hread$=How are =0 =)ou5=%" new PrintStrings.hread$=.han/ )ou =0 =#er) muchI=%" } } 8$e &rogram is e=&ected to &rint out t$e t+o arguments o1 t$e Runnab"e obBects consecuti e"y. 8$e &rob"em3 $o+e er3 is t$e in ocation o1 t$e sleep met$od causes ot$er t$reads to be e=ecuted +$en some ot$er t$read is not yet 1inis$ed +it$ t$e e=ecution o1 t$e print met$od o1 t$e ,woStrings c"ass. )ere is a sam&"e out&ut. Hello How are .han/ )ou there&
Introduction to Programming II Page 126

J.E.D.I.

)ou5 #er) muchI In t$is run3 t$e t$ree t$reads got to $a e t$eir 1irst string argument &rinted be1ore $a ing t$eir second argument &rinted. 8$is resu"ts in a cry&tic out&ut. Actua""y3 t$e e=am&"e $ere doesnHt &ose a ery serious &rob"em but 1or ot$er a&&"ications3 t$is may cause some e=ce&tions or &rob"ems to occur.

&.5.2 ?oc#ing an Object


8o assure t$at on"y one t$read gets to access a &articu"ar met$od3 Ja a a""o+s t$e "oc,ing o1 an obBect inc"uding its met$ods +it$ t$e use o1 monitors. 8$e obBect enters t$e im&"icit monitor +$en t$e obBectHs sync$roni*ed met$od is in o,ed. Once an obBect is in t$e monitor3 t$e monitor ma,es sure t$at no ot$er t$read accesses t$e same obBect. As a conse-uence3 t$is ensures t$at on"y one t$read at a time gets to e=ecute t$e met$od o1 t$e obBect. !or sync$roni*ing a met$od3 t$e synchroni5ed ,ey+ord can be &re1i=ed to t$e $eader o1 t$e met$od de1inition. In t$e case t$at you cannot modi1y t$e source code o1 t$e met$od3 you can sync$roni*e t$e obBect o1 +$ic$ t$e met$od is a member o1. 8$e synta= 1or sync$roni*ing an obBect is as 1o""o+s' s)nchroni:ed $<ob8ect>% { 99statements to be s)nchroni:ed } 9it$ t$is3 t$e obBectHs met$ods can on"y be in o,ed by one t$read at a time.

&.5.3 ;irst -)nchroniBed %5a*ple


)ere no+ is t$e modi1ied code +$erein t$e print met$od o1 t$e ,woStrings c"ass is no+ sync$roni*ed. class .woStrings { s)nchroni:ed static #oid print$String str30 String str4% { S)stem&out&print$str3%" tr) { .hread&sleep$C''%" } catch $Bnterrupted<2ception ie% { } S)stem&out&println$str4%" } } class PrintStrings.hread implements Kunnable { .hread thread" String str30 str4" PrintStrings.hread$String str30 String str4% { this&str3 = str3" this&str4 = str4" thread = new .hread$this%" thread&start$%" } public #oid run$% { .woStrings&print$str30 str4%"
Introduction to Programming II Page 12/

J.E.D.I.

class .est.hread { public static #oid main$String args !% { new PrintStrings.hread$=Hello =0 =there&=%" new PrintStrings.hread$=How are =0 =)ou5=%" new PrintStrings.hread$=.han/ )ou =0 =#er) muchI=%" } } 8$e &rogram no+ &roduces t$e correct statements. Hello there& How are )ou5 .han/ )ou #er) muchI

&.5.4 -econd -)nchroniBed %5a*ple


)ere is sti"" anot$er ersion o1 t$e &receding code. Again3 t$e print met$od $ere o1 t$e ,woStrings c"ass is no+ sync$roni*ed. #ut3 instead o1 a&&"ying t$e synchroni5ed ,ey+ord to a met$od3 it is a&&"ied to an obBect instead. class .woStrings { static #oid print$String str30 String str4% { S)stem&out&print$str3%" tr) { .hread&sleep$C''%" } catch $Bnterrupted<2ception ie% { } S)stem&out&println$str4%" } } class PrintStrings.hread implements Kunnable { .hread thread" String str30 str4" .woStrings ts" PrintStrings.hread$String str30 String str40 .woStrings ts% { this&str3 = str3" this&str4 = str4" this&ts = ts" thread = new .hread$this%" thread&start$%" } public #oid run$% { s)nchroni:ed $ts% { ts&print$str30 str4%" } } } class .est.hread { public static #oid main$String args !% { .woStrings ts = new .woStrings$%" new PrintStrings.hread$=Hello =0 =there&=0 ts%" new PrintStrings.hread$=How are =0 =)ou5=0 ts%" new PrintStrings.hread$=.han/ )ou =0 =#er) muchI=0 ts%"
Introduction to Programming II Page 12?

J.E.D.I.

8$is &rogram a"so out&uts t$e correct statements.

Introduction to Programming II

Page 1.0

J.E.D.I.

&.

(nterthread Co**unication

In t$is section3 youH"" "earn about t$e basic met$ods used to a""o+ t$reads to communicate +it$ ot$er concurrent"y running t$reads. Methods +or (nterthread Co**unication public final #oid wait$% 4auses t$is t$read to +ait unti" some ot$er t$read ca""s t$e notify or notify/ll met$od on t$is obBect. May t$ro+ InterruptedException. public final #oid notif)$% 9a,es u& a t$read t$at ca""ed t$e wait met$od on t$e same obBect. public final #oid notif),ll$% 9a,es u& a"" t$reads t$at ca""ed t$e wait met$od on t$e same obBect.
,a!le A;: 0ethods for Interthread -ommunication

!or a c"earer understanding o1 t$ese met$ods3 "et us consider t$e +aiterCcustomer scenario. In a restaurant scenario3 t$e +aiter waits unti" a customer enters t$e &"ace instead o1 continua""y as,ing &eo&"e i1 t$ey +ant to order or need anyt$ing. 9$en a customer comes in3 t$is signi1ies t$e customerHs interest in ordering 1ood 1rom t$e restaurant. In a +ay3 t$e customer by entering t$e restaurant notifies t$e +aiter t$at $e is need o1 $is ser ice. )o+e er3 it is not a"+ays t$e case t$at t$e customer is immediate"y ready +it$ $is order. It +ou"d be annoying i1 t$e +aiter continua""y as,s t$e customer i1 $eHs ready +it$ $is order e ery once in a +$i"e. Instead3 t$e +aiter waits unti" t$e customer notifies $im t$at $eHs ready. Once t$e customer 1inis$ed gi ing $is orders3 it +ou"d be annoying 1or $im to continua""y nag t$e +aiter i1 $eHs order is ready. 7orma""y3 a customer +ou"d +ait unti" t$e +aiter notifies $im and ser es t$e 1ood. Obser e t$at in t$is scenario3 a &arty t$at +aits on"y +a,es u& once t$e ot$er &arty noti1ies $im. 8$e same is true 1or t$reads.

Introduction to Programming II

Page 1.1

J.E.D.I.

Figure I.A: Kaiter%customer scenario

&. .1 "roducer-Consu*er %5a*ple


8$e 1o""o+ing e=am&"e is an im&"ementation o1 t$e ProducerC4onsumer &rob"em. A c"ass +$ic$ &ro ides t$e met$ods 1or generating and consuming an integer a"ue is se&arated 1rom t$e Producer and t$e 4onsumer t$read c"asses. class SharedData { int data" s)nchroni:ed #oid set$int #alue% { S)stem&out&println$=Yenerate = ( #alue%" data = #alue" } s)nchroni:ed int get$% { S)stem&out&println$=Yet = ( data%" return data" } } class Producer implements Kunnable { SharedData sd" Producer$SharedData sd% { this&sd = sd" new .hread$this0 =Producer=%&start$%" } public #oid run$% { for $int i = '" i < 3'" i((% {
Introduction to Programming II Page 1.2

J.E.D.I.

sd&set$$int%$1ath&random$%*3''%%"

class 6onsumer implements Kunnable { SharedData sd" 6onsumer$SharedData sd% { this&sd = sd" new .hread$this0 =6onsumer=%&start$%" } public #oid run$% { for $int i = '" i < 3' " i((% { sd&get$%" } } } class .estProducer6onsumer { public static #oid main$String args !% throws <2ception { SharedData sd = new SharedData$%" new Producer$sd%" new 6onsumer$sd%" } } )ere is a sam&"e out&ut o1 t$e &rogram. Yenerate Yenerate Yenerate Yenerate Yet SC Yenerate Yet 4> Yenerate Yet ?M Yenerate Yet >C Yenerate Yet >M Yenerate Yet OC Yet OC Yet OC Yenerate Yet >C Yet >C O ?C C4 SC 4> ?M >C >M OC

>C

8$is is not +$at +e +anted t$e &rogram to do. !or e ery a"ue &roduced by t$e &roducer3 +e e=&ect t$e consumer to get eac$ a"ue. )ere is t$e out&ut +e e=&ect instead. Yenerate Yet TS Yenerate Yet 4C Yenerate Yet >? Yenerate TS 4C >? O?
Page 1..

Introduction to Programming II

J.E.D.I.

Yet O? Yenerate Yet ?O Yenerate Yet 4M Yenerate Yet 4S Yenerate Yet OS Yenerate Yet SC Yenerate Yet >O Yenerate Yet ?S

?O 4M 4S OS SC >O ?S

8o 1i= t$e &rob"em +it$ t$is code3 +e use t$e met$ods 1or intert$read communication. 8$e 1o""o+ing im&"ementation o1 t$e ProducerC4onsumer &rob"em uses t$e met$ods 1or intert$read communication. class SharedData { int data" boolean #alueSet = false" s)nchroni:ed #oid set$int #alue% { if $#alueSet% { 99has 8ust produced a #alue tr) { wait$%" } catch $Bnterrupted<2ception ie% { } } S)stem&out&println$=Yenerate = ( #alue%" data = #alue" #alueSet = true" notif)$%" } s)nchroni:ed int get$% { if $I#alueSet% { 99producer hasnQt set a #alue )et tr) { wait$%" } catch $Bnterrupted<2ception ie% { } } S)stem&out&println$=Yet = ( data%" #alueSet = false" notif)$%" return data" } } 9* .he remaining part of the code doesnQt change& *9 class Producer implements Kunnable { SharedData sd" Producer$SharedData sd% { this&sd = sd" new .hread$this0 =Producer=%&start$%" } public #oid run$% { for $int i = '" i < 3'" i((% { sd&set$$int%$1ath&random$%*3''%%" } }
Introduction to Programming II Page 1.0

J.E.D.I.

} class 6onsumer implements Kunnable { SharedData sd" 6onsumer$SharedData sd% { this&sd = sd" new .hread$this0 =6onsumer=%&start$%" } public #oid run$% { for $int i = '" i < 3' " i((% { sd&get$%" } } } class .estProducer6onsumer { public static #oid main$String args !% throws <2ception { SharedData sd = new SharedData$%" new Producer$sd%" new 6onsumer$sd%" } }

Introduction to Programming II

Page 1.(

J.E.D.I.

&.! Concurrenc) 8tilities


9it$ t$e re"ease o1 J2%E(.03 ne+ t$reading contro" and concurrency 1eatures +ere added to Ja a. 8$ese ne+ 1eatures are 1ound in t$e <a#a.util.concurrent &ac,age. In t$is section3 t+o o1 t$ese concurrency 1eatures are e=&"ained.

&.!.1 1he %5ecutor (nter+ace


One o1 t$e most im&ortant en$ancement 1eatures 1or de e"o&ing mu"tit$readed a&&"ications is t$e Executor 1rame+or,. 8$e inter1ace is inc"uded in t$e <a#a.util.concurrent &ac,age. ObBects o1 t$is ty&e e=ecutes t$e $unna!le tas,s. 9it$out t$e use o1 t$is inter1ace3 +e e=ecute $unna!le tas,s by creating ,hread instances and ca""ing t$e start met$od o1 t$e t$e ,hread obBect. 8$e 1o""o+ing code demonstrates a +ay o1 doing t$is' new .hread$<aKunnable7b8ect>%&start$%" 9it$ t$e a ai"abi"ity o1 t$is ne+ inter1ace3 submitted $unna!le obBects are e=ecuted using its execute met$od as 1o""o+s' <an<2ecutor7b8ect>&e2ecute$<aKunnable7b8ect>%" 8$e ne+ Executor 1rame+or, is use1u" 1or mu"tit$readed a&&"ications. #ecause t$reads need stac, and $ea& s&ace3 t$read creation can be e=&ensi e. As a resu"t3 creation o1 se era" t$reads may cause out o1 memory errors. A +ay to get around t$is &rob"em is +it$ t$read &oo"ing. In t$read &oo"ing3 a t$read is -ueued to t$e &oo" a1ter it com&"etes its assigned tas, rat$er t$an dying or terminating. )o+e er3 im&"ementing a +e""C designed t$read &oo"ing sc$eme is not sim&"e. Anot$er &rob"em +as t$e di11icu"ty in cance""ation and s$utting do+n o1 t$reads. 8$e Executor 1rame+or, so" es t$ese &rob"ems by decou&"ing tas, submission 1rom t$e mec$anics o1 $o+ eac$ tas, +i"" be run3 inc"uding detai"s o1 t$read use3 sc$edu"ing and ot$ers. It is norma""y used instead o1 e=&"icit"y creating t$reads. Rat$er t$an creating a t$read and running it ia t$e start met$od 1or eac$ set o1 tas,3 it is more ad isab"e to use t$e 1o""o+ing code 1ragment instead' <2ecutor <e2ecutor-ame> = <an<2ecutor7b8ect>" <e2ecutor-ame>&e2ecute$new <Kunnable.as/3>$%%" <e2ecutor-ame>&e2ecute$new <Kunnable.as/4>$%%" &&& %ince Executor is an inter1ace3 it cannot be instantiated. 8o create an Executor obBect3 one $as to create a c"ass im&"ementing t$is inter1ace or use a 1actory met$od &ro ided in t$e Executors c"ass. 8$is c"ass is a"so a ai"ab"e in t$e same &ac,age as t$e Executor inter1ace. 8$e Executors c"ass a"so &ro ide 1actory met$ods 1or sim&"e t$read &oo" management. )ere is a summary o1 some o1 t$ese 1actory met$ods' Executors Factory Methods public static <2ecutorSer#ice new6ached.hreadPool$% 4reates a t$read &oo" t$at creates ne+ t$reads as needed3 but +i"" reuse &re ious"y constructed t$reads +$en t$ey are a ai"ab"e. An o er"oaded met$od3 +$ic$ a"so ta,es in a 8$read!actory obBect as an argument. public static <2ecutorSer#ice newAi2ed.hreadPool$int n.hreads%

Introduction to Programming II

Page 1.6

J.E.D.I.

4reates a t$read &oo" t$at reuses a 1i=ed set o1 t$reads o&erating o11 a s$ared unbounded -ueue. An o er"oaded met$od3 +$ic$ ta,es in a 8$read!actory obBect as an additiona" &arameter. public static Scheduled<2ecutorSer#ice newScheduled.hreadPool$int corePoolSi:e% 4reates a t$read &oo" t$at can sc$edu"e commands to run a1ter a gi en de"ay3 or to e=ecute &eriodica""y. An o er"oaded met$od3 +$ic$ ta,es in a 8$read!actory obBect as an additiona" &arameter. public static <2ecutorSer#ice newSingle.hread<2ecutor$% 4reates an E=ecutor t$at uses a sing"e +or,er t$read o&erating o11 an unbounded -ueue. An o er"oaded met$od3 +$ic$ a"so ta,es in a 8$read!actory obBect as an argument. public static Scheduled<2ecutorSer#ice newSingle.hreadScheduled<2ecutor$% 4reates a sing"eCt$readed e=ecutor t$at can sc$edu"e commands to run a1ter a gi en de"ay3 or to e=ecute &eriodica""y. An o er"oaded met$od3 +$ic$ a"so ta,es in a 8$read!actory obBect as an argument.
,a!le AA: Factory 0ethods of the Executors -lass

8$e $unna!le tas,s are e=ecuted and 1inis$ed under t$e contro" o1 t$e Executor inter1ace. 8o sto& t$e t$reads3 +e can sim&"y in o,e t$e shutdown met$od o1 t$e inter1ace as 1o""o+s' e2ecutor&shutdown$%"

&.!.2 1he Callable (nter+ace


Reca"" t$at t$ere are t+o +ays o1 creating t$reads. 9e can eit$er e=tend t$e ,hread c"ass or im&"ement t$e $unna!le inter1ace. In +$ic$e er tec$ni-ue used3 +e customi*e its 1unctiona"ity by o erriding t$e run met$od. 8$e met$od $as t$e 1o""o+ing signature' public #oid run$% 8$e dra+bac,s in creating t$reads t$is +ay are' 1. 8$e run met$od cannot return a resu"t since it $as #oid as its return ty&e. 2. %econd3 t$e run met$od re-uires you to $and"e c$ec,ed e=ce&tions +it$in t$is met$od since t$e o erriden met$od does not use any throws c"ause. 8$e -alla!le inter1ace is basica""y t$e same as t$e $unna!le inter1ace +it$out its dra+bac,s. 8o get t$e resu"t 1rom a $unna!le tas,3 +e $a e to use some e=terna" means o1 getting t$e resu"t. A common tec$ni-ue o1 +$ic$ is to use an instance ariab"e 1or storing t$e resu"t. 8$e ne=t code s$o+s $o+ t$is can be done. public 1)Kunnable implements Kunnable { pri#ate int result = '" public #oid run$% { &&& result = someXalue" } 9* .he result attribute is protected from changes from other codes accessing this class *9 public int getKesult$% { return result"
Introduction to Programming II Page 1.6

J.E.D.I.

9it$ t$e -alla!le inter1ace3 getting t$e resu"t is sim&"e as s$o+n in t$e ne=t e=am&"e. import <a#a.util.concurrent.L4 pu!lic class 0y-alla!le implements -alla!le M pu!lic Integer call() throws <a#a.io.I8Exception M ... return some>alue4 N N 8$e call met$od $as t$e 1o""o+ing signature' X call throws <2ception > $ere is a generic ty&e3 +$ic$ means t$at t$e return ty&e o1 ca"" can be o1 any re1erence ty&e. Jou +i"" "earn more about generic ty&es in a "atter c$a&ter. 8$ere are sti"" more concurrency 1eatures in J2%E(.0. P"ease re1er to t$e API documentation 1or a detai"ed discussion o1 t$ese ot$er 1eatures.

Introduction to Programming II

Page 1./

J.E.D.I.

/; <etwor$ing
Ja a a""o+s you to easi"y de e"o& a&&"ications t$at &er1orm a ariety o1 tas,s o er a net+or,. 8$is is one o1 Ja aHs strengt$ since it +as created +it$ t$e Internet in mind. #e1ore "earning about Ja a net+or,ing3 you +i"" 1irst be introduced to some basic conce&ts on net+or,ing. A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. E=&"ain basic net+or,ing conce&ts IP address &rotoco" &orts c"ientAser er &aradigm soc,ets 2. 4reate a&&"ications using t$e Ba a net+or,ing &ac,age Ser#erSoc'et Soc'et 0ulticastSoc'et :atagram1ac'et

1'.1 <asic Concepts on Cet3or#ing


As you &robab"y a"ready ,no+3 t$e Internet is a g"oba" net+or, o1 di11erent ty&es o1 com&uters t$at are connected in arious +ays. Des&ite o1 t$e di ersity o1 $ard+are and so1t+are connected toget$er3 it is &retty ama*ing $o+ t$e Internet remains 1unctiona". 8$is is &ossib"e because o1 communication standards de1ined and con1ormed to. 8$ese standards guarantee com&atibi"ity and re"iabi"ity o1 communication among a +ide range o1 systems o er t$e Internet. Fet us ta,e at "oo, at some o1 t$ese standards.

1'.1.1 (" Address


Eac$ o1 t$e com&uters connected to t$e Internet $a e a uni-ue IP address. 8$e IP address is "ogica""y simi"ar to t$e traditiona" mai"ing address in t$e sense t$at an address uni-ue"y identi1ies a &articu"ar obBect. It is a .2Cbit number used to uni-ue"y identi1y eac$ com&uter connected to t$e Internet. 1I;.1.1.1 is an e=am&"e o1 an IP address. 8$ey may a"so come in symbo"ic 1orms suc$ as docs.rinet.ru.

1'.1.2 "rotocol
%ince t$ere are many di11erent ty&es o1 communication t$at may occur o er t$e Internet3 t$ere must a"so be an e-ua" number o1 mec$anisms 1or $and"ing t$em. Eac$ ty&e o1 communication re-uires a s&eci1ic and uni-ue &rotoco". A &rotoco" re1ers to a set o1 ru"es and standards t$at de1ine a certain ty&e o1 Internet communication. It describes t$e 1ormat o1 data being sent o er t$e Internet3 a"ong +it$ $o+ and +$en it is sent. 8$e conce&t o1 a &rotoco" is actua""y not entire"y ne+ to us. 4onsider $o+ many times you $a e used t$is ty&e o1 con ersation'
Introduction to Programming II Page 1.?

J.E.D.I.

OHello.O OHello. Jood afternoon. 0ay I please spea' at GoanPO O8'ay& please wait for a while.O O,han's.O ... 8$is is a socia" &rotoco" used +$en in o" ed in a te"e&$one con ersation. 8$is ty&e o1 &rotoco"s gi es us con1idence and 1ami"iarity o1 ,no+ing +$at to do in certain situations. FetHs no+ ta,e a "oo, at some im&ortant &rotoco"s used o er t$e Internet. 9it$out a doubt3 )y&erte=t 8rans1er Protoco" ;)88P> is one o1 t$e most common"y used &rotoco". It is used to trans1er )8MF documents on t$e 9eb. 8$en3 t$ereHs !i"e 8rans1er Protoco"3 +$ic$ is more genera" com&ared to )88P and a""o+s you to trans1er binary 1i"es o er t$e Internet. #ot$ &rotoco"s $a e t$eir o+n set o1 ru"es and standards on $o+ data is trans1erred. Ja a &ro ides su&&ort 1or bot$ &rotoco"s.

1'.1.3 "orts
7o+3 &rotoco"s on"y ma,e sense +$en used in t$e conte=t o1 a ser ice. !or instance3 )88P &rotoco" is used +$en you are &ro iding 9eb content t$roug$ an )88P ser ice. Eac$ com&uter on t$e Internet can &ro ide a ariety o1 ser ices t$roug$ t$e arious &rotoco"s su&&orted. 8$e &rob"em3 $o+e er3 is t$at t$e ty&e o1 ser ice must be ,no+n be1ore in1ormation can be trans1erred. 8$is is +$ere &orts come in. A &ort is a 16Cbit number t$at identi1ies eac$ ser ice o11ered by a net+or, ser er. 8o use a &articu"ar ser ice and $ence3 estab"is$ a "ine o1 communication t$roug$ a s&eci1ic &rotoco"3 you need to connect to t$e a&&ro&riate &ort. Ports are associated +it$ a number and some o1 t$ese numbers are s&eci1ica""y associated +it$ a &articu"ar ty&e o1 ser ice. %uc$ &orts +it$ s&eci1ic ser ice assignments are ca""ed standard &orts. !or e=am&"e3 t$e !8P ser ice is "ocated on &ort 21 +$i"e t$e )88P ser ice is "ocated on &ort /0. I1 you +ant to &er1orm an !8P 1i"e trans1er3 you need to connect to &ort 21 o1 t$e $ost com&uter. 7o+3 a"" standard ser ice assignments are gi en &ort a"ues be"o+ 1020. Port a"ues abo e 1020 are a ai"ab"e 1or custom communication. In t$e case t$at a &ort a"ue abo e 1020 is a"ready in use by some custom communication3 you must "oo, 1or ot$er unused a"ues.

1'.1.4 1he ClientD-erver "aradig*


8$e 4"ientA%er er &aradigm is t$e basis 1or Ja a net+or,ing 1rame+or,. Ob ious"y3 t$is arrangement in o" es t+o maBor e"ements3 t$e c"ient and t$e ser er. 8$e c"ient re1ers to t$e mac$ine in need o1 some ty&e o1 in1ormation +$i"e t$e ser er is t$e mac$ine storing t$is in1ormation and +aiting to gi e it out. 8$e &aradigm describes a sim&"e scenario. 8y&ica""y3 a c"ient connects to a ser er and -ueries 1or certain in1ormation. 8$e ser er t$en considers t$e -uery and returns in1ormation a ai"ab"e on it to t$e c"ient.

Introduction to Programming II

Page 100

J.E.D.I.

Figure 1".1: -lientQSer#er model

1'.1.5 -oc#ets
8$e "ast genera" net+or,ing conce&t +eH"" be "oo,ing at be1ore &"unging into Ja a net+or,ing is regarding soc,ets. Most Ja a net+or, &rogramming uses a &articu"ar ty&e o1 net+or, communication ,no+n as soc,ets. A soc,et is a so1t+are abstraction 1or an in&ut or out&ut medium o1 communication. It is t$roug$ t$e use o1 soc,ets t$at Ja a &er1orms a"" o1 its "o+C"e e" net+or, communication. 8$ese are communication c$anne"s t$at enab"e you to trans1er data t$roug$ a &articu"ar &ort. In s$ort3 a soc,et re1ers to an end&oint 1or communication bet+een t+o mac$ines.

1'.2 1he ,ava Cet3or#ing "ac#age


8$e <a#a.net &ac,age &ro ides c"asses use1u" 1or de e"o&ing net+or,ing a&&"ications. !or a com&"ete "ist o1 net+or, c"asses and inter1aces3 &"ease re1er to t$e Ja a API documentation. 9eH"" Bust 1ocus on t$ese 1our c"asses' Ser#erSoc'et3 Soc'et3 0ulticastSoc'et3 and :atagram1ac'et c"asses.

1'.2.1 1he -erver-oc#et and the -oc#et Class


8$e Ser#erSoc'et 4"ass &ro ides t$e basic 1unctiona"ities o1 a ser er. 8$e 1o""o+ing tab"e describes t+o o1 t$e 1our constructors o1 t$e Ser#erSoc'et c"ass'

Introduction to Programming II

Page 101

J.E.D.I.

-erver-oc#et Constructors Ser#erSoc/et$int port% Instantiates a ser er t$at is bound to t$e s&eci1ied &ort. A &ort o1 0 assigns t$e ser er to any 1ree &ort. Ma=imum -ueue "engt$ 1or incoming connection is set to (0 by de1au"t. Ser#erSoc/et$int port0 int bac/log% Instantiates a ser er t$at is bound to t$e s&eci1ied &ort. Ma=imum -ueue "engt$ 1or incoming connection is is based on t$e !ac'log &arameter.
,a!le A2: Ser#erSoc'et constructors

)ere no+ are some o1 t$e c"assHs met$ods' -erver-oc#et Methods public Soc/et accept$% 4auses t$e ser er to +ait and "isten 1or c"ient connections3 t$en acce&t t$em. public #oid close$% 4"oses t$e ser er soc,et. 4"ients can no "onger connect to t$e ser er un"ess it is o&ened again. public int get;ocalPort$% Returns t$e &ort on +$ic$ t$e soc,et is bound to. public boolean is6losed$% Indicates +$et$er t$e soc,et is c"osed or not.
,a!le AD: Ser#erSoc'et methods

8$e succeeding e=am&"e is an im&"ementation o1 a sim&"e ser er3 +$ic$ sim&"y ec$oes t$e in1ormation sent by t$e c"ient. import 8a#a&net&*" import 8a#a&io&*" public class <choingSer#er { public static #oid main$String Ser#erSoc/et ser#er = null" Soc/et client" ! args% {

tr) { ser#er = new Ser#erSoc/et$34>?%" 9934>? is an unused port number } catch $B7<2ception ie% { S)stem&out&println$=6annot open soc/et&=%" S)stem&e2it$3%" } while$true% { tr) { client = ser#er&accept$%" 7utputStream client7ut = client&get7utputStream$%" PrintDriter pw = new PrintDriter$client7ut0 true%" BnputStream clientBn = client&getBnputStream$%" EufferedKeader br = new EufferedKeader$new
Introduction to Programming II Page 102

J.E.D.I.

BnputStreamKeader$clientBn%%" pw&println$br&read;ine$%%" } catch $B7<2ception ie% { }

9$i"e t$e %er er%oc,et c"ass im&"ements ser er soc,ets3 t$e %oc,et c"ass im&"ements a c"ient soc,et. 8$e Soc'et c"ass $as eig$t constructors3 t+o o1 +$ic$ are a"ready de&recated. Fet us $a e a -uic, "oo, at t+o o1 t$ese constructors. -oc#et Constructors Soc/et$String host0 int port% 4reates a c"ient soc,et t$at connects to t$e gi en &ort number on t$e s&eci1ied $ost. Soc/et$Bnet,ddress address0 int port% 4reates a c"ient soc,et t$at connects to t$e gi en &ort number at t$e s&eci1ied IP address.
,a!le AE: Soc'et constructors

)ere no+ are some o1 t$e c"assHs met$ods' -oc#et Methods public #oid close$% 4"oses t$e c"ient soc,et. public BnputStream getBnputStream$% Retrie es t$e in&ut stream associated +it$ t$is soc,et. public 7utputStream get7utputStream$% Retrie es t$e out&ut stream associated +it$ t$is soc,et. public Bnet,ddress getBnet,ddress$% Returns t$e IP address to +$ic$ t$is soc,et is connected public int getPort$% Returns t$e remote &ort to +$ic$ t$is soc,et is connected. public boolean is6losed$% Indicates +$et$er t$e soc,et is c"osed or not.
,a!le AF: Soc'et methods

8$e succeeding e=am&"e is an im&"ementation o1 a sim&"e c"ient3 +$ic$ sim&"y sends data to t$e ser er. import 8a#a&io&*" import 8a#a&net&*" public class 1)6lient { public static #oid main$String args !% { tr) { 99Soc/et client = new Soc/et$=3>>&'&'&3=0 34>?%"
Introduction to Programming II Page 10.

J.E.D.I.

Soc/et client = new Soc/et$Bnet,ddress&get;ocalHost$%0 34>?%" BnputStream clientBn = client&getBnputStream$%" 7utputStream client7ut = client&get7utputStream$%" PrintDriter pw = new PrintDriter$client7ut0 true%" EufferedKeader br = new EufferedKeader$new BnputStreamKeader$clientBn%%" EufferedKeader stdBn = new EufferedKeader$new BnputStreamKeader$S)stem&in%%" S)stem&out&println$=.)pe a message for the ser#er: =%" pw&println$stdBn&read;ine$%%" S)stem&out&println$=Ser#er message: =%" S)stem&out&println$br&read;ine$%%" pw&close$%" br&close$%" client&close$%" } catch $6onnect<2ception ce% { S)stem&out&println$=6annot connect to the ser#er&=%" } catch $B7<2ception ie% { S)stem&out&println$=B97 <rror&=%" }

Running t$e EchoingSer#er ma,es it ready 1or acce&ting message 1rom t$e c"ient. Once a c"ient3 suc$ as 0y-lient3 sends a message to t$e ser er3 t$e ser er ec$oes t$e message bac, to t$e c"ient. )ereHs a sam&"e run o1 0y-lient once EchoingSer#er $as been started' .)pe a message for the ser#er: first message to ser#er Ser#er message: first message to ser#er

Introduction to Programming II

Page 100

J.E.D.I.

1'.2.2 1he Multicast-oc#et and the Datagra*"ac#et Class


8$e 0ulticastSoc'et c"ass is use1u" 1or a&&"ications t$at im&"ement grou& communication. IP addresses 1or a mu"ticast grou& "ies +it$in t$e range 220.0.0.0 to 2.?.2((.2((.2((. )o+e er3 t$e address 220.0.0.0 is reser ed and s$ou"d not be used. 8$is c"ass $as t$ree constructors but +eH"" Bust consider one o1 t$ese constructors. Multicast-oc#et Constructors 1ulticastSoc/et$int port% 4reates a mu"ticast soc,et bound to t$e gi en &ort number.
,a!le AH: 0ulticastSoc'et constructor

8$e 1o""o+ing tab"e gi es t$e descri&tion o1 some 0ulticastSoc'et met$ods.

Multicast-oc#et Methods public #oid 8oinYroup$Bnet,ddress mcastaddr% Join a mu"ticast grou& on t$e s&eci1ied address. public #oid lea#eYroup$Bnet,ddress mcastaddr% Fea e a mu"ticast grou& on t$e s&eci1ied address. public #oid send$DatagramPac/et p% An in$erited met$od 1rom t$e :atagramSoc'et c"ass. %ends p 1rom t$is soc,et.
,a!le AI: 0ulticastSoc'et methods

#e1ore one can send a message to a grou&3 one s$ou"d 1irst be a member o1 t$e mu"ticast grou& by using t$e <oinJroup met$od. A member can no+ send messages t$roug$ t$e send met$od. Once youHre done ta",ing +it$ t$e grou&3 you can use t$e lea#eJroup met$od to re"in-uis$ your members$i&. #e1ore "oo,ing at an e=am&"e o1 using t$e 0ulticastSoc'et c"ass3 "etHs 1irst $a e a -uic, "oo, at t$e :atagram1ac'et c"ass. Obser e t$at in t$e send met$od o1 t$e
Introduction to Programming II Page 10(

J.E.D.I.

0ulticastSoc'et c"ass3 t$e re-uired &arameter is a :atagram1ac'et obBect. 8$us3 +e need to understand t$is ty&e o1 obBects be1ore using t$e send met$od. 8$e :atagram1ac'et c"ass is used to de"i er data t$roug$ a connection"ess &rotoco" suc$ as a mu"ticast. A &rob"em +it$ t$is is t$at t$e de"i ery o1 &ac,ets is not guaranteed. Fet us no+ consider t+o o1 its si= constructors. Datagra*"ac#et Constructors DatagramPac/et$b)te ! buf0 int length% 4onstructs a datagram &ac,et 1or recei ing &ac,ets +it$ a "engt$ length. length s$ou"d be "ess t$an or e-ua" to t$e si*e o1 t$e bu11er !uf. DatagramPac/et$b)te ! buf0 int length0 Bnet,ddress address0 int port% 4onstructs a datagram &ac,et 1or sending &ac,ets +it$ a "engt$ length to t$e s&eci1ied &ort number on t$e s&eci1ied $ost.
,a!le 2": :atagram1ac'et constructors

)ere are some interesting met$ods o1 t$e :atagram1ac'et c"ass. Datagra*"ac#et Methods public b)te ! getData$% Returns t$e bu11er in +$ic$ data $as been stored. public Bnet,ddress get,ddress$% Returns t$e IP address o1 t$e mac$ine +$ere t$e &ac,et is being sent to or +as recei ed 1rom. public int get;ength$% Returns t$e "engt$ o1 data being sent or recei ed. public int getPort$% Returns t$e &ort number on t$e remote $ost +$ere t$e &ac,et is being sent to or +as recei ed 1rom.
,a!le 21: :atagram1ac'et methods

Our mu"ticast e=am&"e a"so consists o1 t+o c"asses3 a ser er and a c"ient. 8$e ser er recei es messages 1rom t$e c"ient and &rints out t$ese messages. )ere is t$e ser er c"ass. import 8a#a&net&*" public class 6hatSer#er { public static #oid main$String args !% throws <2ception { 1ulticastSoc/et ser#er = new 1ulticastSoc/et$34>?%" Bnet,ddress group = Bnet,ddress&getE)-ame$=4>?&C&S&T=%" 99getE)-ame L returns BP address of the gi#en host ser#er&8oinYroup$group%" boolean infinite = true" 9* Ser#er continuall) recei#es data and prints them *9 while$infinite% { b)te buf ! = new b)te 3'4?!" DatagramPac/et data = new DatagramPac/et$buf0 buf&length%" ser#er&recei#e$data%"
Introduction to Programming II Page 106

J.E.D.I.

} ser#er&close$%"

String msg = new String$data&getData$%%&trim$%" S)stem&out&println$msg%"

Introduction to Programming II

Page 106

J.E.D.I.

)ere is t$e c"ient c"ass. import 8a#a&net&*" import 8a#a&io&*" public class 6hat6lient { public static #oid main$String args !% throws <2ception { 1ulticastSoc/et chat = new 1ulticastSoc/et$34>?%" Bnet,ddress group = Bnet,ddress&getE)-ame$=4>?&C&S&T=%" chat&8oinYroup$group%" String msg = ==" S)stem&out&println$=.)pe a message for the ser#er:=%" EufferedKeader br = new EufferedKeader$new BnputStreamKeader$S)stem&in%%" msg = br&read;ine$%" DatagramPac/et data = new DatagramPac/et$msg&getE)tes$%0 '0 msg&length$%0 group0 34>?%" chat&send$data%" chat&close$%" } } )ere is a sam&"e run o1 -hatSer#er and -hat-lient c"ass3 assuming t$at 4$at%er er +as e=ecuted be1ore running t$e c"ient c"ass' /* Executing ChatServer makes it ready to accept messages from clients */ /* Running ChatClient simply passes message to the server and then terminates */ .)pe a message for the ser#er: first chat message to ser#er /* ChatServer receives message from client and prints this message */ first chat message to ser#er /* Running ChatClient again */ .)pe a message for the ser#er: second chat message to ser#er /* ChatServer receives message from client and prints this message */ second chat message to ser#er

Introduction to Programming II

Page 10/

J.E.D.I.

// A""&ets
11.1 Objectives
A&&"ets are one o1 t$e most interesting 1eatures in Ja a. 8$is re1ers to &rograms you run o er ia a +eb bro+ser. Jou +i"" "earn about creating a&&"ets in t$is "esson. A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. De1ine +$at an a&&"et is 2. 4reate your o+n a&&"ets .. E=&"ain t$e a&&"et "i1e cyc"e init start stop destroy paint showStatus Met$ods 1or &"aying an audio c"i&

0. 2se ot$er a&&"et met$ods

(. 2se t$e a&&"et $tm" tag

11.2 Creating Applets


An a&&"et is a s&ecia" ty&e o1 Ba a &rogram t$at is e=ecuted ia t$e Internet. It is ty&ica""y run on a +eb bro+ser suc$ as 7etsca&e 7a igator3 Mo*i""a3 or Microso1t Internet E=&"orer. )o+e er3 com&ared to norma" Ja a a&&"ications3 a&&"ets are not a""o+ed access to t$e com&uter on +$ic$ t$ey are being run 1or security reasons. 8$is ma,es a&&"ets -uite restricted com&ared to Ja a a&&"ications. In t$is modu"e3 you +i"" "earn about creating a&&"ets using t$e A98.

11.2.1 7ello 4orld Applet


8$e /pplet c"ass is a subc"ass o1 t$e 1anel c"ass de1ined in t$e A98. 8$e best +ay to understand $o+ to create an a&&"et is t$roug$ e=am&"es. %o3 $ere is a sim&"e a&&"et t$at dis&"ays I)e""o +or"dGI. import 8a#a&awt&*" import 8a#a&applet&*" 9* insert this part in the html code <applet code==,ppletDemo= width=>'' height=3''> <9applet> *9

Introduction to Programming II

Page 10?

J.E.D.I.

public class ,ppletDemo e2tends ,pplet { public #oid paint$Yraphics g% { g&drawString$=Hello worldI=0 O'0 4C%" } } A1ter com&i"ation3 try running t$is e=am&"e using t$e <a#a command. 9$at $a&&ensD Remember t$at a&&"ets are s&ecia" Ja a a&&"ications. 8$ey are not e=ecuted using t$e <a#a command. Instead3 t$e a&&"et is run on a +eb bro+ser or using t$e a&&"et ie+er. 8o o&en t$e a&&"et t$roug$ a +eb bro+ser3 sim&"y o&en t$e )8MF document in +$ic$ t$e a&&"et is embedded using t$e a&&"et )8MF tag ;t$e commented out code in t$e )e""o 9or"d e=am&"e>. Anot$er +ay o1 running an a&&"et is t$roug$ t$e a&&"et ie+er command. %im&"y 1o""o+ t$is synta=' applet#iewer <8a#a filename> !or e=am&"e3 to run t$e gi en a&&"et e=am&"e3 use' applet#iewer ,ppletDemo&8a#a 8$e )8MF tag in t$e gi en e=am&"e indicates t$at an a&&"et be created +it$ a +idt$ o1 .00 &i=e"s and a $eig$t o1 100 &i=e"s. 8$en3 t$e dra+%tring met$od dra+s t$e I)e""o +or"dGI string at t$e &i=e" &osition ;/032(> counting do+n t$en rig$t.

Figure 11.1: /pplet example

9$en creating an a&&"et3 it is necessary to e=tend t$e /pplet c"ass. As mentioned &re ious"y3 t$e c"ass is 1ound in t$e <a#a.applet &ac,age. )ence3 im&orting t$e <a#a.applet &ac,age is a must. A"so3 it +as mentioned be1ore t$at t$e /pplet c"ass is a subc"ass o1 t$e 1anel c"ass. 8$is im&"ies t$at some met$ods o1 t$e A&&"et c"ass are 1ound in t$e 1anel c"ass. 8o access met$ods or 1ie"ds in t$e 1anel c"ass or ot$er ancestor c"asses3 it is necessary to im&ort t$e <a#a.awt &ac,age.

11.3 Applet Methods


8$is section discusses a&&"et met$ods youH"" 1ind use1u".

11.3.1 1he Applet ?i+e C)cle


Instead o1 starting e=ecution at t$e main met$od "i,e in ty&ica" Ja a a&&"ications3 t$e
Introduction to Programming II Page 1(0

J.E.D.I.

bro+ser or t$e a&&"et ie+er interacts +it$ t$e a&&"et t$roug$ t$e 1o""o+ing met$ods' 1. init() init is t$e 1irst met$od ca""ed. It is in o,ed e=act"y once +$en t$e a&&"et is "oaded. ;. start() A1ter t$e in o,ing t$e init met$od3 start is t$e ne=t met$od ca""ed. It is in o,ed e erytime t$e a&&"etHs )8MF document is dis&"ayed. E=ecution resumes +it$ t$is met$od +$en t$e a&&"et is redis&"ayed. A. stop() 9$en t$e +eb bro+ser "ea es t$e a&&"etHs )8MF document3 t$is met$od is ca""ed to in1orm t$e a&&"et t$at it s$ou"d sto& its e=ecution. 2. destroy() 8$is met$od is ca""ed +$en t$e a&&"et needs to be remo ed 1rom t$e memory com&"ete"y. 8$e stop met$od is a"+ays ca""ed be1ore t$is met$od is in o,ed.

Introduction to Programming II

Page 1(1

J.E.D.I.

9$en creating a&&"ets3 at "east some o1 t$ese met$ods are o erriden. 8$e 1o""o+ing a&&"et e=am&"e o errides t$ese met$ods. import 8a#a&applet&*" import 8a#a&awt&*" 9* <applet code==;ife6)cleDemo= width=>'' height=3''> <9applet> *9 class ;ife6)cleDemo e2tends ,pplet { String msg ===" public #oid init$% { msg (= =initiali:ing&&& =" repaint$%" } public #oid start$% { msg (= =starting&&& =" repaint$%" } public #oid stop$% { msg (= =stopping&&& =" repaint$%" } public #oid destro)$% { msg (= =preparing for unloading&&&=" repaint$%" } public #oid paint$Yraphics g% { g&drawString$msg0 3C0 3C%" } } 8$e 1o""o+ing is a sam&"e $tm" document embedded +it$ a Fi1e4yc"eDemo a&&"et. <H.1;> <.B.;<>;ife 6)cle Demo<9.B.;<> <applet code==;ife6)cleDemo= width=>'' height=3''> <9applet> <9H.1;>

Introduction to Programming II

Page 1(2

J.E.D.I.

11.3.2 1he paint Method


Anot$er im&ortant met$od is t$e paint met$od3 +$ic$ t$e /pplet c"ass in$erits 1rom its ancestor c"ass -omponent. It is in o,ed e erytime t$e a&&"etHs out&ut needs to be redra+n. An e=am&"e o1 suc$ an instance is +$en an a&&"et $idden by anot$er +indo+ is made isib"e again. 8$e met$od is usua""y o erriden +$en you +ant to customi*e $o+ your a&&"et s$ou"d "oo, "i,e. In t$e )e""o 9or"d e=am&"e3 t$e a&&"et $as t$e I)e""o +or"dGI string on t$e bac,ground a1ter $a ing o erriden t$e paint met$od.

11.3.3 1he sho3-tatus Method


8$e a&&"et $as a status +indo+3 +$ic$ in1orms you o1 +$at t$e a&&"et is current"y doing. I1 you +ant to out&ut to t$e status +indo+3 sim&"y in o,e t$e showStatus met$od. 8$e 1o""o+ing e=am&"e is t$e same as t$e )e""o 9or"d e=am&"e but +it$ an additiona" statements t$at modi1ies t$e content o1 t$e status +indo+. import 8a#a&awt&*" import 8a#a&applet&*" 9* <applet code==,ppletDemo= width=>'' height=3''> <9applet> *9 public class ,ppletDemo e2tends ,pplet { public #oid paint$Yraphics g% { g&drawString$=Hello worldI=0 O'0 4C%" showStatus$=.his is an important information&=%" } } )ere is a sam&"e out&ut'

Figure 11.;: showStatus() example

Introduction to Programming II

Page 1(.

J.E.D.I.

11.3.4 "la)ing Audio Clips


A&&"ets are a"so &ro ided +it$ met$ods t$at a""o+ you to &"ay audio 1i"es. P"aying audio c"i&s in an a&&"et in o" es t+o basic ste&s' 1. 5et t$e audio c"i& using t$e getAudio4"i& met$od. 2. 8o &"ay t$e audio c"i&3 use t$e &"ay or "oo& met$od on t$e audio c"i& obBect. play a""o+s you to &"ay t$e audio once +$ereas loop "oo&s on t$e audio c"i& and sto&s on"y +$en t$e stop met$od is ca""ed. 8$e ne=t e=am&"e continua""y &"ays an audio 1i"e unti" t$e a&&"etHs stop met$od is ca""ed. import 8a#a&awt&*" import 8a#a&applet&*" 9* <applet code==,udio,pplet= width=>'' height=3''> <9applet> *9 public class ,udio,pplet e2tends ,pplet { ,udio6lip ac" public #oid init$% { tr) { 9*audio clip is sa#ed in same director) as 8a#a code*9 9* space1usic was downloaded from 8a#a&sun&com *9 ac = get,udio6lip$get6odeEase$%0 =space1usic&au=%" ac&loop$%" } catch $<2ception e% { S)stem&out&println$e%" } } public #oid stop$% { ac&stop$%" } public #oid paint$Yraphics g% { g&drawString$=Pla)ing space musicI=0 O'0 4C%" } }

Introduction to Programming II

Page 1(0

J.E.D.I.

11.4 Applet 71M? 1ags


In t$e &receding e=am&"es3 youH e seen $o+ a&&"et )8MF tags are used in t$e )8MF document or t$e Ba a source code. 7o+3 youH"" be introduced to a more com&"ete ersion o1 t$e a&&"et )8MF tag. <,PP;<. 67D<E,S< = codebase@K;! 67D< = appletAile ,.; = alternate.e2t! -,1< = appletBnstance-ame! DBD.H = widthBnPi2els H<BYH. = heightBnPi2els ,;BY- = alignment! XSP,6< = #spaceBnPi2els! HSP,6< = hspaceBnPi2els! > <P,K,1 -,1< = parameter-ame3 X,;@< = parameterXalue3>! <P,K,1 -,1< = parameter-ame4 X,;@< = parameterXalue4>! &&& <P,K,1 -,1< = parameter-amen X,;@< = parameterXaluen>! H.1; that will be dsipla)ed in the absence of Ra#a! <9,PP;<.>

Introduction to Programming II

Page 1((

J.E.D.I.

Applet 71M? 1ag 2e)3ords 67D<E,S< Directory +$ere t$e a&&"et c"ass is "ocated. Re1ers to t$e )8MF documentHs directory by de1au"t. 67D< 7ame o1 t$e 1i"e containing t$e a&&"et code. 9it$ or +it$out t$e .<a#a or .class e=tension name. ,;. 8e=t dis&"ayed i1 t$e bro+ser understands a&&"et tags but cannot current"y e=ecute t$e a&&"et. May $a&&en i1 Ja a is disab"ed. -,1< 7ame o1 t$e a&&"et. 2sed to a""o+ ot$er a&&"ets to communicate +it$ t$is a&&"et by re1erring to it by its name. DBD.H0 H<BYH. 9idt$ and $eig$t o1 t$e a&&"et +indo+. %&eci1ied in &i=e"s. ,;BYA"ignment or &ositioning o1 t$e a&&"et. Eit$er I"e1tI3 Irig$tI3 Ito&I3 IbottomI3 Imidd"eI3 Ibase"ineI3 Ite=tto&I3 Iabsmidd"eI3 or IabsbottomI. De1au"t &"acement de&ends on t$e en ironment. Ito&I R to& o1 a&&"et a"igned +it$ ta""est item in t$e current "ine. IbottomI3 base"ine R bottom o1 a&&"et a"igned +it$ bottom o1 ot$er content in t$e current "ine. Imidd"eI C midd"e o1 a&&"et a"igned +it$ bottom o1 ot$er content in t$e current "ine. Ite=tto&I C to& o1 a&&"et a"igned +it$ to& o1 ta""est te=t in t$e current "ine. Iabsmidd"eI C midd"e o1 a&&"et a"igned +it$ current "ine. XSP,6<0 HSP,6< %&ace abo e and be"o+ ;V%PA4E> and on t$e sides ;)%PA4E> o1 t$e a&&"et. P,K,1 -,1<0 X,;@< 8o s&eci1y &arameters t$at can be &assed to a&&"etsQ a&&"ets can in o,e t$e get1arameter(String param3ame) met$od.
,a!le 2;: /pplet H,06 ,ags

2RF

ertica" midd"e o1 ot$er content in t$e

IabsbottomI C bottom o1 a&&"et a"igned +it$ bottom o1 ot$er content in t$e current "ine

8$e e=am&"e be"o+ demonstrates $o+ to access &arameter s&eci1ied at t$e )8MF tag. import 8a#a&awt&*" import 8a#a&applet&*" 9* <applet code==ParamDemo= width=>'' height=3''> <param name==m)Param= #alue==Hello worldI=> <9applet> *9

Introduction to Programming II

Page 1(6

J.E.D.I.

public class ParamDemo e2tends ,pplet { public #oid paint$Yraphics g% { g&drawString$getParameter$=m)Param=%0 O'0 4C%" } } 8$e out&ut o1 t$is &rogram is Bust t$e same as t$at o1 )e""o 9or"d a&&"et. )ereHs a screen s$ot o1 t$e e=&ected out&ut.

Figure 11.A: 1aram:emo Sample $un

Introduction to Programming II

Page 1(6

J.E.D.I.

/0 Ad(anced I=- %treams


12.1 Objectives
In a &re ious modu"e3 youH e "earned $o+ to get user in&ut and mani&u"ate 1i"es using streams. Jou +i"" no+ "earn more about streams and ot$er stream c"asses. A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. Enumerate t$e genera" stream ty&es 2. 2se t$e !i"e c"ass and its met$ods 4$aracter and #yte %treams In&ut and Out&ut %treams 7ode and !i"ter %treams .. 2se t$e di11erent In&utAOut&ut c"asses $eader Kriter InputStream 8utputStream 0. E=&"ain t$e conce&t o1 stream c$aining (. De1ine seria"i*ation 6. E=&"ain t$e use o1 t$e transient ,ey+ord 6. 9rite and read 1rom an obBect stream

12.2 .eneral -trea* 1)pes


12.2.1 Character and <)te -trea*s
As mentioned be1ore3 t$ere are genera""y t+o ty&es o1 streams3 t$e c$aracter and byte streams. Fet us Bust re ie+ t$e basic di11erence bet+een t$e t+o. #yte streams are 1i"e or de ice abstractions 1or binary data +$i"e c$aracter streams are 1or 2nicode c$aracters. 8$e InputStream c"ass is t$e abstract root c"ass o1 a"" in&ut byte streams +$ereas t$e 8utputStream c"ass is t$e abstract root c"ass o1 a"" out&ut byte streams. !or c$aracter streams3 t$e corres&onding su&erc"ass o1 a"" c"asses are t$e $eader and t$e Kriter c"ass3 res&ecti e"y. #ot$ c"asses are abstract c"asses 1or reading and +riting to c$aracter streams.

12.2.2 (nput and Output -trea*s


%treams are a"so categori*ed on +$et$er t$ey are used 1or reading or +riting to streams. A"t$oug$ it is a"ready -uite ob ious3 a""o+ me to de1ine t$ese ty&es o1 streams. Jou are a""o+ed to read 1rom in&ut streams but not +rite to t$em. On t$e ot$er $and3 you are a""o+ed to +rite to out&ut streams but not read 1rom t$em. 8$e InputStream c"ass and t$e $eader c"ass are t$e su&erc"asses o1 a"" in&ut streams. 8$e 8utputStream c"ass and t$e Kriter c"ass are t$e root c"asses o1 a"" out&ut streams. In&ut streams are a"so ,no+n as source streams since +e get in1ormation 1rom t$ese
Introduction to Programming II Page 1(/

J.E.D.I.

streams. Mean+$i"e3 out&ut streams are a"so ca""ed sin, streams.

12.2.3 Code and ;ilter -trea*s


7o+3 t$e <a#a.io &ac,age distinguis$es bet+een node and 1i"ter streams. A node stream is a stream +it$ t$e basic 1unctiona"ity o1 reading or +riting 1rom a s&eci1ic "ocation suc$ as a dis, or 1rom t$e net+or,. 8y&es o1 node streams inc"ude 1i"es3 memory and &i&es. !i"ter streams3 on t$e ot$er $and3 are "ayered onto node streams bet+een t$reads or &rocesses to &ro ide additiona" 1unctiona"ities not 1ound in t$e node stream by t$emse" es. Adding "ayers to a node stream is ca""ed stream c$aining. 8$e succeeding sections gi es an o er ie+ o1 t$e di11erent stream c"asses. !or a com&"ete "ist o1 t$ese c"asses3 &"ease re1er to Ja aHs API documentation.

Introduction to Programming II

Page 1(?

J.E.D.I.

12.3 1he ;ile Class


A"t$oug$ t$e File c"ass is not a stream c"ass3 it is im&ortant t$at +e study it since t$e stream c"asses are mani&u"ate 1i"es. 8$e c"ass is an abstract re&resentation o1 actua" 1i"es and directory &at$names. 8o instantiate a File obBect3 you can use t$e 1o""o+ing constructor' A ;ile Constructor Aile$String pathname% Instantiates a File obBect +it$ t$e s&eci1ied pathname as its 1i"ename. 8$e 1i"ename may eit$er be abso"ute ;i.e.3 containes t$e com&"ete &at$> or may consists o1 t$e 1i"ename itse"1 and is assumed to be contained in t$e current directory.
,a!le 2A: File constructor

8$e File c"ass &ro ides se era" met$ods 1or mani&u"ating 1i"es and directories. )ere are some o1 t$ese met$ods. ;ile Methods public String get-ame$% Returns t$e 1i"ename or t$e directory name o1 t$is File obBect. public boolean e2ists$% 8ests i1 a 1i"e or a directory e=ists. public long length$% Returns t$e si*e o1 t$e 1i"e. public long last1odified$% Returns t$e date in mi""iseconds +$en t$e 1i"e +as "ast modi1ied. public boolean canKead$% Returns true i1 itHs &ermissib"e to read 1rom t$e 1i"e. Ot$er+ise3 it returns 1a"se. public boolean canDrite$% Returns true i1 itHs &ermissib"e to +rite to t$e 1i"e. Ot$er+ise3 it returns 1a"se. public boolean isAile$% 8ests i1 t$is obBect is a 1i"e3 t$at is3 our norma" &erce&tion o1 +$at a 1i"e is ;not a directory>. public boolean isDirector)$% 8ests i1 t$is obBect is a directory. public String ! list$% Returns t$e "ist o1 1i"es and subdirectories +it$in t$is obBect. 8$is obBect s$ou"d be a directory. public #oid m/dir$% 4reates a directory denoted by t$is abstract &at$name. public #oid delete$%

Introduction to Programming II

Page 160

J.E.D.I.

;ile Methods Remo es t$e actua" 1i"e or directory re&resented by t$is File obBect.
,a!le 22: File methods

FetHs see $o+ t$ese met$ods +or, by trying out t$e 1o""o+ing e=am&"e' import 8a#a&io&*" public class AileBnfo6lass { public static #oid main$String args !% { String file-ame = args '!" Aile fn = new Aile$file-ame%" S)stem&out&println$=-ame: = ( fn&get-ame$%%" if $Ifn&e2ists$%% { S)stem&out&println$file-ame ( = does not e2ists&=%" 9* 6reate a temporar) director) instead& *9 S)stem&out&println$=6reating temp director)&&&=%" file-ame = =temp=" fn = new Aile$file-ame%" fn&m/dir$%" S)stem&out&println$file-ame ( $fn&e2ists$%5 =e2ists=: =does not e2ist=%%" S)stem&out&println$=Deleting temp director)&&&=%" fn&delete$%" S)stem&out&println$file-ame ( $fn&e2ists$%5 =e2ists=: =does not e2ist=%%" return" } S)stem&out&println$file-ame ( = is a = ( $fn&isAile$%5 =file&= :=director)&=%%" if $fn&isDirector)$%% { String content ! = fn&list$%" S)stem&out&println$=.he content of this director):=%" for $int i = '" i < content&length" i((% { S)stem&out&println$content i!%" } } if $Ifn&canKead$%% { S)stem&out&println$file-ame ( = is not readable&=%" return" } S)stem&out&println$file-ame ( = is = ( fn&length$% ( = b)tes long&=%" S)stem&out&println$file-ame ( = was last modified on = ( fn&last1odified$% ( =&=%" if $Ifn&canDrite$%% { S)stem&out&println$file-ame ( = is not writable&=%" } } } )ere is a sam&"e run o1 t$e FileInfo-lass' -ame: temp&t2t temp&t2t is a file& temp&t2t is >? b)tes long& temp&t2t was last modified on 33?M3C'?OM3TT& temp.txt $as contains t$e 1o""o+ing te=t'
Introduction to Programming II Page 161

J.E.D.I.

what a wonderful world 30 40 step

12.4 9eader Classes


8$is section describes c$aracter streams used 1or reading.

12.4.1 9eader Methods


8$e $eader c"ass consists o1 se era" met$ods 1or reading o1 c$aracters. )ere are some o1 t$e c"assHs met$ods' 9eader Methods public int read$L% throws B7<2ception An o er"oaded met$od3 +$ic$ $as t$ree ersions. Reads c$aracter;s>3 an entire c$aracter array or a &ortion o1 a c$aracter array. public int read$% C Reads a sing"e c$aracter. public int read$char ! cbuf%C Reads c$aracters and stores t$em in c$aracter array c!uf. public abstract int read$char ! cbuf0 int offset0 int length%C Reads u& to length number o1 c$aracters and stores t$em in c$aracter array c!uf starting at t$e s&eci1ied offset. public abstract #oid close$% throws B7<2ception 4"oses t$is stream. 4a""ing t$e ot$er $eader met$ods a1ter c"osing t$e stream +ou"d cause an I8Exception to occur. public #oid mar/$int read,head;imit% throws B7<2ception Mar,s t$e current &osition in t$e stream. A1ter mar,ing3 ca""s to reset;> +i"" attem&t to re&osition t$e stream to t$is &oint. 7ot a"" c$aracterCin&ut streams su&&ort t$is o&eration. public boolean mar/Supported$% Indicates +$et$er a stream su&&orts t$e mar, o&eration or not. 7ot su&&orted by de1au"t. %$ou"d be o eridden by subc"asses. public #oid reset$% throws B7<2ception Re&ositions t$e stream to t$e "ast mar,ed &osition.
,a!le 2D: $eader methods

12.4.2 Code 9eader Classes


8$e 1o""o+ing are some o1 t$e basic $eader c"asses' Code 9eader Classes AileKeader

Introduction to Programming II

Page 162

J.E.D.I.

Code 9eader Classes !or reading 1rom c$aracter 1i"es. 6har,rra)Keader Im&"ements a c$aracter bu11er t$at can be read 1rom. StringKeader !or reading 1rom a string source. PipedKeader 2sed in &airs ;+it$ a corres&onding 1ipedKriter> by t+o t$reads t$at +ant to communicate. One o1 t$ese t$reads reads c$aracters 1rom t$is source.
,a!le 2E: 3ode $eader -lasses

12.4.3 ;ilter 9eader Classes


8o add 1unctiona"ities to t$e basic $eader c"asses3 you can use t$e 1i"ter stream c"asses. )ere are some o1 t$ese c"asses' ;ilter 9eader Classes EufferedKeader A""o+s bu11ering o1 c$aracters in order to &ro ide 1or t$e e11icient reading o1 c$aracters3 arrays3 and "ines. AilterKeader !or reading 1i"tered c$aracter streams. BnputStreamKeader 4on erts read bytes to c$aracters. ;ine-umberKeader A subc"ass o1 t$e 9uffered$eader c"ass t$at is ab"e to ,ee& trac, o1 "ine numbers. Pushbac/Keader A subc"ass o1 t$e Filter$eader c"ass t$at a""o+s c$aracters to be &us$ed bac, or unread into t$e stream.
,a!le 2F: Filter $eader -lasses

Introduction to Programming II

Page 16.

J.E.D.I.

12.5 4riter Classes


8$is section describes c$aracter streams used 1or +riting.

12.5.1 4riter Methods


8$e Kriter c"ass consists o1 se era" met$ods 1or +riting o1 c$aracters. )ere are some o1 t$e c"assHs met$ods' 4riter Methods public #oid write$L% throws B7<2ception An o er"oaded met$od +it$ 1i e ersions' public #oid write$int c% R 9rites a sing"e c$aracter re&resented by t$e gi en integer a"ue. public #oid write$char ! cbuf% R 9rites t$e contents o1 t$e c$aracter array c!uf. public abstract #oid write$char ! cbuf0 int offset0 int length% R 9rites length number o1 c$aracters 1rom t$e c!uf array3 starting at t$e s&eci1ied offset. public #oid write$String str% R 9rites t$e string string. public #oid write$String str0 int offset0 int length% R 9rites length number o1 c$aracters 1rom t$e string str3 starting at t$e s&eci1ied offset. public abstract #oid close$% throws B7<2ception 4"oses t$is stream a1ter 1"us$ing any un+ritten c$aracters. In ocation o1 ot$er met$ods a1ter c"osing t$is stream +ou"d cause an I8Exception to occur. public abstract #oid flush$% !"us$es t$e stream ;i.e.3 c$aracters sa ed in t$e bu11er are immediate"y +ritten to t$e intended destination>.
,a!le 2H: Kriter methods

12.5.2 Code 4riter Classes


8$e 1o""o+ing are some o1 t$e basic Kriter c"asses' Code 4riter Classes AileDriter !or +riting c$aracters to a 1i"e. 6har,rra)Driter Im&"ements a c$aracter bu11er t$at can be +ritten to. StringDriter !or +riting to a string source. PipedDriter 2sed in &airs ;+it$ a corres&onding 1iped$eader> by t+o t$reads t$at +ant to communicate. One o1 t$ese t$reads +rites c$aracters to t$is stream.
,a!le 2I: 3ode Kriter classes

Introduction to Programming II

Page 160

J.E.D.I.

12.5.3 ;ilter 4riter Classes


8o add 1unctiona"ities to t$e basic Kriter c"asses3 you can use t$e 1i"ter stream c"asses. )ere are some o1 t$ese c"asses' ;ilter 4riter Classes EufferedDriter A""o+s bu11ering o1 c$aracters in order to &ro ide 1or t$e e11icient +riting o1 c$aracters3 arrays3 and "ines. AilterDriter !or +riting 1i"tered c$aracter streams. 7utputStreamDriter Encodes c$aracters +ritten to it into bytes. PrintDriter Prints 1ormatted re&resentations o1 obBects to a te=tCout&ut stream.
,a!le D": Filter Kriter classes

12.

A <asic 9eaderD4riter %5a*ple

8$e succeeding e=am&"e uses t$e File$eader and t$e FileKriter c"ass. In t$is e=am&"e3 t$e &rogram reads 1rom a 1i"e s&eci1ied by t$e user and co&ies t$e content o1 t$is 1i"e to anot$er 1i"e. import 8a#a&io&*" class 6op)Aile { #oid cop)$String input0 String output% { AileKeader reader" AileDriter writer" int data" tr) { reader = new AileKeader$input%" writer = new AileDriter$output%" while $$data = reader&read$%% I= L3% { writer&write$data%" } reader&close$%" writer&close$%" } catch $B7<2ception ie% { ie&printStac/.race$%" } } public static #oid main$String args !% { String inputAile = args '!" String outputAile = args 3!" 6op)Aile cf = new 6op)Aile$%" cf&cop)$inputAile0 outputAile%" }

8ry out t$e &rogram yourse"1 and obser e +$at $a&&ens to t$e 1i"es mani&u"ated.
Introduction to Programming II Page 16(

J.E.D.I.

2sing temp.txt 1rom our &re ious e=am&"e3 $ereHs t$e resu"t +$en +e &ass temp.txt as t$e inputFile and temp;.txt as t$e outputFile'

Figure 1;.1: Sample output for -opyFile

Introduction to Programming II

Page 166

J.E.D.I.

12.! Modi+ied 9eaderD4riter %5a*ple


8$e succeeding e=am&"e is simi"ar to t$e &re ious e=am&"e but is more e11icient. Instead o1 reading and +riting to t$e stream one at a time3 c$aracters read are 1irst stored in a bu11er be1ore +riting c$aracters "ine &er "ine. 8$e &rogram uses t$e tec$ni-ue o1 stream c$aining +$erein t$e File$eader and t$e FileKriter c"ass are decorated +it$ t$e 9uffered$eader and t$e 9ufferedKriter c"ass3 res&ecti e"y. import 8a#a&io&*" class 6op)Aile { #oid cop)$String input0 String output% { EufferedKeader reader" EufferedDriter writer" String data" tr) { reader = new EufferedKeader$new AileKeader$input%%" writer = new EufferedDriter$new AileDriter$output%%" while $$data = reader&read;ine$%% I= null% { writer&write$data0 '0 data&length$%%" } reader&close$%" writer&close$%" } catch $B7<2ception ie% { ie&printStac/.race$%" } } public static #oid main$String args !% { String inputAile = args '!" String outputAile = args 3!" 6op)Aile cf = new 6op)Aile$%" cf&cop)$inputAile0 outputAile%" }

4om&are t$is code +it$ t$e &re ious one. 9$at is t$e resu"t o1 running t$is &rogramD )ereHs a sam&"e out&ut o1 t$is ersion o1 -opyFile.

Introduction to Programming II

Page 166

J.E.D.I. Figure 1;.;: Sample output for -opyFile

Introduction to Programming II

Page 16/

J.E.D.I.

12.$ (nput-trea* Classes


8$is section gi es an o er ie+ o1 t$e di11erent byte streams used 1or reading.

12.$.1 (nput-trea* Methods


8$e InputStream c"ass consists o1 se era" met$ods 1or reading o1 bytes. )ere are some o1 t$e c"assHs met$ods' (nput-trea* Methods public int read$L% throws B7<2ception An o er"oaded met$od3 +$ic$ a"so $as t$ree Reads bytes. ersions "i,e t$at o1 t$e $eader c"ass.

public abstract int read$% C Reads t$e ne=t byte o1 data 1rom t$is stream. public int read$b)te ! bEuf%C Reads some number o1 bytes and stores t$em in t$e !9uf byte array. public abstract int read$char ! cbuf0 int offset0 int length%C Reads u& to length number o1 bytes and stores t$em in t$e byte array !9uf starting at t$e s&eci1ied offset. public abstract #oid close$% throws B7<2ception 4"oses t$is stream. 4a""ing t$e ot$er InputStream met$ods a1ter c"osing t$e stream +ou"d cause an I8Exception to occur. public #oid mar/$int read,head;imit% throws B7<2ception Mar,s t$e current &osition in t$e stream. A1ter mar,ing3 ca""s to reset;> +i"" attem&t to re&osition t$e stream to t$is &oint. 7ot a"" byteCin&ut streams su&&ort t$is o&eration. public boolean mar/Supported$% Indicates +$et$er a stream su&&orts t$e mar, and reset o&eration. 7ot su&&orted by de1au"t. %$ou"d be o eridden by subc"asses. public #oid reset$% throws B7<2ception Re&ositions t$e stream to t$e "ast mar,ed &osition.
,a!le D1: InputStream methods

12.$.2 Code (nput-trea* Classes


8$e 1o""o+ing are some o1 t$e basic InputStream c"asses' Code (nput-trea* Classes AileBnputStream !or reading bytes 1rom a 1i"e. Euffered,rra)BnputStream Im&"ements a bu11er t$at contains bytes3 +$ic$ may be read 1rom t$e stream. PipedBnputStream

Introduction to Programming II

Page 16?

J.E.D.I.

Code (nput-trea* Classes %$ou"d be connected to a 1iped8utputStream. 8$ese streams are ty&ica""y used by t+o t$reads +$erein one o1 t$ese t$reads reads data 1rom t$is source +$i"e t$e ot$er t$read +rites to t$e corres&onding 1iped8utputStream.
,a!le D;: 3ode InputStream classes

12.$.3 ;ilter (nput-trea* Classes


8o add 1unctiona"ities to t$e basic InputStream c"asses3 you can use t$e 1i"ter stream c"asses. )ere are some o1 t$ese c"asses' ;ilter (nput-trea* Classes EufferedBnputStream A subc"ass o1 FilterInputStream t$at a""o+s bu11ering o1 in&ut in order to &ro ide 1or t$e e11icient reading o1 bytes. AilterBnputStream !or reading 1i"tered byte streams3 +$ic$ may trans1orm t$e basic source o1 data a"ong t$e +ay and &ro ide additiona" 1unctiona"ities. 7b8ectBnputStream 2sed 1or obBect seria"i*ation. Deseria"i*es obBects and &rimiti e data &re ious"y +ritten using an 8!<ect8utputStream. DataBnputStream A subc"ass o1 FilterInputStream t$at "ets an a&&"ication read Ja a &rimiti e data 1rom an under"ying in&ut stream in a mac$ineCinde&endent +ay. ;ine-umberBnputStream A subc"ass o1 FilterInputStream t$at a""o+s trac,ing o1 t$e current "ine number. Pushbac/BnputStream A subc"ass o1 t$e FilterInputStream c"ass t$at a""o+s bytes to be &us$ed bac, or unread into t$e stream.
,a!le DA: Filter InputStream classes

Introduction to Programming II

Page 160

J.E.D.I.

12.& Output-trea* Classes


8$is section gi es an o er ie+ o1 t$e di11erent byte streams used 1or +riting.

12.&.1 Output-trea* Methods


8$e 8utputStream c"ass consists o1 se era" met$ods 1or +riting o1 bytes. )ere are some o1 t$e c"assHs met$ods' Output-trea* Methods public #oid write$L% throws B7<2ception An o er"oaded met$od 1or +riting bytes to t$e stream. It $as t$ree ersions' public abstract #oid write$int b% R 9rites t$e s&eci1ied byte out&ut stream. a"ue ! to t$is

public #oid write$b)te ! bEuf% R 9rites t$e contents o1 t$e byte array !9uf to t$is stream. public #oid write$b)te ! bEuf0 int offset0 int length% R 9rites length number o1 bytes 1rom t$e !9uf array to t$is stream3 starting at t$e s&eci1ied offset to t$is stream. public abstract #oid close$% throws B7<2ception 4"oses t$is stream and re"eases any system resources associated +it$ t$is stream. In ocation o1 ot$er met$ods a1ter ca""ing t$is met$od +ou"d cause an I8Exception to occur. public abstract #oid flush$% !"us$es t$e stream ;i.e.3 bytes sa ed in t$e bu11er are immediate"y +ritten to t$e intended destination>.
,a!le D2: 8utputStream methods

12.&.2 Code Output-trea* Classes


8$e 1o""o+ing are some o1 t$e basic 8utputStream c"asses' Code Output-trea* Classes Aile7utputStream !or +riting bytes to a 1i"e. Euffered,rra)7utputStream Im&"ements a bu11er t$at contains bytes3 +$ic$ may be +ritten to t$e stream. Piped7utputStream %$ou"d be connected to a 1ipedInputStream. 8$ese streams are ty&ica""y used by t+o t$reads +$erein one o1 t$ese t$reads +rites data to t$is stream +$i"e t$e ot$er t$read reads 1rom t$e corres&onding 1ipedInputStream.
,a!le DD: 3ode 8utputStream classes

Introduction to Programming II

Page 161

J.E.D.I.

12.&.3 ;ilter Output-trea* Classes


8o add 1unctiona"ities to t$e basic 8utputStream c"asses3 you can use t$e 1i"ter stream c"asses. )ere are some o1 t$ese c"asses' ;ilter Output-trea* Classes Euffered7utputStream A subc"ass o1 Filter8utputStream t$at a""o+s bu11ering o1 out&ut in order to &ro ide 1or t$e e11icient +riting o1 bytes. A""o+s +riting o1 bytes to t$e under"ying out&ut stream +it$out necessari"y causing a ca"" to t$e under"ying system 1or eac$ byte +ritten. Ailter7utputStream !or +riting 1i"tered byte streams3 +$ic$ may trans1orm t$e basic source o1 data a"ong t$e +ay and &ro ide additiona" 1unctiona"ities. 7b8ect7utputStream 2sed 1or obBect seria"i*ation. %eria"i*es obBects and &rimiti e data to an 8utputStream. Data7utputStream A subc"ass o1 Filter8utputStream t$at "ets an a&&"ication +rite Ja a &rimiti e data to an under"ying out&ut stream in a mac$ineCinde&endent +ay. PrintStream A subc"ass o1 Filter8utputStream t$at &ro ides ca&abi"ity 1or &rinting re&resentations o1 arious data a"ues con enient"y.
,a!le DE: Filter 8utputStream classes

Introduction to Programming II

Page 162

J.E.D.I.

12.1' A <asic (nput-trea*DOutput-trea* %5a*ple


8$e 1o""o+ing e=am&"e uses t$e FileInputStream and t$e File8utputStream c"ass to read 1rom a s&eci1ied 1i"e and co&ies t$e content o1 t$is 1i"e to anot$er 1i"e. import 8a#a&io&*" class 6op)Aile { #oid cop)$String input0 String output% { AileBnputStream inputStr" Aile7utputStream outputStr" int data" tr) { inputStr = new AileBnputStream$input%" outputStr = new Aile7utputStream$output%" while $$data = inputStr&read$%% I= L3% { outputStr&write$data%" } inputStr&close$%" outputStr&close$%" } catch $B7<2ception ie% { ie&printStac/.race$%" } } public static #oid main$String args !% { String inputAile = args '!" String outputAile = args 3!" 6op)Aile cf = new 6op)Aile$%" cf&cop)$inputAile0 outputAile%" }

Passing tempo.txt and tempo;.txt as arguments3 $ereHs a sam&"e run o1 t$is code'

Figure 1;.A: Sample output for -opyFile

Introduction to Programming II

Page 16.

J.E.D.I.

12.11 Modi+ied (nput-trea*DOutput-trea* %5a*ple


8$e ne=t e=am&"e is uses t$e 1ush!ac'InputStream FileInputStream obBect and t$e 1rintStream c"ass. import 8a#a&io&*" class 6op)Aile { #oid cop)$String input% { Pushbac/BnputStream inputStr" PrintStream outputStr" int data" tr) { inputStr = new Pushbac/BnputStream$new AileBnputStream$input%%" outputStr = new PrintStream$S)stem&out%" while $$data = inputStr&read$%% I= L3% { outputStr&println$=read data: = ( $char% data%" inputStr&unread$data%" data = inputStr&read$%" outputStr&println$=unread data: = ( $char% data%" } inputStr&close$%" outputStr&close$%" } catch $B7<2ception ie% { ie&printStac/.race$%" } } public static #oid main$String args !% { String inputAile = args '!" 6op)Aile cf = new 6op)Aile$%" cf&cop)$inputAile%" } c"ass t$at decorates a

8est t$is code on a 1i"e containing a 1e+ "ines or c$aracters. %ay3 +e $a e a 1i"e named tempo.txt containing t$e 1o""o+ing te=t' one 3 two Passing tempo.txt to t$e code generates t$e 1o""o+ing out&ut' read data: o unread data: read data: n unread data: read data: e unread data: read data: unread data: read data: 3 unread data: read data: unread data: read data: o n e

Introduction to Programming II

Page 160

J.E.D.I.

unread data: read data: t unread data: t read data: w unread data: w read data: o unread data: o

Introduction to Programming II

Page 16(

J.E.D.I.

12.12 -erialiBation
8$e Ja a Virtua" Mac$ine ;JVM> su&&orts t$e abi"ity to read or +rite an obBect to a stream. 8$is ca&abi"ity is ca""ed seria"i*ation3 t$e &rocess o1 I1"atteningI an obBect so t$at it can be sa ed to some &ermanent storage or &assed to anot$er obBect ia t$e 8utputStream c"ass. 9$en +riting an obBect3 it is im&ortant t$at its state be +ritten in a seria"i*ed 1orm suc$ t$at t$e obBect can be reconstructed as it is being read. %a ing an obBect to some ty&e o1 &ermanent storage is ,no+n as &ersistence. 8$e streams used 1or deseria"i*ing and seria"i*ing are t$e 8!<ectInputStream and t$e 8!<ect8utputStream c"asses3 res&ecti e"y. 8o a""o+ an obBect to be seria"i*ab"e ;i.e.3 can be sa ed and retrie ed>3 its c"ass s$ou"d im&"ement t$e Seriali5a!le inter1ace. 8$e c"ass s$ou"d a"so &ro ide a de1au"t constructor or a constructor +it$ no arguments. One nice t$ing about seria"i*abi"ity is t$at it is in$erited3 +$ic$ means t$at +e donHt $a e to im&"ement Seriali5a!le on e ery c"ass. 8$is means "ess +or, 1or &rogrammers. Jou can Bust im&"ement Seriali5a!le once a"ong t$e c"ass $eirarc$y.

12.12.1 1he transient 2e)3ord


9$en an obBect is seria"i*ed3 on"y t$e obBectHs data are &reser ed. Met$ods and constructors are not &art o1 t$e seria"i*ed stream. 8$ere are some obBects t$oug$ t$at are not seria"i*ab"e because t$e data t$ey re&resent constant"y c$anges. %ome e=am&"es o1 suc$ obBects are FileInputStream and ,hread obBects. A 3otSeriali5a!leException is t$ro+n i1 t$e seria"i*ation o&eration 1ai"s 1or some reason. Do not des&air t$oug$. A c"ass containing a nonCseria"i*ab"e obBect can sti"" be seria"i*ed i1 t$e re1erence to t$is nonCseria"i*ab"e obBect is mar,ed +it$ t$e transient ,ey+ord. 4onsider t$e 1o""o+ing e=am&"e' class 1)6lass implements Seriali:able { transient .hread thread" 99tr) remo#ing transient int data" 9* some other data *9 } 8$e transient ,ey+ord &re ents t$e data 1rom being seria"i*ed. Instantiating obBects 1rom t$is c"ass can no+ be +ritten to an 8utputStream.

12.12.2 -erialiBation/ 4riting an Object -trea*


8o +rite an obBect to a stream3 you need to use t$e 8!<ect8utputStream c"ass and its write8!<ect met$od. 8$e write8!<ect met$od $as t$e 1o""o+ing signature' public final #oid write7b8ect$7b8ect ob8% throws B7<2ception +$ere o!< is t$e obBect to be +ritten to t$e stream. 8$e e=am&"e be"o+ +rites a 9oolean obBect to an 8!<ect8utputStream. 8$e 9oolean c"ass im&"ements t$e Seriali5a!le inter1ace. 8$us3 obBects instantiated 1rom t$is c"ass can be +ritten to and read 1rom a stream.

Introduction to Programming II

Page 166

J.E.D.I.

import 8a#a&io&*" public class Seriali:eEoolean { Seriali:eEoolean$% { Eoolean booleanData = new Eoolean$=true=%" tr) { Aile7utputStream fos = new Aile7utputStream$=boolean&ser=%" 7b8ect7utputStream oos = new 7b8ect7utputStream$fos%" oos&write7b8ect$booleanData%" oos&close$%" } catch $B7<2ception ie% { ie&printStac/.race$%" }

public static #oid main$String args !% { Seriali:eEoolean sb = new Seriali:eEoolean$%" }

12.12.3 DeserialiBation/ 9eading an Object -trea*


8o read an obBect 1rom a stream3 you need to use t$e 8!<ectInputStream c"ass and its read8!<ect met$od. 8$e read8!<ect met$od $as t$e 1o""o+ing signature' public final 7b8ect read7b8ect$% throws B7<2ception0 6lass-otAound<2ception +$ere o!< is t$e obBect to be read 1rom t$e stream. 8$e 8!<ect ty&e returned s$ou"d be ty&ecasted to t$e a&&ro&riate c"ass name be1ore met$ods on t$at c"ass can be e=ecuted. 8$e e=am&"e be"o+ reads a 9oolean obBect 1rom an 8!<ectInputStream. 8$is is a continuation o1 t$e &re ious e=am&"e on seria"i*ation. import 8a#a&io&*" public class @nseriali:eEoolean { @nseriali:eEoolean$% { Eoolean booleanData = null" tr) { AileBnputStream fis = new AileBnputStream$=boolean&ser=%" 7b8ectBnputStream ois = new 7b8ectBnputStream$fis%" booleanData = $Eoolean% ois&read7b8ect$%" ois&close$%" } catch $<2ception e% { e&printStac/.race$%" } S)stem&out&println$=@nseriali:ed Eoolean from = ( =boolean&ser=%" S)stem&out&println$=Eoolean data: = ( booleanData%" S)stem&out&println$=6ompare data with true: = ( booleanData&eJuals$new Eoolean$=true=%%%"

public static #oid main$String args !% { @nseriali:eEoolean usb = new @nseriali:eEoolean$%" }

Introduction to Programming II

Page 166

J.E.D.I.

8$e 1o""o+ing is t$e e=&ected out&ut o1 Unseriali5e9oolean' @nseriali:ed Eoolean from boolean&ser Eoolean data: true 6ompare data with true: true

Introduction to Programming II

Page 16/

J.E.D.I.

/4 An Introduction to 8enerics
13.1 Objectives
Ja aHs "atest re"ease &ro ides t$e biggest "ea& 1or+ard in Ja a &rogramming com&ared to its ot$er ersions. It inc"udes signi1icant e=tensions to t$e source "anguage synta=. 8$e most isib"e o1 +$ic$ is t$e addition o1 generic ty&es. 8$is modu"e introduces you to t$e basic conce&ts re"ated to Ja a generic ty&es. A1ter com&"eting t$is "esson3 you s$ou"d be ab"e to' 1. Enumerate t$e bene1its o1 generic ty&es 2. Dec"are a generic c"ass .. 2se constrained generics 0. Dec"are generic met$ods (. 2se Ja a co""ections +it$ generic ty&es

13.2 4h) .enerics6


One o1 t$e most signi1icant causes o1 bugs in t$e Ja a &rogramming "anguage is t$e need to continua""y ty&ecast or do+ncast e=&ressions to more s&eci1ic data ty&es t$an t$eir static ty&es. !or e=am&"e3 an /rray6ist obBect a""o+s us to add any re1erence ty&e obBect to t$e "ist but +$en +e retrie e t$ese e"ements3 +e need to ty&ecast t$e obBects to a s&eci1ic re1erence ty&e a&&ro&riate 1or our needs. Do+ncasting is a &otentia" $ots&ot 1or -lass-astException. It a"so ma,es our codes +ordier3 t$us3 "ess readab"e. Moreo er3 do+ncasting a"so e11ecti e"y destroys t$e bene1its o1 a strong"y ty&ed "anguage since it nu""i1ies t$e sa1ety t$at accom&anies bui"tCin ty&e c$ec,ing. 8$e main goa" o1 adding generics to Ja a is to so" e t$is &rob"em. 5eneric ty&es a""o+ a sing"e c"ass to +or, +it$ a +ide ariety o1 ty&es. It is a natura" +ay o1 e"iminating t$e need 1or casting. FetHs 1irst consider an /rray6ist obBect and see $o+ generic ty&es +ou"d $e"& in im&ro ing our code. As you a"ready ,no+3 an /rray6ist obBect $as t$e abi"ity to store e"ements o1 any re1erence ty&e to t$is "ist. An /rray6ist instance3 $o+e er3 $as a"+ays 1orced us to do+ncast t$e obBects +e retrie e out o1 t$e "ist. 4onsider t$e 1o""o+ing statement' String m)String = (String) m),rra);ist&get$'%" 8$e generic ersion o1 t$e /rray6ist c"ass is designed to +or, nati e"y +it$ any ty&e o1 c"ass. At t$e same3 it a"so &reser es t$e bene1its o1 ty&e c$ec,ing. 9e can do a+ay +it$ t$e need o1 $a ing to ty&ecast t$e e"ement +e get 1rom t$e "ist and $a e t$e 1o""o+ing statement instead o1 t$e &re ious one' String m)String = m),rra);ist&get$'%" A"t$oug$ do+ncasting +as a"ready remo ed3 t$is doesnHt mean t$at you cou"d assign anyt$ing to t$e return a"ue o1 t$e get met$od and do a+ay +it$ ty&ecasting a"toget$er. I1 you assign anyt$ing e"se besides a String to t$e out&ut o1 t$e get met$od3 you +ou"d
Introduction to Programming II Page 16?

J.E.D.I.

encounter a com&i"e time ty&e mismatc$ suc$ as t$is message' found: 8a#a&lang&String reJuired: 8a#a&lang&Bnteger Bnteger data = m),rra);ist&get$'%" !or you to Bust $a e an idea $o+ generic ty&es are used be1ore digging into more detai"s3 consider t$e 1o""o+ing code 1ragment' ,rra);ist <String> gen,rr;ist = new ,rra);ist <String>$%" gen,rr;ist&add$=, generic string=%" String m)String = gen,rr;ist&get$'%" RoptionPane&show1essageDialog$this0 m)String%" #ro+sing t$roug$ t$e statements3 you &robab"y obser ed t$e +ord <String a&&earing immediate"y a1ter t$e re1erence data ty&e /rray6ist. Jou can inter&ret t$e 1irst statement as instantiating a generic ersion o1 t$e /rray6ist c"ass and t$is generic ersion contains obBects o1 ty&e String. gen/rr6ist is bound to String ty&e. )ence3 binding an Integer or some ot$er nonC%tring ty&e to t$e resu"t o1 t$e get 1unction +ou"d be i""ega". 8$e ne=t statement is i""ega". int m)Bnt = gen,rr;ist&get$%"

13.3 Declaring a .eneric Class


!or t$e &re ious code 1ragment to +or,3 +e s$ou"d $a e de1ined a generic ersion o1 t$e /rray6ist c"ass. !ortunate"y3 Ja aHs ne+est ersion a"ready &ro ides users +it$ generic ersions o1 a"" Ja a -ollection c"asses. In t$is section3 youH"" "earn $o+ to dec"are your o+n generic c"ass. Instead o1 $a ing a "engt$y discussion on $o+ to dec"are a generic c"ass3 you are gi en a sim&"e generic c"ass e=am&"e to "earn 1rom. class EasicYeneric <,> { pri#ate , data" public EasicYeneric$, data% { this&data = data" } public , getData$% { return data" } } public class YenSample { public String method$String input% { String data3 = input" EasicYeneric <String> basicYeneric = new EasicYeneric <String>$data3%" String data4 = basicYeneric&getData$%" return data4" } public Bnteger method$int input% { Bnteger data3 = new Bnteger$input%" EasicYeneric <Bnteger> basicYeneric = new EasicYeneric <Bnteger>$data3%" Bnteger data4 = basicYeneric&getData$%" return data4"
Introduction to Programming II Page 1/0

J.E.D.I.

} public static #oid main$String args !% { YenSample sample = new YenSample$%" S)stem&out&println$sample&method$=Some generic data=%%" S)stem&out&println$sample&method$34>?%%" }

Running t$e code gi es t$e 1o""o+ing e=&ected out&ut' Some generic data 34>? 7o+ "etHs go t$roug$ t$e &arts o1 t$e code t$at use t$e synta= 1or generic ty&es. !or t$e dec"aration o1 t$e 9asicJeneric c"ass3 class EasicYeneric <,> t$e c"ass name is 1o""o+ed by a &air o1 brac,ets enc"osing t$e ca&ita" "etter /' </ . 8$is is ca""ed a ty&e &arameter. 2se o1 t$ese brac,ets indicates t$at t$e c"ass dec"ared is a generic c"ass. 8$is means t$at t$e c"ass does not +or, +it$ any s&eci1ic re1erence ty&e. 8$en3 obser e t$at a 1ie"d o1 t$e c"ass +as dec"ared to be o1 ty&e /. pri#ate , data" 8$is dec"aration s&eci1ies t$at t$e 1ie"d data is o1 generic ty&e3 de&ending on t$e data ty&e t$at t$e 9asicJeneric obBect +as designed to +or, +it$. 9$en dec"aring an instance o1 t$e c"ass3 you must s&eci1y t$e re1erence ty&e +it$ +$ic$ you +ant to +or, +it$. EasicYeneric <String> basicYeneric = new EasicYeneric <String>$data3%" 8$e <String synta= a1ter t$e dec"aration 9asicJeneric s&eci1ies t$at t$is instance o1 t$e c"ass is going to +or, +it$ ariab"es o1 ty&e String. Jou can a"so +or, +it$ ariab"es o1 ty&e Integer or any ot$er re1erence ty&e. 8o +or, +it$ an Integer3 t$e code 1ragment $ad t$e 1o""o+ing statement' EasicYeneric <Bnteger> basicYeneric = new EasicYeneric <Bnteger>$data3%" Jou can &robab"y inter&ret t$e rest o1 t$e code on your o+n. 4onsider t$e dec"aration o1 t$e get:ata met$od. public , getData$% { return data" } 8$e met$od get:ata returns a a"ue o1 ty&e /3 a generic ty&e. 8$is doesnHt mean t$at t$e met$od +i"" not $a e a runtime data ty&e3 or e en at com&i"e time. A1ter you dec"are an obBect o1 ty&e 9asicJeneric3 / is bound to a s&eci1ic data ty&e. 8$is instance +i"" act as i1 it +ere dec"ared to $a e t$is s&eci1ic data ty&e and t$is ty&e on"y 1rom t$e ery beginning. In t$e gi en code3 t+o instances o1 t$e 9asicJeneric c"ass +ere created.
Introduction to Programming II Page 1/1

J.E.D.I.

EasicYeneric <String> basicYeneric = new EasicYeneric String data4 = basicYeneric&getData$%" EasicYeneric <Bnteger> basicYeneric = new EasicYeneric Bnteger data4 = basicYeneric&getData$%"

String!$data3%"

"nteger!$data3%"

7otice t$at instantiation o1 a generic c"ass is Bust simi"ar to instantiating a norma" c"ass e=ce&t t$at t$e s&eci1ic data ty&e enc"osed in < succeed t$e constructor name. 8$is additiona" in1ormation indicates t$e ty&e o1 data youH"" be +or,ing +it$ 1or t$is &articu"ar instance o1 t$e 9asicJeneric c"ass. A1ter instantiation3 you can no+ access members o1 t$e c"ass ia t$e instance. 8$ere is no "onger any need to ty&ecast t$e return a"ue o1 t$e get:ata met$od since it $as a"ready been decided t$at it +i"" +or, +it$ a s&eci1ic re1erence data ty&e.

13.3.1 E"ri*itiveE ?i*itation


A "imitation to generic ty&es in Ja a is t$ey are restricted to re1erence ty&es and +onHt +or, +it$ &rimiti e data ty&es. !or e=am&"e3 t$e 1o""o+ing statement +ou"d be i""ega" since int is a &rimiti e data ty&e. EasicYeneric <int> basicYeneric = new EasicYeneric <int>$data3%" JouH"" $a e to +ra& &rimiti e ty&es 1irst be1ore using t$em as arguments to a generic ty&e.

13.3.2 Co*piling .enerics


8o com&i"e Ja a source codes +it$ generic ty&es using JD@ ; . 1.(.0>3 use t$e 1o""o+ing synta=' 8a#ac L#ersion Lsource =3&C= Lsourcepath src Ld classes src9Swap6lass&8a#a +$ere src re1ers to t$e "ocation o1 t$e Ba a source code +$i"e class re1ers to t$e "ocation +$ere t$e c"ass 1i"e +i"" be stored. )ereHs an e=am&"e' 8a#ac L#ersion Lsource =3&C= Lsourcepath c:Wtemp Ld c:Wtemp c:9temp9Swap6lass&8a#a

Introduction to Programming II

Page 1/2

J.E.D.I.

13.4 Constrained .enerics


In t$e &receding e=am&"e gi en3 t$e ty&e &arameters o1 c"ass 9asicJeneric can be o1 any re1erence data ty&e. 8$ere are cases3 $o+e er3 +$erein you +ant to restrict t$e &otentia" ty&e instantiations o1 a generic c"ass. Ja a a"so a""o+s us to "imit t$e set o1 &ossib"e ty&e arguments to subty&es o1 a gi en ty&e bound. !or e=am&"e3 +e may +ant to de1ine a generic Scroll1ane c"ass t$at is a tem&"ate 1or an ordinary -ontainer decorated +it$ scro""ing 1unctiona"ity. 8$e runtime ty&e o1 an instance o1 t$is c"ass +i"" o1ten be a subc"ass o1 -ontainer3 but t$e static or genera" ty&e is sim&"y -ontainer. 8o "imit t$e ty&e instantiations o1 a c"ass3 +e use t$e extends ,ey+ord 1o""o+ed by t$e c"ass bounding t$e generic ty&e as &art o1 t$e ty&e &arameter. 8$e 1o""o+ing e=am&"e "imits ty&e instantiation o1 t$e Scroll1ane c"ass to subty&es o1 t$e -ontainer c"ass. class ScrollPane <1)Pane e2tends 6ontainer> { &&& } class .estScrollPane { public static #oid main$String args !% { ScrollPane <Panel> scrollPane3 = new ScrollPane <Panel>$%" 99 .he ne2t statement is illegal ScrollPane <Eutton> scrollPane4 = new ScrollPane <Eutton>$%" } } Instantiation o1 scroll1ane1 is a"id since 1anel is a subc"ass o1 t$e -ontainer c"ass +$ereas creation o1 scroll1ane; +ou"d cause a com&i"e time error since 9utton is not a subc"ass o1 -ontainer. 2sing constrained generics gi e us added static ty&e c$ec,ing. As a resu"t3 +e are guaranteed t$at e ery instantiation o1 t$e generic ty&e ad$eres to t$e bounds +e assigned to it. %ince +e are assured t$at e ery ty&e instantiation is a subc"ass o1 t$e assigned bound3 +e can sa1e"y ca"" any met$ods 1ound in t$e obBectHs static ty&e. I1 +e $adnHt &"ace any e=&"icit bound on t$e &arameter3 t$e de1au"t bound is 8!<ect. 8$is means t$at +e canHt in o,e met$ods on an instance o1 t$e bound t$at donHt a&&ear in t$e 8!<ect c"ass.

Introduction to Programming II

Page 1/.

J.E.D.I.

13.5 Declaring a .eneric Method


#esides dec"aring a generic c"ass3 Ja a a"so gi es us t$e &ri i"ege o1 dec"aring a generic met$od. 8$ese are ca""ed &o"ymor&$ic met$ods3 +$ic$ are de1ined to be met$ods &arameteri*ed by ty&e. Parameteri*ing met$ods are use1u" +$en +e +ant to &er1orm tas,s +$ere t$e ty&e de&endencies bet+een t$e arguments and return a"ue are natura""y generic3 but t$e generic nature doesnHt re"y on any c"assC"e e" ty&e in1ormation and +i"" c$ange 1rom met$od ca"" to met$od ca"". !or e=am&"e3 su&&ose +e +ant to add a ma'e met$od to an /rray6ist c"ass. 8$is static met$od +ou"d ta,e in a sing"e argument3 +$ic$ +ou"d be t$e so"e e"ement o1 t$e /rray6ist obBect. 8o ma,e our /rray6ist generic so as to accomodate any ty&e o1 e"ement3 t$e sing"e argument in t$e ma'e met$od s$ou"d $a e a generic ty&e as an argument and as a return ty&e. 8o dec"are generic ty&es at met$od "e e"3 consider t$e 1o""o+ing e=am&"e' class @tilities { 9* . implicitl) e2tends 7b8ect *9 public static <.> ,rra);ist<.> ma/e$. first% { return new ,rra);ist<.>$first%" } } Ja a a"so uses a ty&eCin1erence mec$anism to automatica""y in1er t$e ty&es o1 &o"ymor&$ic met$ods based on t$e ty&es o1 arguments. 8$is "essens +ordiness and com&"e=ity o1 a met$od in ocation. 8o construct a ne+ instance o1 /rray6ist<Integer 3 +e +ou"d sim&"y $a e t$e 1o""o+ing statement' @tilities&ma/e$Bnteger$'%%"

Introduction to Programming II

Page 1/0

J.E.D.I.

13.

,ava Collections and .enerics

A discussion o1 -ollection met$ods +as a"ready gi en in an ear"ier c$a&ter. )o+e er3 in JD@ (.03 t$ese met$ods +ere u&dated to acommodate 5eneric ty&es. 8$e 1o""o+ing tab"e gi es t$e JD@ (.0 e-ui a"ent o1 met$ods youH e studied ear"ier. Co&&ection Methods public boolean add$E o% Inserts s&eci1ied e"ement o to t$is co""ection. Returns true i1 o +as success1u""y added to t$e co""ection. public #oid clear$% Remo es a"" e"ements o1 t$is co""ection. public boolean remo#e$7b8ect o% Remo es a sing"e instance o1 t$e 8!<ect o 1rom t$is co""ection3 i1 it is &resent. Returns true i1 o +as 1ound and remo ed 1rom t$e co""ection. public boolean contains$7b8ect o% Returns true i1 t$is co""ection contains t$e 8!<ect o. public boolean is<mpt)$% Returns true i1 t$is co""ection does not contain any obBect or e"ement. public int si:e$% Returns t$e number o1 e"ements in t$is co""ection. public Bterator<E> iterator$% Returns an iterator t$at a""o+s us to go t$roug$ t$e contents o1 t$is co""ection. public boolean eJuals$7b8ect o% Returns true i1 t$e 8!<ect o is e-ua" to t$is co""ection. public int hash6ode$% Returns t$e $as$ code a"ue ;i.e.3 t$e ID> 1or t$is co""ection. %ame obBects or co""ections $a e t$e same $as$ code a"ue or ID.
,a!le DF: -ollection methods

)ere is a sam&"e code t$at uses t$e generic ersion o1 t$e 6in'ed6ist c"ass. import 8a#a&util&*" class ;in/ed;istDemo { public static #oid main$String args !% { ;in/ed;ist <Bnteger> list = new ;in/ed;ist <Bnteger>$%" list&add$new Bnteger$3%%" list&add$new Bnteger$4%%" list&add$new Bnteger$3%%" S)stem&out&println$list%" ;in/ed;ist <Bnteger> list4 = new ;in/ed;ist <Bnteger>$list%" S)stem&out&println$list4%"

Running t$e code gi es t$is e=&ected out&ut' 30 40 3! 30 40 3!

Introduction to Programming II

Page 1/(

J.E.D.I.

Re erences
1. Fee 4$u, Munn. ObBect Oriented Programming +it$ Ja a. Ju"y 1?3 1???. 2. Sun Java Programming Student Guide SL-275. Sun i!ro"y"tem". #pril 2$$$.

.. Mar, J. Encarnacion. 4%1?6 7otes. %&ecia" 8o&ics' Ja a Programming. 0. Patric, 7aug$ton and )erbert %c$i"dt. Ja a 2' 8$e 4om&"ete Re1erence. OsborneAMc5ra+C)i"". 1???. (. 8$e Ja a 8utoria"' A Practica" 5uide 1or Programmers. A ai"ab"e at $tt&'AABa a.sun.comAdocsAboo,sAtutoria" 6. Ja a in a 7uts$e"". 4$a&ter 0' 8$e Ja a P"at1orm. A ai"ab"e at $tt&'AA+++.uni=.org.uaAore""yABa aCentABnutAc$00T10.$tm 6. )8MF 8ag Re1erence' A&&"ets and P"ugCins. A ai"ab"e at $tt&'AA+++.code=.co.*aA$tm"Atags10.$tm /. 4"ientA%er er 7et+or,ing in Ja a by Mic$ae" Morrison. A ai"ab"e at $tt&'AAdocs.rinet.ru'/0/.AJ21Ac$26.$tm ?. A 5ent"e Introduction to 5enerics in Ja a by 4$ar"ie 4a" ert. A ai"ab"e at $tt&'AAbdn.bor"and.comAartic"eA0310103.20(0300.$tm" 10.Diagnosing Ja a 4ode' Ja a 5enerics 9it$out t$e Pain3 Part 1 by Eric A""en. A ai"ab"e at $tt&'AA+++C106.ibm.comAde e"o&er+or,sABa aA"ibraryABCdBc0211..$tm" 11.Insertion %ort. )erongHs 7otes on %orting by Dr. )erong Jang. A ai"ab"e at $tt&'AA+++.geocities.comA$erongTyangAsortAinsertion.$tm" 12.9i,i&edia' %e"ection %ort. A ai"ab"e at $tt&'AAen.+i,i&edia.orgA+i,iA%e"ectionTsort 1..MinHs 9or"d' About Merge %ort. A ai"ab"e at $tt&'AA+++.geocities.comA%i"iconVa""eyAProgramA2/60A!i"eAMerge1AMDoc1.$tm" 10.%e-uentia" and Para""e" %orting A"gorit$ms' Euic, %ort by )ans 9erner Fang. A ai"ab"e at $tt&'AA+++.iti.1$C1"ensburg.deA"angAa"gorit$menAsortierenA-uic,A-uic,en.$tm 1(.A"1red A$o3 et a". Data %tructures and A"gorit$ms. AddisonC9es"ey Pub"is$ing 4om&any. 1?/6. 16.8$e 4oncurrency 2ti"ities R J2%E(.0. A ai"ab"e at $tt&'AA+++.&artic"e.,t$.seAX"indseyAJa a4ourseA#oo,APart1AJa aA4$a&ter10Aconcurre ncy8oo"s.$tm" 16.API Documentation 1or Ja a 2 P"at1orm %tandard Ed. (.0. A ai"ab"e at $tt&'AABa a.sun.comAB2seA1.(.0AdocsAa&iAinde=.$tm" 1/.API Documentation 1or Ja a 2 P"at1orm %tandard Ed. V1.0.1. A ai"ab"e at $tt&'AABa a.sun.comAB2seA1.0.1AdocsAa&iAinde=.$tm"
Introduction to Programming II Page 1/6

J.E.D.I.

1?.$tt&'AA+++."ee&oint.netAnotesCBa aAbac,groundAtoo"sA7et#eans.$tm" $tt&'AABa a.sun.comAB2seA1.0.1AdocsAa&iAinde=.$tm"

Introduction to Programming II

Page 1/6

You might also like