Professional Documents
Culture Documents
Introduction to Programming II
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
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
#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
#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.
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.
.. 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.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.
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
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.
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!%" } } }
J.E.D.I.
String college"
Introduction to Programming II
Page 1.
J.E.D.I.
99instantiation
1.3.
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 }
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.
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" }
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.
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&
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.
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
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 ?
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 { }
Introduction to Programming II
Page 2.
J.E.D.I.
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.
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.
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.
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
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
...
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% {
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
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'
Introduction to Programming II
Page .0
J.E.D.I.
Introduction to Programming II
Page .(
J.E.D.I.
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.
Introduction to Programming II
Page .?
J.E.D.I.
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.
Introduction to Programming II
Page 00
J.E.D.I.
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.
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.
!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.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
top
botto*
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
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.
Introduction to Programming II
Page 06
J.E.D.I.
Introduction to Programming II
Page 06
J.E.D.I.
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.
)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.
Introduction to Programming II
Page (0
J.E.D.I.
Introduction to Programming II
Page (1
J.E.D.I.
Introduction to Programming II
Page (2
J.E.D.I.
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
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.
Introduction to Programming II
Page (6
J.E.D.I.
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.
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.
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.
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
Introduction to Programming II
Page 66
J.E.D.I.
4.
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
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¤t.ime1illis$%" for $int i = '" i < arr3&length" i((% { arr4 i! = arr3 i!" } end.ime = S)stem¤t.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¤t.ime1illis$%" S)stem&arra)cop)$arr30 '0 arr40 '0 arr3&length%" end.ime = S)stem¤t.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
Introduction to Programming II
Page 6?
J.E.D.I.
Introduction to Programming II
Page 60
J.E.D.I.
Introduction to Programming II
Page 61
J.E.D.I.
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.
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=
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(
J.E.D.I.
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
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>.
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.
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$
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.
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
.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$.
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.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.
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.2 An %5a*ple
5i en array'
Introduction to Programming II
Page /6
J.E.D.I.
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 ( . ( /
rig$t 0 ( /
rig$t 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 ( /
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.
Introduction to Programming II
Page //
J.E.D.I.
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'
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;>
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
)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'
Introduction to Programming II
Page ?1
J.E.D.I.
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.
Introduction to Programming II
Page ?.
J.E.D.I.
Introduction to Programming II
Page ?0
J.E.D.I.
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.
Introduction to Programming II
Page ?6
J.E.D.I.
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 ?/
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.
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%"
Introduction to Programming II
Page 101
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.
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
!or t$e com&"ete "ist o1 %+ing com&onents3 &"ease re1er to t$e API documentation.
J.E.D.I.
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.
Introduction to Programming II
Page 100
J.E.D.I.
Introduction to Programming II
Page 10(
J.E.D.I.
Introduction to Programming II
Page 106
J.E.D.I.
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.
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%
%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
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.
Description
Introduction to Programming II
Page 10?
J.E.D.I.
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.
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$%" }
Figure H.A: $unning 0ouseE#ents:emo: 0ouse enters the Frame Introduction to Programming II Page 112
J.E.D.I.
Introduction to Programming II
Page 11.
J.E.D.I.
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'
Introduction to Programming II
Page 11(
J.E.D.I.
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.
$.
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.
Introduction to Programming II
Page 116
J.E.D.I.
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
Introduction to Programming II
Page 11?
&.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.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
&.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
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.
Introduction to Programming II
Page 12.
J.E.D.I.
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
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=%" } }
Introduction to Programming II
Page 12(
J.E.D.I.
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.
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.
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
J.E.D.I.
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.
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.
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$%"
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.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.
Introduction to Programming II
Page 100
J.E.D.I.
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.
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.
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.
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$%"
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&
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.
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.
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.
Introduction to Programming II
Page 1(.
J.E.D.I.
Introduction to Programming II
Page 1(0
J.E.D.I.
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
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.
Introduction to Programming II
Page 1(6
J.E.D.I.
J.E.D.I.
Introduction to Programming II
Page 1(?
J.E.D.I.
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.
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
Introduction to Programming II
Page 16.
J.E.D.I.
Introduction to Programming II
Page 160
J.E.D.I.
12.
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'
Introduction to Programming II
Page 166
J.E.D.I.
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
Introduction to Programming II
Page 16/
J.E.D.I.
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
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
Introduction to Programming II
Page 160
J.E.D.I.
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
Introduction to Programming II
Page 161
J.E.D.I.
Introduction to Programming II
Page 162
J.E.D.I.
Passing tempo.txt and tempo;.txt as arguments3 $ereHs a sam&"e run o1 t$is code'
Introduction to Programming II
Page 16.
J.E.D.I.
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.
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$%" }
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
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$%"
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.
Introduction to Programming II
Page 1/2
J.E.D.I.
Introduction to Programming II
Page 1/.
J.E.D.I.
Introduction to Programming II
Page 1/0
J.E.D.I.
13.
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%"
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.
Introduction to Programming II
Page 1/6