jedi course notes intro1 masterdocument
TRANSCRIPT
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 1/244
J.E.D.I
Introduction to Programming I 1
Introduction toProgramming I
Student's Manual
Version 1.3
June 2006
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 2/244
Introduction to Programming I 2
J.E.D.I
A u t h o r
Florence Tiu Balagtas
T e a mJoyce !estroFlorence Balagtas"ommel Feria"eginald #utc$erson"e%ecca &ngJo$n Paul Petines'ang '$in"ag$a!an 'rini!as(att$e) T$om*son
R e q ui re m e n t s F o r t he L a b or a tor y E x e r c ise sSup ported Ope rat in g Syst em sT$e +etBeans IDE ,., runs on o*erating systems t$at su**ort t$e Ja!a V(.
• (icroso-t indo)s /P Pro-essional 'P2 or ne)er
• (ac &' / 10.., or ne)er
• "ed #at Fedora ore 3
• 'olaris 10 &*erating 'ystem *date 1 4'P"5 and 7686
Plat-orm Edition9
+etBeans Enter*rise Pac: is also :no)n to run on t$e -ollo)ing *lat-orms;
• (icroso-t indo)s 2000 Pro-essional 'P
• 'olaris 7 &' 4'P" and 7686 Plat-orm Edition9 and 'olaris < &'
4'P" and 7686 Plat-orm Edition9
• Various ot$er =inu distri%utions
M in im um a rd ! a re " on# ig ur a t i o n
Note: The NetBeans IDE's minimum screen resolution is 1024x768pixels.
Operating System Processor Memory $is% Space(icroso-t indo)s ,00 (#> Intel Pentium III ,12 (B 7,0 (B o- -ree
dis: s*ace
=inu ,00 (#> Intel Pentium III)or:station or e?ui!alent
,12 (B ,0 (B o- -reedis: s*ace
'olaris &' 4'P"9 ltra'P" II ,0 (#> ,12 (B ,0 (B o- -reedis: s*ace
'olaris &' 47686Plat-orm Edition9
(D &*teron 100 'eries1.7 @#>
,12 (B ,0 (B o- -reedis: s*ace
(acintos$ &' /o*erating system
Po)erP @ ,12 (B ,0 (B o- -reedis: s*ace
Recom me nded a rd!are "on#igurati on
Operating System Processor Memory $is% Speed
(icroso-t indo)s 1. @#> Intel Pentium III)or:station or e?ui!alent
1 @B 1 @B o- -ree dis:s*ace
=inu 1. @#> Intel Pentium III)or:station or e?ui!alent
1 @B 7,0 (B o- -reedis: s*ace
'olaris &' 4'P"9 ltra'P" IIIi 1 @#> 1 @B 7,0 (B o- -reedis: s*ace
'olaris &' 47686Plat-orm Edition9
(D &*teron 100 'eries1.7 @#>
1 @B 7,0 (B o- -reedis: s*ace
(acintos$ &' /o*erating system
Po)erP @, 1 @B 7,0 (B o- -reedis: s*ace
R e q u i red So# t!a r e+etBeans Enter*rise Pac: ,., Early ccess runs on t$e Ja!a 2 Plat-orm'tandard Edition De!elo*ment Ait ,.0 *date 1 or $ig$er 4JDA ,.0 !ersion
1.,.0C01 or $ig$er9 )$ic$ consists o- t$e Ja!a "untime En!ironment *lusde!elo*er tools -or com*iling de%ugging and running a**lications )ritten int$e Ja!a language. 'un Ja!a 'ystem **lication 'er!er Plat-orm Edition < $as%een tested )it$ JDA ,.0 u*date 6.
• For So&aris 'indo!s and Linux you can do)nload t$e JDA -or your
*lat-orm -rom $tt*; 88 a! a.s un .com8 2se 81. ,.0 8 do )nl oa d.$tml
• For Mac OS ( Ja!a 2 Plat-orm 'tandard Edition 4J2'E9 ,.0 "elease is
re?uired. ou can do)nload t$e JDA -rom **les De!elo*er onnectionsite. 'tart $ere; $ tt* ;8 8 d e ! e lo * e r. a **l e .co m 8 a ! a 4you must register todo)nload t$e JDA9.
F o r m o r e in -o r mat ion *l e a s e ! is it;$ tt* ;88 ))) .n e t%e a n s . o rg 8co mm u n ity 8 re le a ses 8 0 8 r e ln o te s .$ tm l
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 3/244
Tab&e o# "ontents1 Introduction to om*uter Programming..............................................................10
1.1 &%ecti!es............................................................................................... 101.2 Introduction............................................................................................. 101.3 Basic om*onents o- a om*uter................................................................ 11
1.3.1 #ard)are.......................................................................................... 111.3.1.1 T$e entral Processing nit.......................................................... 111.3.1.2 (emory .................................................................................... 111.3.1.3 In*ut and &ut*ut De!ices............................................................. 12
1.3.2 'o-t)are........................................................................................... 121. &!er!ie) o- om*uter Programming =anguages........................................... 13
1..1 $at is a Programming =anguageG....................................................... 131..2 ategories o- Programming =anguages..................................................13
1., T$e Program De!elo*ment =i-e ycle........................................................... 11.,.1 Pro%lem De-inition............................................................................. 1,
1.,.2 Pro%lem nalysis............................................................................... 1,1.,.3 lgorit$m design and re*resentation.................................................... 16
1.,.3.1 Flo)c$arting 'ym%ols and t$eir meanings...................................... 1H1.,. oding and De%ugging....................................................................... 17
1.6 +um%er 'ystems and on!ersions.............................................................. 1<1.6.1 Decimal............................................................................................ 1<1.6.2 Binary.............................................................................................. 1<1.6.3 &ctal................................................................................................ 1<1.6. #eadecimal..................................................................................... 1<1.6., on!ersions...................................................................................... 20
1.6.,.1 Decimal to Binary 8 Binary to Decimal............................................ 201.6.,.2 Decimal to &ctal 4or #eadecimal98&ctal 4or #eadecimal9 to Decimal....
211.6.,.3 Binary to &ctal 8 &ctal to Binary.................................................... 221.6.,. Binary to #eadecimal 8 #eadecimal to Binary............................... 23
1.H Eercises................................................................................................. 21.H.1 riting lgorit$ms............................................................................. 21.H.2 +um%er on!ersions.......................................................................... 2
2 Introduction to Ja!a........................................................................................ 2,2.1 &%ecti!es............................................................................................... 2,2.2 Ja!a Bac:ground...................................................................................... 2,
2.2.1 little Bit o- #istory .......................................................................... 2,2.2.2 $at is Ja!a Tec$nologyG................................................................... 2,
2.2.2.1 *rogramming language............................................................. 2,2.2.2.2 de!elo*ment en!ironment......................................................... 2,2.2.2.3 n a**lication en!ironment.......................................................... 2,2.2.2. de*loyment en!ironment........................................................... 26
2.2.3 'ome Features o- Ja!a........................................................................ 262.2.3.1 T$e Ja!a Virtual (ac$ine.............................................................. 262.2.3.2 @ar%age ollection...................................................................... 262.2.3.3 ode 'ecurity............................................................................. 2H
2.2. P$ases o- a Ja!a Program.................................................................... 273 @etting to :no) your Programming En!ironment................................................. 2<
3.1 &%ecti!es............................................................................................... 2<3.2 Introduction............................................................................................. 2<3.3 (y First Ja!a Program............................................................................... 2<3. sing a Tet Editor and onsole................................................................. 30
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 4/244
3..1 Errors .............................................................................................. 0
3..1.1 'ynta Errors............................................................................. 03..1.2 "untime Errors.......................................................................... 1
3., sing +etBeans........................................................................................ 23.6 Eercises................................................................................................. ,,
3.6.1 #ello orld...................................................................................... ,,3.6.2 T$e Tree........................................................................................... ,,
Programming Fundamentals............................................................................. ,6.1 &%ecti!es............................................................................................... ,6.2 Dissecting my -irst Ja!a *rogram................................................................ ,6.3 Ja!a omments........................................................................................ ,7
.3.1 KK'tyle omments......................................................................... ,7.3.2 'tyle omments............................................................................. ,7.3.3 '*ecial Ja!adoc omments................................................................. ,7
. Ja!a 'tatements and %loc:s....................................................................... ,<., Ja!a Identi-iers........................................................................................ 60
.6 Ja!a Aey)ords......................................................................................... 61.H Ja!a =iterals............................................................................................ 62
.H.1 Integer =iterals ................................................................................. 62.H.2 FloatingPoint =iterals ........................................................................ 62.H.3 Boolean =iterals ................................................................................ 62.H. $aracter =iterals .............................................................................. 63.H., 'tring =iterals ................................................................................... 63
.7 Primiti!e data ty*es.................................................................................. 6.7.1 =ogical %oolean............................................................................... 6.7.2 Tetual L c$ar................................................................................... 6.7.3 Integral L %yte s$ort int M long.......................................................... 6,.7. Floating Point L -loat and dou%le.......................................................... 66
.< Varia%les................................................................................................. 6H.<.1 Declaring and Initiali>ing Varia%les....................................................... 6H.<.2 &ut*utting Varia%le Data.................................................................... 67.<.3 'ystem.out.*rintln49 !s. 'ystem.out.*rint49 ......................................... 67.<. "e-erence Varia%les !s. Primiti!e Varia%les............................................ 6<
.10 &*erators.............................................................................................. H0.10.1 rit$metic o*erators......................................................................... H0.10.2 Increment and Decrement o*erators................................................... H3.10.3 "elational o*erators......................................................................... H,.10. =ogical o*erators.............................................................................. H7
.10..1 MM 4logical +D9 and M 4%oolean logical +D9............................... H<.10..2 NN 4logical &"9 and N 4%oolean logical inclusi!e &"9.........................71.10..3 O 4%oolean logical eclusi!e &"9.................................................. 73.10.. 4logical +&T9.......................................................................... 7
.10., onditional &*erator 4G;9.................................................................. 7,.10.6 &*erator Precedence........................................................................ 7H
.11 Eercises............................................................................................... 77.11.1 Declaring and *rinting !aria%les......................................................... 77.11.2 @etting t$e a!erage o- t$ree num%ers................................................. 77.11.3 &ut*ut greatest !alue....................................................................... 77.11. &*erator *recedence........................................................................ 77
, @etting In*ut -rom t$e Aey%oard....................................................................... 7<,.1 &%ecti!es............................................................................................... 7<,.2 sing Bu--ered"eader to get in*ut.............................................................. 7<,.3 sing J&*tionPane to get in*ut................................................................... <3
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 5/244
,. Eercises................................................................................................. <,
,..1 =ast 3 )ords 4Bu--ered"eader !ersion9.................................................. <,,..2 =ast 3 )ords 4J&*tionPane !ersion9...................................................... <,
6 ontrol 'tructures........................................................................................... <66.1 &%ecti!es............................................................................................... <66.2 Decision ontrol 'tructures........................................................................ <6
6.2.1 i- statement...................................................................................... <66.2.2 i-else statement............................................................................... <76.2.3 i-elsei- statement........................................................................... 1006.2. ommon Errors )$en using t$e i-else statements;............................... 1016.2., Eam*le -or i-elseelse i-.................................................................. 1026.2.6 s)itc$ statement............................................................................. 1036.2.H Eam*le -or s)itc$........................................................................... 10,
6.3 "e*etition ontrol 'tructures.................................................................... 1066.3.1 )$ile loo*....................................................................................... 1066.3.2 do)$ile loo*................................................................................... 107
6.3.3 -or loo*........................................................................................... 10<6. Branc$ing 'tatements............................................................................. 110
6..1 %rea: statement.............................................................................. 1106..1.1 nla%eled %rea: statement......................................................... 1106..1.2 =a%eled %rea: statement............................................................ 111
6..2 continue statement.......................................................................... 1126..2.1 nla%eled continue statement..................................................... 1126..2.2 =a%eled continue statement........................................................ 112
6..3 return statement.............................................................................. 1136., Eercises............................................................................................... 11
6.,.1 @rades........................................................................................... 116.,.2 +um%er in )ords.............................................................................. 11
6.,.3 #undred Times................................................................................ 116.,. Po)ers........................................................................................... 11H Ja!a rrays.................................................................................................. 11,
H.1 &%ecti!es............................................................................................. 11,H.2 Introduction to arrays.............................................................................. 11,H.3 Declaring rrays..................................................................................... 116H. ccessing an array element...................................................................... 117H., rray lengt$........................................................................................... 11<H.6 (ultidimensional rrays........................................................................... 120H.H Eercises............................................................................................... 121
H.H.1 Days o- t$e ee:............................................................................. 121H.H.2 @reatest num%er.............................................................................. 121H.H.3 ddress%oo: Entries......................................................................... 121
7 ommandline rguments.............................................................................. 1227.1 &%ecti!es............................................................................................. 1227.2 ommandline arguments........................................................................ 1227.3 ommandline arguments in +etBeans...................................................... 127. Eercises............................................................................................... 127
7..1 Print arguments............................................................................... 1277..2 rit$metic &*erations....................................................................... 127
< or:ing )it$ t$e Ja!a lass =i%rary................................................................. 12<<.1 &%ecti!es............................................................................................. 12<<.2 Introduction to &%ect&riented Programming............................................. 12<<.3 lasses and &%ects................................................................................ 130
<.3.1 Di--erence Bet)een lasses and &%ects.............................................. 130
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 6/244
<.3.2 Enca*sulation.................................................................................. 131
<.3.3 lass Varia%les and (et$ods.............................................................. 131<.3. lass Instantiation........................................................................... 132
<. (et$ods................................................................................................ 133<..1 $at are (et$ods and $y se (et$odsG........................................... 133<..2 alling Instance (et$ods and Passing Varia%les....................................13<..3 Passing Varia%les in (et$ods............................................................. 13,
<..3.1 Pass%y!alue........................................................................... 13,<..3.2 Pass%yre-erence...................................................................... 136
<.. alling 'tatic (et$ods...................................................................... 13H<.., 'co*e o- a !aria%le........................................................................... 137
<., asting on!erting and om*aring &%ects............................................... 11<.,.1 asting Primiti!e Ty*es..................................................................... 11<.,.2 asting &%ects............................................................................... 13<.,.3 on!erting Primiti!e Ty*es to &%ects and Vice Versa............................ 1,<.,. om*aring &%ects........................................................................... 16
<.,., Determining t$e lass o- an &%ect..................................................... 17<.6 Eercises............................................................................................... 1<
<.6.1 De-ining terms................................................................................. 1<<.6.2 Ja!a 'ca!enger #unt........................................................................ 1<
10 reating your o)n lasses............................................................................ 1,010.1 &%ecti!es............................................................................................ 1,010.2 De-ining your o)n classes...................................................................... 1,110.3 Declaring ttri%utes.............................................................................. 1,2
10.3.1 Instance Varia%les.......................................................................... 1,210.3.2 lass Varia%les or 'tatic Varia%les.................................................... 1,3
10. Declaring (et$ods................................................................................ 1,310..1 ccessor met$ods........................................................................... 1,
10..2 (utator (et$ods............................................................................ 1,,10..3 (ulti*le "eturn statements.............................................................. 1,610.. 'tatic met$ods............................................................................... 1,610.., 'am*le 'ource ode -or 'tudent"ecord class..................................... 1,H
10., T$e t$is re-erence................................................................................. 1,<10.6 &!erloading (et$ods............................................................................. 16010.H Declaring onstructors........................................................................... 162
10.H.1 De-ault onstructor........................................................................ 16210.H.2 &!erloading onstructors................................................................ 16210.H.3 sing onstructors......................................................................... 16310.H. T$e t$is49 onstructor all............................................................... 16
10.7 Pac:ages............................................................................................. 16,10.7.1 Im*orting Pac:ages........................................................................ 16,10.7.2 reating your o)n *ac:ages............................................................ 16,10.7.3 'etting t$e =''PT#.................................................................. 166
10.< ccess (odi-iers................................................................................... 16710.<.1 de-ault access 4also called *ac:age accessi%ility9................................ 16710.<.2 *u%lic access................................................................................. 16710.<.3 *rotected access............................................................................ 16<10.<. *ri!ate access................................................................................ 16<
10.10 Eercises........................................................................................... 1H010.10.1 ddress Boo: Entry....................................................................... 1H010.10.2 ddressBoo:................................................................................ 1H0
11 In$eritance Polymor*$ism and Inter-aces....................................................... 1H111.1 &%ecti!es............................................................................................ 1H1
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 7/244
11.2 In$eritance.......................................................................................... 1H1
11.2.1 De-ining 'u*erclasses and 'u%classes............................................... 1H211.2.2 T$e su*er :ey)ord......................................................................... 1H11.2.3 &!erriding (et$ods........................................................................ 1H,11.2. Final (et$ods and Final lasses........................................................ 1H6
11.3 Polymor*$ism...................................................................................... 1HH11. %stract lasses................................................................................... 1H<11., Inter-aces............................................................................................ 171
11.,.1 $y do )e use Inter-acesG.............................................................. 17111.,.2 Inter-ace !s. %stract lass.............................................................. 17111.,.3 Inter-ace !s. lass.......................................................................... 17211.,. reating Inter-aces......................................................................... 17211.,., "elations$i* o- an Inter-ace to a lass............................................... 1711.,.6 In$eritance among Inter-aces........................................................... 17
11.6 Eercises............................................................................................. 17,11.6.1 Etending 'tudent"ecord................................................................ 17,
11.6.2 T$e '$a*e a%stract class................................................................. 17,12 Basic Ece*tion #andling.............................................................................. 176
12.1 &%ecti!es............................................................................................ 17612.2 $at are Ece*tionsG............................................................................ 17612.3 #andling Ece*tions.............................................................................. 17612. Eercises............................................................................................. 17<
12..1 atc$ing Ece*tions1...................................................................... 17<12..2 atc$ing Ece*tions 2..................................................................... 17<
**endi ; Ja!a and +etBeans Installation......................................................... 1<0Installing Ja!a in %untu Da**er..................................................................... 1<1Installing Ja!a in indo)s............................................................................. 1<6Installing +etBeans in %untu Da**er.............................................................. 200
Installing +etBeans in indo)s....................................................................... 207**endi B; @etting to :no) your Programming En!ironment 4indo)s /P !ersion9.. 21,(y First Ja!a Program................................................................................... 21,sing a Tet Editor and onsole...................................................................... 216
'etting t$e Pat$........................................................................................ 22<sing +etBeans............................................................................................ 230
**endi D ; (ac$ine Pro%lems.......................................................................... 20(ac$ine Pro%lem 1; P$one Boo:...................................................................... 20(ac$ine Pro%lem 2; (ines)ee*er.................................................................... 21(ac$ine Pro%lem 3; +um%er on!ersion........................................................... 22
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 8/244
Re)ision istory
For *ersion +,-
June 2006
Section $etai&s
**endi and B $a*ter 3;@ettingto :no) your *rogrammingen!ironment
')itc$ to +et%eans ,., Beta Version
**endi $a*ter 3;@etting to:no) your *rogramming en!ironment
')itc$ -rom "ed$at =inu to %untu Da**er
**endi F; dditional Eercises dded 4Teac$ers manual9c8o JEDI mem%ersc$ool teac$ers
For *ersion +,.January 2006
Section $etai&s
Version +um%er $ange -rom 1.1 to 1.2
$a*ter 3; @ettting to :no) your*rogramming en!ironment**endi
$ange +et%eans8net%eans to /et0eans
$a*ter ; Programming
Fundamentals
=ist o- Ja!a :ey)ords
$a*ter 10; reating your o)n classes oding guidelines; -ilenames s$ould $a!e t$esame name as t$e pub&ic class name
(aster Documents dded to list o- re-erences
For *ersion +,+
ugust 200,
Section $etai&s
Version +um%er $ange -rom 1.0 to 1.1
"e!ision #istory dded
**endi E; #andson =a% Eercises dded 4c8o 'ang9
$a*ter 10; reating our o)n classes dded su%section on #o) to set class*at$ at*ac:ages section
$a*ter 11; In$eritance Inter-acesand Polymor*$ism
Polymor*$ism section• dded eam*le t$at uses anot$er class
)$ose met$od can recei!e a re-erence!aria%le
Inter-ace• dded sections
• $y do )e use Inter-acesG
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 9/244
J.E.D.I
Section $etai&s
• Inter-ace !s. %stract lass
• Inter-ace !s. lass
• "elations$i* o- an Inter-ace to a lass• In$eritance among Inter-aces
Introduction to Programming I <
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 10/244
Introduction to Programming I 10
J.E.D.I
+ Introduction to "omputer
Programming
1.1 Objectives
In t$is section )e )ill %e discussing t$e %asic com*onents o- a com*uter %ot$ $ard)areand so-t)are. e )ill also %e gi!ing a %rie- o!er!ie) o- *rogramming languages and t$e*rogram de!elo*ment li-e cycle. Finally di--erent num%er systems and con!ersions -romone ty*e to anot$er )ill %e discussed.
t t$e end o- t$e lesson t$e student s$ould %e a%le to;
• Identi-y t$e di--erent com*onents o- a com*uter
• Ano) a%out *rogramming languages and t$eir categories
• nderstand t$e *rogram de!elo*ment li-e cycle and a**ly it in *ro%lem sol!ing
• =earn t$e di--erent num%er systems and t$eir con!ersions
1.2 Introduction
com*uter is a mac$ine t$at *er-orms a !ariety o- tas:s according to s*eci-icinstructions. It is a data *rocessing mac$ine )$ic$ acce*ts data !ia an input device and
its processor mani*ulates t$e data according to a program.
T$e com*uter $as t)o maor com*onents. T$e -irst one is t$e ard!are )$ic$ is t$etangi%le *art o- t$e com*uter. It is com*osed o- electronic and mec$anical *arts.
T$e second maor com*onent is t$e so#t!are )$ic$ is t$e intangi%le *art o- a com*uter.It consists o- data and t$e com*uter *rograms.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 11/244
Introduction to Programming I 11
J.E.D.I
1.3 Basic Components of a Computer
1.3.1 ard!are
+,-,+,+ The "entra& Processing 1nit
T$e *rocessor is t$e %rainQ o- t$e com*uter. It contains millions o- etremely tinyelectrical *arts. It does t$e -undamental com*uting )it$in t$e system. Eam*les o-*rocessors are Pentium t$lon and 'P".
+,-,+,. Memory
T$e memory is )$ere data and instructions needed %y t$e P to do its a**ointed tas:scan %e -ound. It is di!ided into se!eral storage locations )$ic$ $a!e corres*ondingaddresses. T$e P accesses t$e memory )it$ t$e use o- t$ese addresses.
+, Main Memory
T$e main memory is !ery closely connected to t$e *rocessor. It is used to $old *rogramsand data t$at t$e *rocessor is acti!ely )or:ing )it$. It is not used -or longtermstorage. It is sometimes called t$e "( 4"andom ccess (emory9.
T$e com*uters main memory is considered as volatile storage. T$is means t$at oncet$e com*uter is turned o-- all in-ormation residing in t$e main memory is erased.
., The Secondary Memory
T$e secondary memory is connected to main memory. It is used to $old *rograms anddata -or long term use. Eam*les o- secondary memory are $ard dis:s and cdrom.
'econdary memory is considered as non"volatile storage. T$is means t$at in-ormationresiding in secondary memory is not erased a-ter t$e com*uter is turned o--.
Main
Memor#
Secondar#
Memor# $ropert#
Fast 'lo) '*eed
E*ensi!e $ea* Price
=o) #ig$ a*acity
es +o Volatile
Table 1: Comparison between main memory and secondary memory
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 12/244
Introduction to Programming I 12
J.E.D.I
+,-,+,- Input and Output $e)ices
In*ut and out*ut de!ices allo)s a com*uter system to interact )it$ t$e outside )orld %ymo!ing data into and out o- t$e system.
Eam*les o- in*ut de!ices are :ey%oards mice and micro*$ones. Eam*les o- out*utde!ices are monitors *rinters and s*ea:ers.
1.3.2 Soft!are
so-t)are is t$e *rogram t$at a com*uter uses in order to -unction. It is :e*t on some$ard)are de!ice li:e a $ard dis: %ut it itsel- is intangi%le. T$e data t$at t$e com*uteruses can %e anyt$ing t$at a *rogram needs. Programs acts li:e instructions -or t$e*rocessor.
Some Types o# "omputer Programs2
+, Systems Programs
• Programs t$at are needed to :ee* all t$e $ard)are and so-t)are systems running
toget$er smoot$ly
• Eam*les;
• &*erating 'ystems li:e =inu indo)s ni 'olaris (ac&'
., App&ication Programs
• Programs t$at *eo*le use to get t$eir )or: done
• Eam*les;
• ord Processor
• @ame *rograms
• '*reads$eets
-, "ompi&ers
• T$e com*uter understands only one language; mac$ine language. (ac$ine
language is in t$e -orm o- ones and >eros. 'ince it is $ig$ly im*ractical -or *eo*leto create *rograms out o- >eros and ones t$ere must %e a )ay o- translating orcon!erting a language )$ic$ )e understand into mac$ine language -or t$is
*ur*ose t$ere eists com*ilers.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 13/244
Introduction to Programming I 13
J.E.D.I
1.% Overvie! of Computer $rogramming&anguages
1.%.1 (at is a $rogramming &anguage)
*rogramming language is a standardi>ed communication tec$ni?ue -or e*ressinginstructions to a com*uter. =i:e $uman languages eac$ language $as its o)n syntaand grammar.
Programming languages ena%le a *rogrammer to *recisely s*eci-y )$at data a com*uter)ill act u*on $o) t$ese data )ill %e stored8transmitted and *recisely )$at actions tota:e under !arious circumstances.
T$ere are di--erent ty*es o- *rogramming languages t$at can %e used to create
*rograms %ut regardless o- )$at language you use t$ese instructions are translatedinto mac$ine language t$at can %e understood %y com*uters.
1.%.2 Categories of $rogramming &anguages
+, igh3&e)e& Programming Languages
• $ig$le!el *rogramming language is a *rogramming language t$at is more user
-riendly to some etent *lat-orminde*endent and a%stract -rom lo)le!elcom*uter *rocessor o*erations suc$ as memory accesses. *rogramming
statement may %e translated into one or se!eral mac$ine instructions %y a
compi&er.
• Eam*les are Ja!a KK Basic Fortran
., Lo!3&e)e& Assemb&y Language
• ssem%ly languages are similar to mac$ine languages %ut t$ey are muc$ easier to
*rogram in %ecause t$ey allo) a *rogrammer to su%stitute names -or num%ers.
ssem%ly languages are a!aila%le -or eac$ P -amily and eac$ assem%lyinstruction is translated into one mac$ine instruction %y an assemb&er *rogram.
/ote2 T$e terms R$ig$le!elR and Rlo)le!elR are in$erently relati!e. &riginally assem%lylanguage )as considered lo)le!el and &B&= etc. )ere considered $ig$le!el. (any*rogrammers today mig$t re-er to t$ese latter languages as lo)le!el.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 14/244
Introduction to Programming I 1
J.E.D.I
1.* +(e $rogram ,evelopment &ife
C#cle
Programmers do not sit do)n and start )riting code rig$t a)ay )$en trying to ma:e acom*uter *rogram. Instead t$ey -ollo) an organi>ed *lan or met$odology t$at %rea:st$e *rocess into a series o- tas:s.
#ere are t$e %asic ste*s in trying to sol!e a *ro%lem on t$ecom*uter;
1. Pro%lem De-inition
2. Pro%lem nalysis3. lgorit$m design and re*resentation 4Pseudocode or -lo)c$art9. oding and de%ugging
In order to understand t$e %asic ste*s in sol!ing a *ro%lem on a com*uter let us de-inea single *ro%lem t$at )e )ill sol!e ste*%yste* as )e discuss t$e *ro%lem sol!ingmet$odologies in detail. T$e *ro%lem )e )ill sol!e )ill %e de-ined in t$e net section.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 15/244
Introduction to Programming I 1,
J.E.D.I
1.*.1 $roblem ,efinition
*rogrammer is usually gi!en a tas: in t$e -orm o- a *ro%lem. Be-ore a *rogram can %e
designed to sol!e a *articular *ro%lem t$e *ro%lem must %e )ell and clearly de-ined -irstin terms o- its in*ut and out*ut re?uirements.
clearly de-ined *ro%lem is already $al- t$e solution. om*uter *rogramming re?uiresus to de-ine t$e *ro%lem -irst %e-ore )e e!en try to create a solution.
&et us no! define our e-ample
problem
reate a *rogram t$at )ill determine t$e num%er o- times a name occurs in a list.Q
1.*.2 $roblem /nal#sis
-ter t$e *ro%lem $as %een ade?uately de-ined t$e sim*lest and yet t$e most e--icientand e--ecti!e a**roac$ to sol!e t$e *ro%lem must %e -ormulated.
sually t$is ste* in!ol!es %rea:ing u* t$e *ro%lem into smaller and sim*ler su%*ro%lems.
0-ample $roblemDetermine t$e num%er o- times a name occurs in a list
Input to t(e program
list o- names name to loo: -or
Output of t(e
program
t$e num%er o- times t$e name occurs in a list
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 16/244
YES
Introduction to Programming I 16
J.E.D.I
1.*.3 /lgorit(m design and representation
&nce our *ro%lem is clearly de-ined )e can no) set to -inding a solution. In com*uter
*rogramming it is normally re?uired to e*ress our solution in a ste*%yste* manner.
n A&gorithm is a clear and unam%iguous s*eci-ication o- t$e ste*s needed to sol!e a*ro%lem. It may %e e*ressed in eit$er uman &anguage 4Englis$ Tagalog9 t$roug$ agra*$ical re*resentation li:e a #&o!chart or t$roug$ a pseudocode )$ic$ is a cross%et)een $uman language and a *rogramming language.
+o) gi!en t$e *ro%lem de-ined in t$e *re!ious sections $o) do )e e*ress our generalsolution in suc$ a )ay t$at it is sim*le yet understanda%leG
0-pressing our solution t(roug( umanlanguage
1. @et t$e list o- names2. @et t$e name to loo: -or lets call t$is t$e :eyname3. om*are t$e :eyname to eac$ o- t$e names in t$e list. I- t$e :eyname is t$e same )it$ a name in t$e list add 1 to t$e count,. I- all t$e names $a!e %een com*ared out*ut t$e result
0-pressing our solution t(roug( aflo!c(art
Figure 1.1: Example of a flow chart
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 17/244
Introduction to Programming I 1H
J.E.D.I
0-pressing our solution t(roug(
pseudocode
=et name=ist S =ist o- +ames
=et :ey+ame S t$e name to %e soug$t=et ount S 0For eac$ name in +ame=ist do t$e -ollo)ingi- name SS :ey+ameount S ount K 1
Dis*lay ount
Figure 1.2: Example of a pseudocode
+,4,-,+ F&o!charting Symbo&s and theirmeanings
-lo)c$art is a design tool used to gra*$ically re*resent t$e logic in a solution.Flo)c$arts ty*ically do not dis*lay *rogramming language commands. "at$er t$ey state
t$e conce*t in Englis$ or mat$ematical notation.
#ere are some guidelines -or commonly used sym%ols in creating -lo)c$arts. ou can useany sym%ols in creating your -lo)c$arts as long as you are consistent in using t$em.
S#mbol ame Meaning
"e*resents t$e *rocess o- eecuting a de-inedo*eration or grou*s o- o*erations t$at results in a
Process Symbo&
Input5Output
6I5O7 Symbo&
F&o!&ine Symbo&
Annotation
Symbo&
c$ange in !alue -orm or location o- in-ormation.lso -unctions as t$e de-ault sym%ol )$en noot$er sym%ol is a!aila%le.
"e*resents an I8& -unction )$ic$ ma:es dataa!aila%le -or *rocessing 4in*ut9 or dis*laying4out*ut9o- *rocessed in-ormation.
"e*resents t$e se?uence o- a!aila%le in-ormationand eecuta%le o*erations.T$e lines connectot$er sym%ols and t$e arro)$eads aremandatory only -or rig$ttole-t and %ottomtoto* -lo).
"e*resents t$e addition o- descri*ti!ein-ormation comments or e*lanatory notes asclari-ication. T$e !ertical line and t$e %ro:en line
may %e *laced on t$e le-t as s$o)n or on t$erig$t.
$ecision Symbo&
Termina& Symbo&
"e*resents a decision t$at determines )$ic$ o- anum%er o- alternati!e *at$s is to %e -ollo)ed.
"e*resents t$e %eginning t$e end or a *oint o-
interru*tion or delay in a *rogram.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 18/244
S#mbol ame Meaning
"e*resents any entry -rom or eit to anot$er*art o- t$e -lo)c$art. lso ser!es as an o--*age
"onnector
Symbo&
Prede#inedProcess Symbo&
connector.
"e*resents a named *rocess consisting o- one ormore o*erations or *rogram ste*s t$at ares*eci-ied else)$ere.
Table 2: Flowchart Symbols
1.*.% Coding and ,ebugging
-ter constructing t$e algorit$m it is no) *ossi%le to create t$e source code. sing t$ealgorit$m as %asis t$e source code can no) %e )ritten using t$e c$osen *rogramminglanguage.
(ost o- t$e time a-ter t$e *rogrammer $as )ritten t$e *rogram t$e *rogram isnt 100)or:ing rig$t a)ay. T$e *rogrammer $as to add some -ies to t$e *rogram in case o-errors 4also called %ugs9 t$at occurs in t$e *rogram. T$is *rocess o- is calleddebugging.
T$ere are t)o ty*es o- errors t$at a *rogrammer )ill encounter along t$e )ay. T$e -irstone is com*iletime error and t$e ot$er is runtime error.
Compile"+ime 0rrors occur i- t$ere is a synta error in t$e code. T$e com*iler )illdetect t$e error and t$e *rogram )ont e!en com*ile. t t$is *oint t$e *rogrammer isuna%le to -orm an eecuta%le t$at a user can run until t$e error is -ied.
Forgetting a semicolon at t$e end o- a statement or miss*elling a certain command -oream*le is a com*iletime error. Its somet$ing t$e com*iler can detect as an error.
om*ilers arent *er-ect and so cant catc$ all errors at com*ile time. T$is is es*eciallytrue -or logic errors suc$ as in-inite loo*s. T$is ty*e o- error is called runtime error.
For eam*le t$e actual synta o- t$e code loo:s o:ay. But )$en you -ollo) t$e codeslogic t$e same *iece o- code :ee*s eecuting o!er and o!er again in-initely so t$at it
loo*s. In suc$ a case com*ilers arent really smart enoug$ to catc$ all o- t$ese ty*es o-errors at com*iletime and t$ere-ore t$e *rogram com*iles -ine into an eecuta%le -ile.#o)e!er and un-ortunately )$en t$e enduser runs t$e *rogram t$e *rogram 4or e!ent$eir )$ole com*uter9 -ree>es u* due to an in-inite loo*. &t$er ty*es o- runtime errorsare )$en an incorrect !alue is com*uted t$e )rong t$ing $a**ens etc.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 19/244
1. umber S#stems and Conversions+um%ers can %e re*resented in a !ariety o- )ays. T$e re*resentation de*ends on )$at is
called t$e 0ASE. T$e -ollo)ing are t$e -our most common re*resentations.
1..1 ,ecimal
e normally re*resent num%ers in t$eir decimal -orm. +um%ers in decimal -orm are in%ase 10. T$is means t$at t$e only digits t$at a**ear are 0<. #ere are eam*les o-num%ers )ritten in decimal -orm;
12610 4normally )ritten as ust 12691110 4normally )ritten as ust 119
1..2 Binar#
+um%ers in %inary -orm are in %ase 2. T$is means t$at t$e only legal digits are 0 and 1.
e need to )rite t$e su%scri*t 2 to indicate t$at t$e num%er is a %inary num%er. #ereare eam*les o- num%ers )ritten in %inary -orm;11111102
10112
1..3 Octal
+um%ers in octal -orm are in %ase 7. T$is means t$at t$e only legal digits are 0H. eneed to )rite t$e su%scri*t 7 to indicate t$at t$e num%er is an octal num%er. #ere are
eam*les o- num%ers )ritten in octal -orm;1H67
137
1..% e-adecimal
+um%ers in $eadecimal -orm are in %ase 16. T$is means t$at t$e only legal digits are 0< and t$e letters F 4or a- lo)ercase or u**ercase does not matter9. e need to )ritet$e su%scri*t 16 to indicate t$at t$e num%er is a $eadecimal num%er. #ere are
eam*les o- num%ers )ritten in $eadecimal -orm;HE16
B16
#eadecimal 0 1 2 3 , 6 H 7 < B D E F
Decimal E?ui!alent0 1 2 3 , 6 H 7 < 10 11 12 13 1
1
,
Table : !exadecimal "umbers and their E#ui$alence to decimal numbers
,ecimal Binar# Octal e-adecimal
12610 11111102 1H67 HE16
1110 10112 137 B16
Table %: Summary of Examples
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 20/244
Introduction to Programming I 20
.riteitt$is)ay
1..* Conversions
+,8,4,+ $ecima& to 0inary 5 0inary to $ecima&
To con!ert a decimal num%er to %inary continuously di!ide t$e num%er %y 2 and get t$eremainder 4)$ic$ is eit$er 0 or 19 and get t$at num%er as a digit o- t$e %inary -orm o-t$e num%er. @et t$e ?uotient and di!ide t$at num%er again %y 2 and re*eat t$e )$ole*rocess until t$e ?uotient reac$es 0 or 1. e t$en get all t$e remainders starting -romt$e last remainder and t$e result is t$e %inary -orm o- t$e num%er.+&TE; For t$e last digit )$ic$ is already less t$an t$e di!isor 4)$ic$ is 29 ust co*y t$e!alue to t$e remainder *ortion.
For Example:12610 S G 2
uotient 4emainder
126 8 2 S 63 063 8 2 S 31 131 8 2 S 1, 11, 8 2 S H 1H 8 2 S 3 13 8 2 S 1 11 8 2 S 1
'o )riting t$e remainders -rom t$e %ottom u* )e get t$e %inary num%er 1111110.
To con!ert a %inary num%er to decimal )e multi*ly t$e %inary digit to R2 raised to t$e*osition o- t$e %inary num%erR. e t$en add all t$e *roducts to get t$e resulting decimalnum%er.
For Example:111111&2 ' ( 1&
)osition * + % 2 1 &
BinaryDigits
+ + + + + + 9
0 20 S 0
1 21 S 2
1 22 S
1 23S 7
1 2S 16
1 2, S 32
1 26 S 6
T&T=; 126
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 21/244
.riteitt$is)ay
.riteitt$is)ay
+,8,4,. $ecima& to Octa& 6or exadecima&75Octa& 6or exadecima&7 to$ecima&
on!erting decimal num%ers to &ctal or $eadecimal is %asically t$e same as con!erting
decimal to %inary. #o)e!er instead o- $a!ing 2 as t$e di!isor you re*lace it )it$ 74-oroctal9 or 16 4-or $eadecimal9.
For Example ,-ctal:12610 S G 7
uotient 4emainder
126 8 7 S 1, 61, 8 7 S 1 H1 8 7 S 1
'o )riting t$e remainders -rom t$e %ottom u* )e get t$e octal num%er 1H6:
For Example ,!exadecimal:12610 S G 16
uotient 4emainder 1 4e?ual to $e
126 8 16 S Hdigit E9
H 8 16 S H
'o )riting t$e remainders -rom t$e %ottom u* )e get t$e $eadecimal num%er HE+8
U U Uon!erting octal or $eadecimal num%ers is also t$e same as con!erting %inary num%ersto decimal. To do t$at )e )ill ust re*lace t$e %ase num%er 2 )it$ 7 -or &ctal and 16 -or$eadecimal.
For Example ,-ctal:1/*0 ' ( 1&
)osition 2 1 &
&ctal Digits + ; 8
6 70 S 6
H 71
S ,6
1 72S 6
T&T=; 126
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 22/244
For Example ,!exadecimal:/E 1* ' ( 1&
)osition 1 &
#e Digits ; E
1 160 S 1
H 161 S 112
T&T=; 126
+,8,4,- 0inary to Octa& 5 Octa& to 0inary
To con!ert -rom %inary num%ers to octal )e *artition t$e %inary num%er into grou*s o- 3digits 4-rom rig$t to le-t9 and *ad it )it$ >eros i- t$e num%er o- digits is not di!isi%le %y3. e t$en con!ert eac$ *artition into its corres*onding octal digit. T$e -ollo)ing is ata%le s$o)ing t$e %inary re*resentation o- eac$ octal digit.
Octal ,igit Binar#
4epresentation
0 000
1 001
2 010
3 011
100
, 101
6 110
H 111
Table +: -ctal igits and their corresponding binary represenation
For Example:111111&2 ' ( 0
5 5 1 1 1 1 1 1 5
+ ; 8
E?ui!alent octal num%er
on!erting octal num%ers to %inary is ust t$e o**osite o- )$at is gi!en a%o!e. 'im*lycon!ert eac$ octal digit into its %inary re*resentation 4gi!en t$e ta%le9 and concatenatet$em. T$e result is t$e %inary re*resentation.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 23/244
+,8,4,< 0inary to exadecima& 5 exadecima& to0inary
To con!ert -rom %inary num%ers to $eadecimal )e *artition t$e %inary num%er into
grou*s o- digits 4-rom rig$t to le-t9 and *ad it )it$ >eros i- t$e num%er o- digits is notdi!isi%le %y . e t$en con!ert eac$ *artition into its corres*onding $eadecimal digit.T$e -ollo)ing is a ta%le s$o)ing t$e %inary re*resentation o- eac$ $eadecimal digit.
e-adecimal
,igit
Binar#
4epresentation
0 0000
1 0001
2 0010
3 0011
0100
, 0101
6 0110
H 0111
7 1000
< 1001
1010
B 1011
1100
D 1101
E 1110
F 1111
Table *: !exadecimal igits and their corresponding binary represenation
For Example:111111&2 ' ( 1*
5 1 1 1 1 1 1 5
; E
E?ui!alent #eadecimalnum%er
on!erting $eadecimal num%ers to %inary is ust t$e o**osite o- )$at is gi!en a%o!e.'im*ly con!ert eac$ $eadecimal digit into its %inary re*resentation 4gi!en t$e ta%le9and concatenate t$em. T$e result is t$e %inary re*resentation.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 24/244
1.6 0-ercises
1.6.1 riting /lgorit(ms
@i!en t$e -ollo)ing set o- tas:s create an algorit$m to accom*lis$ t$e -ollo)ing tas:s.ou may )rite your algorit$ms using *seudocodes or you can use -lo)c$arts.
1. Ba:ing Bread
2. =ogging into your la%oratorys com*uter
3. @etting t$e a!erage o- t$ree num%ers
1.6.2 umber Conversions
on!ert t$e -ollo)ing num%ers;
1. 1<7010 to %inary $eadecimal and octal
2. 10010011012 to decimal $eadecimal and octal
3. H67 to %inary $eadecimal and decimal
. 3F16 to %inary decimal and octal
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 25/244
. Introduction to =a)a
2.1 ObjectivesIn t$is section )e )ill %e discussing a little %it o- Ja!a $istory and )$at is Ja!a
Tec$nology. e )ill also discuss t$e *$ases t$at a Ja!a *rogram undergoes.
t t$e end o- t$e lesson t$e student s$ould %e a%le to;
• Descri%e t$e -eatures o- Ja!a tec$nology suc$ as t$e Ja!a !irtual mac$ine gar%age
collection and code security
• Descri%e t$e di--erent *$ases o- a Ja!a *rogram
2.2 7ava Bac8ground
2.2.1 / little Bit of istor#
Ja!a )as created in 1<<1 %y James @osling et al. o- 'un (icrosystems. Initially called&a: in $onor o- t$e tree outside @oslings )indo) its name )as c$anged to Ja!a%ecause t$ere )as already a language called &a:.
T$e original moti!ation -or Ja!a )as t$e need -or *lat-orm inde*endent language t$atcould %e em%edded in !arious consumer electronic *roducts li:e toasters andre-rigerators. &ne o- t$e -irst *roects de!elo*ed using Ja!a )as a *ersonal $and$eldremote control named 'tar H.
t a%out t$e same time t$e orld ide e% and t$e Internet )ere gaining *o*ularity.@osling et. al. reali>ed t$at Ja!a could %e used -or Internet *rogramming.
2.2.2 (at is 7ava +ec(nolog#)
.,.,.,+ A programming &anguage
s a programming &anguage Ja!a can create all :inds o- a**lications t$at you couldcreate using any con!entional *rogramming language.
.,.,.,. A de)e&opment en)ironments a de)e&opment en)ironment Ja!a tec$nology *ro!ides you )it$ a large suite o-tools; a com*iler an inter*reter a documentation generator a class -ile *ac:aging tooland so on.
.,.,.,- An app&ication en)ironment
Ja!a tec$nology a**lications are ty*ically general*ur*ose *rograms t$at run on anymac$ine )$ere t$e =a)a runtime en)ironment 4J"E9 is installed.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 26/244
.,.,.,< A dep&oyment en)ironment
T$ere are t!o main dep&oyment en)ironments2 First> the =RE su**lied %y t$e Ja!a2
'o-t)are De!elo*ment Ait 4'DA9 contains t$e com*lete set o- class -iles -or all t$e Ja!atec$nology *ac:ages )$ic$ includes %asic language classes @I com*onent classesand so on. T$e ot$er main de*loyment en!ironment is on your !eb bro!ser. (ostcommercial %ro)sers su**ly a Ja!a tec$nology inter*reter and runtime en!ironment.
2.2.3 Some 9eatures of 7ava
.,.,-,+ The =a)a *irtua& Machine
T$e =a)a *irtua& Machine is an imaginary mac$ine t$at is im*lemented %y emulatingso-t)are on a real mac$ine. T$e JV( *ro!ides t$e $ard)are *lat-orm s*eci-ications to)$ic$ you com*ile all Ja!a tec$nology code. T$is s*eci-ication ena%les t$e Ja!a so-t)are
to %e *lat-orminde*endent %ecause t$e com*ilation is done -or a generic mac$ine:no)n as t$e JV(.
bytecode is a s*ecial mac$ine language t$at can %e understood %y t$e =a)a *irtua&Machine 6=*M7. T$e %ytecode is inde*endent o- any *articular com*uter $ard)are soany com*uter )it$ a Ja!a inter*reter can eecute t$e com*iled Ja!a *rogram no matter)$at ty*e o- com*uter t$e *rogram )as com*iled on.
.,.,-,. ?arbage "o&&ection
(any *rogramming languages allo)s a *rogrammer to allocate memory during runtime.#o)e!er a-ter using t$at allocated memory t$ere s$ould %e a )ay to deallocate t$atmemory %loc: in order -or ot$er *rograms to use it again. In KK and ot$erlanguages t$e *rogrammer is res*onsi%le -or t$is. T$is can %e di--icult at times sincet$ere can %e instances )$erein t$e *rogrammers -orget to deallocate memory andt$ere-or result to )$at )e call memory lea:s.
In Ja!a t$e *rogrammer is -reed -rom t$e %urden o- $a!ing to deallocate t$at memoryt$emsel!es %y $a!ing )$at )e call t$e garbage co&&ection thread. T$e gar%agecollection t$read is res*onsi%le -or -reeing any memory t$at can %e -reed. T$is $a**ensautomatically during t$e li-etime o- t$e Ja!a *rogram.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 27/244
.,.,-,- "ode Security
ode security is attained in Ja!a t$roug$ t$e im*lementation o- its =a)a RuntimeEn)ironment 6=RE7, T$e J"E runs code com*iled -or a JV( and *er-orms class loading
4t$roug$ t$e class loader9 code !eri-ication 4t$roug$ t$e %ytecode !eri-ier9 and -inallycode eecution.
T$e "&ass Loader is res*onsi%le -or loading all classes needed -or t$e Ja!a *rogram. Itadds security %y se*arating t$e names*aces -or t$e classes o- t$e local -ile system -romt$ose t$at are im*orted -rom net)or: sources. T$is limits any Troan $orse a**licationssince local classes are al)ays loaded -irst. -ter loading all t$e classes t$e memorylayout o- t$e eecuta%le is t$en determined. T$is adds *rotection against unaut$ori>edaccess to restricted areas o- t$e code since t$e memory layout is determined duringruntime.
-ter loading t$e class and layouting o- memory t$e bytecode )eri#ier t$en tests t$e
-ormat o- t$e code -ragments and c$ec:s t$e code -ragments -or illegal code t$at can!iolate access rig$ts to o%ects.
-ter all o- t$ese $a!e %een done t$e code is t$en -inally eecuted.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 28/244
2.2.% $(ases of a 7ava $rogram
T$e -ollo)ing -igure descri%es t$e *rocess o- com*iling and eecuting a Ja!a *rogram.
Figure 2.1: )hases of a a$a )rogram
T$e -irst ste* in creating a Ja!a *rogram is %y )riting your *rograms in a tet editor.Eam*les o- tet editors you can use are note*ad !i emacs etc. T$is -ile is stored in adis: -ile )it$ t$e etension .java.
-ter creating and sa!ing your Ja!a *rogram com*ile t$e *rogram %y using t$e Ja!a
om*iler. T$e out*ut o- t$is *rocess is a -ile o- Ja!a bytecodes )it$ t$e -ile etension.class.
T$e .class -ile is t$en inter*reted %y t$e Ja!a inter*reter t$at con!erts t$e %ytecodes
into t$e mac$ine language o- t$e *articular com*uter you are using.
+as8 +ool to use Output
rite t$e *rogram ny tet editor File )it$ .a!a etension
om*ile t$e *rogram Ja!a om*iler File )it$ .class etension
4Ja!a %ytecodes9
"un t$e *rogram Ja!a Inter*reter Program &ut*ut
Table /: Summary of )hases of a a$a )rogram
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 29/244
- ?etting to %no! your Programming
En)ironment3.1 ObjectivesIn t$is section )e )ill %e discussing on $o) to )rite com*ile and run Ja!a *rograms.T$ere are t)o )ays o- doing t$is t$e -irst one is %y using a console and a tet editor.T$e second one is %y using +etBeans )$ic$ is an Integrated $e)e&opmentEn)ironment or I$E.
t t$e end o- t$e lesson t$e student s$ould %e a%le to;
• reate a Ja!a *rogram using tet editor and console in t$e =inu 4%untu Da**er9
en!ironment
• Di--erentiate %et)een syntaerrors and runtime errors
• reate a Ja!a *rogram using +etBeans
3.2 Introductionn IDE is a *rogramming en!ironment integrated into a so-t)are a**lication t$at*ro!ides a @I %uilder a tet or code editor a com*iler and8or inter*reter and ade%ugger.
T$is tutorial uses %untu Da**er as t$e o*erating system. (a:e sure t$at %e-ore you dot$is tutorial you $a!e installed Ja!a and +etBeans in your system. For instructions on$o) to install Ja!a and +etBeans *lease re-er to Appendix A. For t$e indo)s /P!ersion o- t$is section *lease re-er to Appendix 0.
Be-ore going into details let us -irst ta:e a loo: at t$e -irst Ja!a *rogram you )ill %e)riting.
3.3 M# 9irst 7ava $rogram
public class Hello{
/*** My first java program*/public static void main(String[] args {
//prints t!e string "Hello #orld" on screenSystem.out.println("Hello #orld$"%
&&
Be-ore )e try to e*lain )$at t$e *rogram means lets -irst try to )rite t$is *rogram in a
-ile and try to run it.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 30/244
Introduction to Programming I 30
3.% :sing a +e-t 0ditor and ConsoleFor t$is eam*le )e )ill %e using a tet editor to edit t$e Ja!a source code. ou )ill also
need to o*en t$e Terminal )indo) to com*ile and eecute your Ja!a *rograms.
Step +2 Start the Text Editor
To start t$e Tet Editor in =inu clic: on **licationsccessoriesTet Editor.
Figure .1: Text Editor 3pplication in 4inux
Step .2 Open Termina&
To o*en Terminal in =inu clic: on **lications ccessories Terminal.
Figure .2: Terminal in 4inux
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 31/244
Introduction to Programming I 31
Step -2 'rite your the source code o# your =a)a program in the Text Editor
Figure .: 5riting the Source Code with the Text Editor
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 32/244
Introduction to Programming I 32
Step <2 Sa)e your =a)a Programe )ill sa!e our *rogram on a -ile named R#ello.a!aR and )e )ill %e sa!ing it inside a-older named (JVP"&@"('.
To o*en t$e Sa)e dialog %o clic: on t$e File menu -ound on t$e menu%ar and t$enclic: on 'a!e.
-ter doing t$e *rocedure descri%ed a%o!e a dialog %o )ill a**ear as s$o)n in Figure%elo).
Figure .%: Sa$e 3s ialog
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 33/244
Introduction to Programming I 33
lic: on t$e %ro)se %utton and t$en clic: on t$e reate Folder %utton.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 34/244
Introduction to Programming I 3
+ame t$e ne) -older (JVP"&@"('. +o) clic: on t$e (JP"&@"(' -older inorder to get inside t$at -older. ou )ill see a similar -igure as s$o)n %elo) a-ter youclic:ed on (JVP"&@"('. T$e -older s$ould %e em*ty -or no) since its a ne)lycreated -older and )e $a!ent sa!ed anyt$ing in it yet.
+o) in t$e 'election tet%o ty*e in t$e -ilename o- your *rogram )$ic$ is
R#ello.a!aR and t$en clic: on t$e 'VE %utton.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 35/244
Introduction to Programming I 3,
+o) t$at you!e sa!ed your -ile notice $o) t$e title o- t$e -rame c$anges -rom RntitledDocument 1 4modi-ied9 L geditR to R#ello.a!a 4W8(JVP"&@"('9 geditR. Ta:enote t$at i- you )ant to ma:e c$anges in your -ile you can ust edit it and t$en sa!e itagain %y clic:ing on File 'a!e.
Figure .+: "ew 5indow 3fter Sa$ing
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 36/244
Introduction to Programming I 36
Step 42 "ompi&ing your program+o) t$e net ste* is to com*ile your *rogram. @o to t$e Terminal )indo) )e usto*ened a )$ile ago.
Ty*ically )$en you o*en t$e terminal )indo) it o*ens u* and ta:es you directly to)$at is called your home #o&der. To see )$at is inside t$at $ome -older ty*e &s andt$en *ress E+TE". $at you )ill see is a list o- -iles and -olders inside your $ome -older.
+o) you can see $ere t$at t$ere is a -older named R(JVP"&@"('R )$ic$ )e $a!ecreated a )$ile ago and )$ere )e sa!ed our #ello.a!a *rogram. +o) lets go insidet$at directory.
To go inside a directory you ty*e in t$e command; cd @directory name, T$e RcdRcommand stands -or c$ange directory. In t$is case since t$e name o- our directory is(JVP"&@"(' you ty*e in; cd MB=A*APRO?RAMS
Figure .*: Changing the irectory
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 37/244
Introduction to Programming I 3H
&nce inside t$e -older )$ere your Ja!a *rograms are let us no) start com*iling yourJa!a *rogram. Ta:e note t$at you s$ould ma:e sure t$at t$e -ile is inside t$e -older)$ere you are in. In order to do t$at eecute t$e RlsR command again to see i- your -ileis inside t$at -older.
Figure ./: 4ist of Files 6nside the "ew irectory
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 38/244
Introduction to Programming I 37
To com*ile a Ja!a *rogram )e ty*e in t$e command; Ca)ac @#i&ename. 'o in t$iscase ty*e in; Ca)ac e&&o,Ca)a,
Figure .0: Compiling a$a File
During com*ilation a!ac adds a -ile to t$e dis: called @#i&ename,c&ass> or in t$is case
e&&o,c&ass )$ic$ is t$e actual %ytecode.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 39/244
Introduction to Programming I 3<
Step 82 Running the Program+o) assuming t$at t$ere are no *ro%lems during com*ilation 4)ell e*lore more o- t$e*ro%lems encountered during com*ilation in t$e net section9 )e are no) ready to runyour *rogram.
To run your Ja!a *rogram ty*e in t$e command; Ca)a @#i&ename !ithout theextension so in t$e case o- our eam*le ty*e in; Ca)a e&&o
ou can see on t$e screen t$at you $a!e ust run your -irst Ja!a *rogram t$at *rints t$emessage R#ello )orldR.
Figure .7: 8unning Class File
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 40/244
Introduction to Programming I 0
3.%.1 0rrors
$at )e!e s$o)n so -ar is a Ja!a *rogram )$erein )e didnt encounter any *ro%lems incom*iling and running. #o)e!er t$is is not al)ays t$e case. s )$at )e $a!e discussed
in t$e -irst *art o- t$is course )e usually encounter errors along t$e )ay.
s discussed %e-ore t$ere are t)o ty*es o- errors. T$e -irst one is a com*iletime erroror also called as synta error. T$e second one is t$e runtime error.
-,<,+,+ Syntax Errors
'ynta errors are usually ty*ing errors. ou may $a!e miss*elled a command in Ja!a or-orgot to )rite a semicolon at t$e end o- a statement. Ja!a attem*ts to isolate t$e error%y dis*laying t$e line o- code and *ointing to t$e -irst incorrect c$aracter in t$at line.#o)e!er t$e *ro%lem may not %e at t$e eact *oint.
&t$er common mista:es are in ca*itali>ation s*elling t$e use o- incorrect s*ecialc$aracters and omission o- correct *unctuation.
=ets ta:e -or eam*le our #ello.a!a *rogram )$erein )e intentionally omit t$esemicolon at one statement and )e try to ty*e t$e incorrect s*elling o- a command.
Figure .1&: Source Code 5ith Errors
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 41/244
Introduction to Programming I 1
'ee t$e error messages generated a-ter com*iling t$e *rogram. T$e -irst error messagesuggests t$at t$ere is an error in line 6 o- your *rogram. It *ointed to t$e net )orda-ter t$e statict )$ic$ s$ould %e s*elled as static.
T$e second error message suggests t$at t$ere is a missing semicolon a-ter yourstatement.
Figure .11: Compiling the Source Code with Errors
s a rule o- t$um% i- you encounter a lot o- error messages try to correct t$e -irstmista:e in a long list and try to com*ile t$e *rogram again. Doing so may reduce t$etotal num%er o- errors dramatically.
-,<,+,. Run3time Errors
"untime errors are errors t$at )ill not dis*lay until you run or eecute your *rogram.E!en *rograms t$at com*ile success-ully may dis*lay )rong ans)ers i- t$e *rogrammer$as not t$oug$t t$roug$ t$e logical *rocesses and structures o- t$e *rogram.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 42/244
Introduction to Programming I 2
3.* :sing etBeans+o) t$at )e!e tried doing our *rograms t$e com*licated )ay lets no) see $o) to do
all t$e *rocesses )e!e descri%ed in t$e *re!ious sections %y using ust one a**lication.
In t$is *art o- t$e lesson )e )ill %e using /et0eans )$ic$ is an Integrated$e)e&opment En)ironment or I$E. n IDE is a *rogramming en!ironment integratedinto a so-t)are a**lication t$at *ro!ides a @I %uilder a tet or code editor a com*ilerand8or inter*reter and a de%ugger.
Step +2 Run /et0eansT$ere are t)o )ays to run +etBeans. &ne is t$roug$ commandline using terminal or %y
st clic:ing on t$e s$ortcut %utton -ound on t$e des:to*.
To run +etBeans using commandline. &*en terminal 4see ste*s on $o) to run terminalin t$e *re!ious discussion9 and ty*e; netbeans
Figure .12: 8unning "et9eans with the Command4ine
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 43/244
Introduction to Programming I 3
T$e second )ay to run +etBeans is %y clic:ing on t$e s$ortcut icon -ound on yourDes:to*.
Figure .1: 8unning "et9eans using shortcut icon on des;top
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 44/244
Introduction to Programming I
-ter you!e o*en +etBeans IDE you )ill see a gra*$ical user inter-ace 4@I9 similar to)$at is s$o)n %elo).
Figure .1%: 5indow 3fter -penning "et9eans
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 45/244
Introduction to Programming I ,
Step .2 Ma%e a proCect+o) lets -irst ma:e a *roect. lic: on File +e) Proect. -ter doing t$is a +e)Proect dialog )ill a**ear. +o) clic: on Ja!a **lication and clic: on t$e +E/T %utton.
Figure .1+: Choosing )ro<ect Type
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 46/244
Introduction to Programming I 6
+o) a +e) **lication dialog )ill a**ear.
Figure .1*: Setting the )ro<ect 6nformation
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 47/244
Introduction to Programming I H
+o) try to c$ange t$e **lication =ocation %y clic:ing on t$e B"&'E %utton. Proect =ocation dialog )ill t$en a**ear. Dou%leclic: on your $ome -older.
Figure .1/: Setting the )ro<ect 4ocation
T$e contents o- t$e root -older is t$en dis*layed. +o) dou%leclic: on t$e
(JVP"&@"(' -older and clic: on t$e &PE+ %utton.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 48/244
Introduction to Programming I 7
'ee no) t$at t$e Proect =ocation and Proect Folder is c$anged to
8$ome8-lorence8(JVP"&@"('.
Finally on t$e reate (ain lass tet-ield ty*e in #ello as t$e main class name andt$en clic: on t$e FI+I'# %utton.
Figure .10: 5indow after Setting the )ro<ect 4ocation to =>3?3)8-@83=SASetting the =ain Class of the)ro<ect to !ello
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 49/244
Introduction to Programming I <
Step -2 Type in your programBe-ore ty*ing in your *rogram let us -irst descri%e t$e main )indo) a-ter creating t$e*roect.
s s$o)n %elo) +etBeans automatically creates t$e %asic code -or your Ja!a *rogram.ou can ust add your o)n statements to t$e generated code. &n t$e le-t side o- t$e)indo) you can see a list o- -olders and -iles t$at +etBeans generated a-ter creating t$e*roect. T$is can all %e -ound in your (JVP"&@"(' -older )$ere you set t$eProect location.
Figure .17: ?iew of the Created )ro<ect
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 50/244
Introduction to Programming I ,0
+o) try to modi-y t$e code generated %y +etBeans. Ignore t$e ot$er *arts o- t$e*rogram -or no) as )e )ill e*lain t$e details o- t$e code later. Insert t$e code;
System.out.println("Hello #orld$"%
a-ter t$e statement 88T&D& code a**lication logic $ere.
Figure .2&: 6nserting the Code
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 51/244
Introduction to Programming I ,1
Step <2 "ompi&e your program+o) to com*ile your *rogram ust clic: on Build Build (ain Proect. &r you couldalso use t$e s$ortcut %utton to com*ile your code.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 52/244
Introduction to Programming I ,2
I- t$ere are no errors in your *rogram you )ill see a %uild success-ul message on t$eout*ut )indo).
Figure .21: ?iew after a Successful Compilation
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 53/244
Introduction to Programming I ,3
Step 42 Run your programTo run your *rogram clic: on "un "un (ain Proect. &r you could also use t$es$ortcut %utton to run your *rogram.
Figure .22: 8unning with "et9eans
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 54/244
Introduction to Programming I ,
T$e out*ut o- your *rogram is dis*layed in t$e out*ut )indo).
Figure .2: ?iew after a Successful 8un
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 55/244
Introduction to Programming I ,,
3. 0-ercises
3..1 ello orld;
sing +etBeans create a class named; Xour+ameY. T$e *rogram s$ould out*ut on t$escreen;
'elcome to ava )rogramming [our+ame]$$$
3..2 +(e +ree
sing +etBeans create a class named; TheTree. T$e *rogram s$ould out*ut t$e-ollo)ing lines on t$e screen;
, t!in- t!at , s!all never see
a poem as lovely as a tree. tree #!ose !ungry mout! is pressedgainst t!e 0art!1s s#eet flo#ing breast.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 56/244
Introduction to Programming I ,6
< Programming Fundamenta&s
%.1 ObjectivesIn t$is section )e )ill %e discussing t$e %asic *arts o- a Ja!a *rogram. e )ill start %ytrying to e*lain t$e %asic *arts o- t$e #ello.a!a *rogram introduced in t$e *re!ioussection. e )ill also %e discussing some coding guidelines or code con!entions along t$e)ay to $el* in e--ecti!ely )riting reada%le *rograms.
t t$e end o- t$e lesson t$e student s$ould %e a%le to;
• Identi-y t$e %asic *arts o- a Ja!a *rogram
• Di--erentiate among Ja!a literals *rimiti!e data ty*es !aria%le ty*es identi-iers
and o*erators
• De!elo* a sim*le !alid Ja!a *rogram using t$e conce*ts learned in t$is c$a*ter
%.2 ,issecting m# first 7ava
program+o) )ell try to t$e dissect your -irst Ja!a *rogram;
public class Hello{
/**
* My first java program*/public static void main(String[] args {
//prints t!e string "Hello #orld" on screenSystem.out.println("Hello #orld$"%
&&
T$e -irst line o- t$e code
public class Hello
indicates t$e name o- t$e class )$ic$ is e&&o, In Ja!a all code s$ould %e *laced insidea class declaration. e do t$is %y using t$e c&ass :ey)ord. In addition t$e class uses anaccess specifier pub&ic> )$ic$ indicates t$at our class in accessi%le to ot$er classes -romot$er *ac:ages 4*ac:ages are a collection o- classes9. e )ill %e co!ering *ac:ages andaccess s*eci-iers later.
T$e net line )$ic$ contains a curly %race Z indicates t$e start o- a %loc:. In t$is code)e *laced t$e curly %race at t$e net line a-ter t$e class declaration $o)e!er )e canalso *lace t$is net to t$e -irst line o- our code. 'o )e could actually )rite our code as;
public class Hello
Zor
public class Hello {
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 57/244
Introduction to Programming I ,H
T$e net t$ree lines indicates a Ja!a comment. comment is somet$ing used todocument a *art o- a code. It is not *art o- t$e *rogram itsel- %ut used -ordocumentation *ur*oses. It is good *rogramming *ractice to add comments to yourcode.
/*** My first java program
U8
comment is indicated %y t$e delimiters 5DQ and D5Q. nyt$ing )it$in t$ese delimitersare ignored %y t$e Ja!a com*iler and are treated as comments.T$e net line
public static void main(String[] args {
or can also %e )ritten as
public static void main(String[] args{
indicates t$e name o- one met$od in e&&o )$ic$ is t$e main met$od. T$e main met$odis t$e starting *oint o- a Ja!a *rogram. ll *rograms ece*t **lets )ritten in Ja!a start)it$ t$e main met$od. (a:e sure to -ollo) t$e eact signature.
T$e net line is also a Ja!a comment
//prints t!e string "Hello #orld" on screen
+o) )e learned t)o )ays o- creating comments. T$e -irst one is %y *lacing t$e
comment inside 8U and U8 and t$e ot$er one is %y )riting 88 at t$e start o- t$ecomment.
T$e net line
System.out.println("Hello #orld$"%
*rints t$e tet #ello orldQ on screen. T$e command 'ystem.out.*rintln49 *rints t$etet enclosed %y ?uotation on t$e screen.
T$e last t)o lines )$ic$ contains t$e t)o curly %races is used to close t$e main met$odand c&ass res*ecti!ely.
Coding<uidelines
1. >our a$a programs should always end with the .javaextension.2. Filenames should matc( the name of your public class. So for exampleB if the
name of your public class is ello= you should sa$e it in a file called ello.java.. >ou should write comments in your code explaining what a certain class doesB
or what a certain method do.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 58/244
Introduction to Programming I ,7
%.3 7ava Commentsomments are notes )ritten to a code -or documentation *ur*oses. T$ose tet are not
*art o- t$e *rogram and does not a--ect t$e -lo) o- t$e *rogram.
Ja!a su**orts t$ree ty*es o- comments; KKstyle single line comments stylemultiline comments and s*ecial a!adoc comments.
%.3.1 C>>"St#le Comments
KK 'tyle comments starts )it$ 88. ll t$e tet a-ter 88 are treated as comments. Foream*le
// 2!is is a 344 style or single line comments
%.3.2 C"St#le Comments
style comments or also called multiline comments starts )it$ a 8U and ends )it$ a U8.ll tet in %et)een t$e t)o delimeters are treated as comments. nli:e KK stylecomments it can s*an multi*le lines. For eam*le
/* t!is is an e5maple of a3 style or multiline comments */
%.3.3 Special 7avadoc Comments
'*ecial Ja!adoc comments are used -or generating an #T(= documentation -or your Ja!a*rograms. ou can create a!adoc comments %y starting t$e line )it$ 8UU and ending it)it$ U8. =i:e style comments it can also s*an lines. It can also contain certain tags to
add more in-ormation to your comments. For eam*le
/**2!is is an e5ample of special java doc comments used for 6ngenerating an !tml documentation. ,t uses tags li-e78aut!or 9lorence :alagtas8version ;.<*/
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 59/244
Introduction to Programming I ,<
%.% 7ava Statements and bloc8s statement is one or more lines o- code terminated %y a semicolon. n eam*le o- a
single statement is
System.out.println4#ello )orldQ9[
b&oc% is one or more statements %ounded %y an o*ening and closing curly %races t$atgrou*s t$e statements as one unit. Bloc: statements can %e nested inde-initely. nyamount o- )$ite s*ace is allo)ed. n eam*le o- a %loc: is
public static void main( String[] args {System.out.println("Hello"%System.out.println("#orld"%
&
Coding <uidelines
1. 6n creating bloc;sB you can place the opening curly brace in line with thestatementB li;e for exampleB
public static $oid main, StringD args
or you can place the curly brace on the next lineB
li;eB public static $oid main, StringD args
2. >ou should indent the next statements after the start of a bloc;Bfor
exampleB public static $oid main, StringD args System.out.println,!elloGSystem.out.println,worldG
H
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 60/244
Introduction to Programming I 60
%.* 7ava IdentifiersIdenti-iers are to:ens t$at re*resent names o- !aria%les met$ods classes etc. Eam*les
o- identi-iers are; #ello main 'ystem out.
Ja!a identi-iers are c a s e s e n s i ti ! e . T$is means t$at t$e identi-ier; e&&o is not t$e sameas he&&o. Identi-iers must %egin )it$ eit$er a letter an underscore CQ or a dollar sign
\Q. =etters may %e lo)er or u**er case. 'u%se?uent c$aracters may use num%ers 0 to<.
Identi-iers cannot use Ja!a :ey)ords li:e class *u%lic !oid etc. e )ill discuss morea%out Ja!a :ey)ords later.
Coding<uidelines
1. For names of classesB capitaliIe the first letter of the class name. For namesof methods and $ariablesB the first letter of the word should start with a smallletter.For example:
+ his I s /n0 xampleOf C lass ame
t his I s /n0 xampleOf M ethod ame
2. 6n case of multiword identifiersB use capital letters to indicate the start of theword except the first word. For exampleB char3rrayB file"umberB Class"ame.
. 3$oid using underscores at the start of the identifier such as Jread or Jwrite.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 61/244
Introduction to Programming I 61
%. 7ava ?e#!ordsAey)ords are *rede-ined identi-iers reser!ed %y Ja!a -or a s*eci-ic *ur*ose. ou cannot
use :ey)ords as names -or your !aria%les classes met$ods ]etc. #ere is a list o- t$eJa!a Aey)ords.
Figure %.1: a$a Key 5ords
e )ill try to discuss all t$e meanings o- t$ese :ey)ords and $o) t$ey are used in our
Ja!a *rograms as )e go along t$e )ay.
/ote2 true false and null are not :ey)ords %ut t$ey are reser!ed )ords so you
cannot use t$em as names in your *rograms eit$er
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 62/244
Introduction to Programming I 62
%.6 7ava &iterals=iterals are to:ens t$at do not c$ange or are constant. T$e di--erent ty*es o- literals in
Ja!a are; Integer =iterals FloatingPoint =iterals Boolean =iterals $aracter =iterals and'tring =iterals.
%.6.1 Integer &iterals
Integer literals come in di--erent -ormats; decima& 4%ase 109 hexadecima& 4%ase 169and octa& 4%ase 79. In using integer literals in our *rogram )e $a!e to -ollo) somes*ecial notations.
For decimal num%ers )e $a!e no s*ecial notations. e ust )rite a decimal num%er as itis. For $eadecimal num%ers it s$ould %e *receeded %y 0Q or 0/Q. For octals t$ey are*receeded %y 0Q.
For eam*le consider t$e num%er +.. Its decimal re*resentation is +. )$ile in$eadecimal it is 9x" and in octal it is e?ui!alent to 9+<.
Integer literals de-ault to t$e data ty*e int. n int is a signed 32%it !alue. In somecases you may )is$ to -orce integer literal to t$e data ty*e &ong %y a**ending t$e lQ or
=Q c$aracter. long is a signed 6%it !alue. e )ill co!er more on data ty*es later.
%.6.2 9loating"$oint &iterals
Floating *oint literals re*resent decimals )it$ -ractional *arts. n eam*le is 3.11,.Floating *oint literals can %e e*ressed in standard or scienti-ic notations. For eam*le,73., is in standard notation )$ile ,.73,e2 is in scienti-ic notation.
Floating *oint literals de-ault to t$e data ty*e doub&e )$ic$ is a 6%it !alue. To use asmaller *recision 432%it9 #&oat ust a**end t$e -Q or FQ c$aracter.
%.6.3 Boolean &iterals
Boolean literals $a!e only t)o !alues true or #a&se.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 63/244
Introduction to Programming I 63
%.6.% C(aracter &iterals
$aracter =iterals re*resent single nicode c$aracters. nicode c$aracter is a 16%itc$aracter set t$at re*laces t$e 7%it 'II c$aracter set. nicode allo)s t$e inclusion o-
sym%ols and s*ecial c$aracters -rom ot$er languages.
To use a c$aracter literal enclose t$e c$aracter in single ?uote delimiters. For eam*let$e letter a is re*resented as a.
To use s*ecial c$aracters suc$ as a ne)line c$aracter a %ac:slas$ is used -ollo)ed %yt$e c$aracter code. For eam*le ^_n` -or t$e ne)line c$aracter ^_r` -or t$e carriagereturn ^_%` -or %ac:s*ace.
%.6.* String &iterals
'tring literals re*resent multi*le c$aracters and are enclosed %y dou%le ?uotes. neam*le o- a string literal is Ge&&o 'or&dH,
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 64/244
Introduction to Programming I 6
%.@ $rimitive data t#pesT$e Ja!a *rogramming language de-ines eig$t *rimiti!e data ty*es. T$e -ollo)ing are
%oolean 4-or logical9 c$ar 4-or tetual9 %yte s$ort int long 4integral9 dou%le and -loat4-loating *oint9.
%[email protected] &ogical " boolean
%oolean data ty*e re*resents t)o states; tru e and -a l s e . n eam*le is
boolean result = true%
T$e eam*le s$o)n a%o!e declares a !aria%le named resu&t as boo&ean ty*e andassigns it a !alue o- true.
%[email protected] +e-tual A c(ar
c$aracter data ty*e 4c$ar9 re*resents a single nicode c$aracter. It must $a!e itsliteral enclosed in single ?uotes4` `9. For eam*le
>a1 //2!e letter a>6t1 // tab
To re*resent s*ecial c$aracters li:e 4single ?uotes9 or R 4dou%le ?uotes9 use t$e esca*ec$aracter _. For eam*le
?\'? //for single @uotes?\"? //for double @uotes
lt$oug$ 'tring is not a *rimiti!e data ty*e 4it is a lass9 )e )ill ust introduce 'tringin t$is section. 'tring re*resents a data ty*e t$at contains multi*le c$aracters. It isnot a primiti)e data type> it is a c&ass, It $as it`s literal enclosed in dou%le ?uotes4Q9.
For eam*le
String message=AHello #orld$B
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 65/244
Introduction to Programming I 6,
%[email protected] Integral A b#te= s(ort= int long
Integral data ty*es in Ja!a uses t$ree -orms L decimal octal or $eadecimal. Eam*lesare
< //2!e decimal value <CDD //2!e leading C indicates an octal valueC5:33 //2!e leading C5 indicates a !e5adecimal value
Integral ty*es $as i n t as de-ault data ty*e. ou can de-ine its l o n g !alue %y a**endingt$e letter l or =. Integral data ty*e $a!e t$e -ollo)ing ranges;
Integer
&engt(ame or +#pe 4ange
7 %its %yte 2H to 2H1
16 %its s$ort 21,
to 21,
1
32 %its int 231 to 2311
6 %its long 263
to 263
1
Table 0: 6ntegral types and their ranges
Coding <uidelines6n defining a long $alueB a lowercase 4 is not recommended because it is hard to
distinguish from the digit 1.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 66/244
Introduction to Programming I 66
%.@.% 9loating $oint A float and double
Floating *oint ty*es $as do u %l e as de-ault data ty*e. Floating*oint literal includes eit$era decimal *oint or one o- t$e -ollo)ing
0 or e //(add e5ponential value9 or f //(floatE or d //(double
Eam*les are
F.;G // simple floatingpoint value (a doubleI.C<0<F // large floatingpoint value<.D;J9 // simple float siKe value;<F.G04FCIE // large double value #it! redundant E
In t$e eam*le s$o)n a%o!e t$e 23 a-ter t$e E in t$e second eam*le is im*licitly
*ositi!e. T$at eam*le is e?ui!alent to 6.02EK23. Floating*oint data ty*es $a!e t$e-ollo)ing ranges;
9loat &engt( ame or +#pe 4ange
32 %its -loat 231 to 2311
6 %its dou%le 263 to 2631
Table 7: Floating point types and their ranges
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 67/244
Introduction to Programming I 6H
%. Dariables )ariab&e is an item o- data used to store state o- o%ects.
!aria%le $as a data type and a name. T$e data type indicates t$e ty*e o- !alue t$att$e !aria%le can $old. T$e )ariab&e name must -ollo) rules -or identi-iers.
%..1 ,eclaring and InitialiEing Dariables
To declare a !aria%le is as -ollo)s
<data type> <name> [=initial value];
/ote2 Values enclosed in are re?uired !alues )$ile t$ose !alues enclosed in XY areo*tional.
#ere is a sam*le *rogram t$at declares and initiali>es some !aria%les
public class LariableSamples{
public static void main( String[] args {//declare a data type #it! variable name// result and boolean data typeboolean result%
//declare a data type #it! variable name// option and char data typec!ar option%option = ?3?% //assign ?3? to option
//declare a data type #it! variable name//grade, double data type and initialiKed//to C.Cdouble grade = C.C%
&&
Coding <uidelines
1. 6t always good to initialiEe your $ariables as you declare them.2. Lse descriptive names for your $ariables. 4i;e for exampleB if you want to ha$e
a $ariable that contains a grade for a studentB name it asB grade and not <ust somerandom letters you choose.
. eclare one $ariable per line of code. For exampleB the $ariabledeclarationsB double exam'&Gdouble #uiI'1&G
double grade ' &Gis preferred o$er the declarationB
double exam'&B #uiI'1&B grade'&G
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 68/244
Introduction to Programming I 67
%..2 Outputting Dariable ,ata
In order to out*ut t$e !alue o- a certain !aria%le )e can use t$e -ollo)ing commands
System.out.println(System.out.print(
#eres a sam*le *rogram
public class utputLariable{
public static void main( String[] args {int value = ;C%c!ar 5%5 = >1%
System.out.println( value %System.out.println( A2!e value of 5=A 4 5 %
&&
T$e *rogram )ill out*ut t$e -ollo)ing tet on screen
;C2!e value of 5=
%..3 S#stem.out.printlnFG vs. S#stem.out.printFG
$at is t$e di--erence %et)een t$e commands 'ystem.out.*rintln49 and'ystem.out.*rint49G T$e -irst one a**ends a ne)line at t$e end o- t$e data to out*ut)$ile t$e latter doesnt.
onsider t$e statements
System.out.print("Hello "%System.out.print("#orld$"%
T$ese statements )ill out*ut t$e -ollo)ing on t$e screen
Hello #orld$
+o) consider t$e -ollo)ing statements
System.out.println("Hello "%System.out.println("#orld$"%
T$ese statements )ill out*ut t$e -ollo)ing on t$e screen
Hello#orld$
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 69/244
Introduction to Programming I 6<
%..% 4eference Dariables vs. $rimitiveDariables
e )ill no) di--erentiate t$e t)o ty*es o- !aria%les t$at Ja!a *rograms $a!e. T$ese are
re#erence )ariab&es and primiti)e )ariab&es.
Primiti)e )ariab&es are !aria%les )it$ *rimiti!e data ty*es. T$ey store data in t$eactual memory location o- )$ere t$e !aria%le is.
Re#erence )ariab&es are !aria%les t$at stores t$e address in t$e memory location. It*oints to anot$er memory location o- )$ere t$e actual data is. $en you declare a!aria%le o- a certain class you are actually declaring a re-erence !aria%le to t$e o%ect)it$ t$at certain class.
For eam*le su**ose )e $a!e t)o !aria%les )it$ data ty*es int and 'tring.
int num = ;C%String name = "Hello"
'u**ose t$e illustration s$o)n %elo) is t$e actual memory o- your com*uter )$ereinyou $a!e t$e address o- t$e memory cells t$e !aria%le name and t$e data t$ey $old.
Memor# /ddress
Dariableame
,ata
1001 num 10
; ;
1,63 name ddress420009
; ;
;;
2000 R#elloR
s you can see -or t$e *rimiti!e !aria%le num t$e data is on t$e actual location o-)$ere t$e !aria%le is. For t$e re-erence !aria%le name t$e !aria%le ust $olds t$eaddress o- )$ere t$e actual data is.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 70/244
Introduction to Programming I H0
%.15 OperatorsIn Ja!a t$ere are di--erent ty*es o- o*erators. T$ere are arit$metic o*erators relational
o*erators logical o*erators and conditional o*erators. T$ese o*erators -ollo) a certain:ind o- *recedence so t$at t$e com*iler )ill :no) )$ic$ o*erator to e!aluate -irst in casemulti*le o*erators are used in one statement.
%.15.1 /rit(metic operators
#ere are t$e %asic arit$metic o*erators t$at can %e used in creating your Ja!a *rograms
Operator :se ,escription
K o*1 K o*2 dds o*1 and o*2
U o*1 U o*2 (ulti*lies o*1 %y o*2
8 o*1 8 o*2 Di!ides o*1 %y o*2
o*1 o*2om*utes t$e remainder o- di!idingo*1 %y o*2
o*1 o*2 'u%tracts o*2 -rom o*1
Table 1&: 3rithmetic operations and their functions
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 71/244
Introduction to Programming I H1
#eres a sam*le *rogram in t$e usage o- t$ese o*erators;
public class rit!meticEemo{
public static void main(String[] args{
//a fe# numbersint i = FD%int j = G<%double 5 = <D.GDN%double y = D.<<%System.out.println("Lariable values..."%System.out.println(" i = " 4 i%System.out.println(" j = " 4 j%System.out.println(" 5 = " 4 5%System.out.println(" y = " 4 y% //adding numbersSystem.out.println("dding..."%
System.out.println(" i 4 j = " 4 (i 4 j%System.out.println(" 5 4 y = " 4 (5 4 y%
//subtracting numbersSystem.out.println("Subtracting..."%System.out.println(" i j = " 4 (i j%System.out.println(" 5 y = " 4 (5 y%
//multiplying numbersSystem.out.println("Multiplying..."%System.out.println(" i * j = " 4 (i * j%System.out.println(" 5 * y = " 4 (5 * y%
//dividing numbersSystem.out.println("Eividing..."%System.out.println(" i / j = " 4 (i / j%System.out.println(" 5 / y = " 4 (5 / y%
//computing t!e remainder resulting from dividingnumbers
System.out.println("3omputing t!e remainder..."%System.out.println(" i O j = " 4 (i O j%System.out.println(" 5 O y = " 4 (5 O y%
//mi5ing types System.out.println("Mi5ingtypes..."% System.out.println(" j 4 y = "4 (j 4 y% System.out.println(" i * 5 = "4 (i * 5%
&&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 72/244
Introduction to Programming I H2
#ere is t$e out*ut o- t$e *rogram
Lariable values...i = FD
j = G<5 = <D.GDNy = D.<<
dding...i 4 j = DP5 4 y = FG.IPN
Subtracting...i j = N5 y = <C.<NN
Multiplying...i * j = ;NNG5 * y = ;PJ.FD
Eividing...i / j = C
5 / y = F.JCNG3omputing t!e remainder...
i O j = FD5 O y = N.J;N
Mi5ing types...j 4 y = GP.<<i * 5 = ;C;I.NJ
/ote2 $en an integer and a -loating*oint num%er are used as o*erands to a singlearit$metic o*eration t$e result is a -loating *oint. T$e integer is im*licitly con!erted to a-loating*oint num%er %e-ore t$e o*eration ta:es *lace.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 73/244
Introduction to Programming I H3
%.15.2 Increment and ,ecrement operators
side -rom t$e %asic arit$metic o*erators Ja!a also includes a unary increment o*erator4KK9 and unary decrement o*erator 49. Increment and decrement o*erators increase
and decrease a !alue stored in a num%er !aria%le %y 1.
For eam*le t$e e*ression
count = count 4 ;% //increment t!e value of count by ;
is e?ui!alent to
count44%
Operator :se ,escription
KK o*KKIncrements o* %y 1[ e!aluates to t$e!alue o- o* %e-ore it )as incremented
KK KKo*Increments o* %y 1[ e!aluates to t$e!alue o- o* a-ter it )as incremented
o*Decrements o* %y 1[ e!aluates to t$e!alue o- o* %e-ore it )asdecremented
o*Decrements o* %y 1[ e!aluates to t$e!alue o- o* a-ter it )as decremented
Table 11: 6ncrement and ecrement operators
T$e increment and decrement o*erators can %e *laced %e-ore or a-ter an o*erand.
$en used be#ore an o*erand it causes t$e !aria%le to %e incremented or decremented%y 1 and t$en t$e ne) !alue is used in t$e e*ression in )$ic$ it a**ears. For eam*le
int i = ;Cint j = F%int - = C%
- = ++ 4 i% //#ill result to - = G4;C = ;G
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 74/244
Introduction to Programming I H
$en t$e increment and decrement o*erators are *laced a-ter t$e o*erand t$e old !alueo- t$e !aria%le )ill %e used in t$e e*ression )$ere it a**ears. For eam*le
int i = ;Cint j = F%int - = C%
- = j44 4 i% //#ill result to - = F4;C = ;F
Coding <uideline 3lways ;eep expressions containing increment and decrement operators simpleand easy to understand.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 75/244
Introduction to Programming I H,
%.15.3 4elational operators
"elational o*erators com*are t)o !alues and determines t$e relations$i* %et)een t$ose!alues. T$e out*ut o- e!aluation are t$e boo&ean )a&ues true or -alse.
Operator :se ,escription
o*1 o*2 o*1 is greater t$an o*2
S o*1 S o*2 o*1 is greater t$an or e?ual to o*2
o*1 o*2 o*1 is less t$an o*2
S o*1 S o*2 o*1 is less t$an or e?ual to o*2
SS o*1 SS o*2 o*1 and o*2 are e?ual
S o*1 S o*2 o*1 and o*2 are not e?ual
Table 12: 8elational -perators
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 76/244
Introduction to Programming I H6
#eres a sam*le *rogram t$at uses relational o*erators
public class QelationalEemo{
public static void main(String[] args {//a fe# numbersint i = FD%int j = G<%int - = G<%System.out.println("Lariable values..."%System.out.println(" i = " 4 i%System.out.println(" j = " 4 j%System.out.println(" - = " 4 -%
//greater t!anSystem.out.println("Rreater t!an..."%System.out.println(" i j = " 4 (i j% //falseSystem.out.println(" j i = " 4 (j i% //true
System.out.println(" - j = " 4 (- j% //false
//greater t!an or e@ual toSystem.out.println("Rreater t!an or e@ual to..."%System.out.println(" i = j = " 4 (i = j% //falseSystem.out.println(" j = i = " 4 (j = i% //trueSystem.out.println(" - = j = " 4 (- = j% //true
//less t!anSystem.out.println("Tess t!an..."%System.out.println(" i U j = " 4 (i U j% //trueSystem.out.println(" j U i = " 4 (j U i% //falseSystem.out.println(" - U j = " 4 (- U j% //false
//less t!an or e@ual to
System.out.println("Tess t!an or e@ual to..."%System.out.println(" i U= j = " 4 (i U= j% //trueSystem.out.println(" j U= i = " 4 (j U= i% //falseSystem.out.println(" - U= j = " 4 (- U= j% //true
//e@ual toSystem.out.println("0@ual to..."%System.out.println(" i == j = " 4 (i == j% //falseSystem.out.println(" - == j = " 4 (- == j% //true
//not e@ual toSystem.out.println("+ot e@ual to..."%System.out.println(" i $= j = " 4 (i $= j% //trueSystem.out.println(" - $= j = " 4 (- $= j% //false
&&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 77/244
Introduction to Programming I HH
#eres t$e out*ut -rom t$is *rogram;
Lariable values...i = FD
j = G<- = G<
Rreater t!an...i j = falsej i = true- j = false
Rreater t!an or e@ual to...i = j = falsej = i = true- = j = true
Tess t!an...i U j = truej U i = false- U j = false
Tess t!an or e@ual to...i U= j = truej U= i = false- U= j = true
0@ual to...i == j = false- == j = true
+ot e@ual to...i $= j = true- $= j = false
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 78/244
Introduction to Programming I H7
%.15.% &ogical operators
=ogical o*erators $a!e one or t)o %oolean o*erands t$at yield a %oolean result. T$ereare si logical o*erators; MM 4logical +D9 M 4%oolean logical +D9 NN 4logical &"9 N
4%oolean logical inclusi!e &"9 O 4%oolean logical eclusi!e &"9 and 4logical +&T9.
T$e %asic e*ression -or a logical o*eration is
5; op 5<
)$ere 1 2 can %e %oolean e*ressions !aria%les or constants and o* is eit$er MM MNN N or O o*erator. T$e trut$ ta%les t$at )ill %e s$o)n net summari>e t$e result o-eac$ o*eration -or all *ossi%le com%inations o- 1 and 2.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 79/244
Introduction to Programming I H<
<,+9,<,+ 6&ogica& A/$7 and 6boo&ean &ogica& A/$7
#ere is t$e trut$ ta%le -or MM and M
-1 -2 4esult
T"E T"E T"E
T"E F='E F='E
F='E T"E F='E
F='E F='E F='E
Table 1: Truth table for M and MM
T$e %asic di--erence %et)een MM and M o*erators is t$at MM su**orts short3circuite)a&uations 4or *artial e!aluations9 )$ile M doesnt. $at does t$is meanG
@i!en an e*ression
e5p; VV e5p<
MM )ill e!aluate t$e e*ression e*1 and immediately return a -alse !alue is e*1 is-alse. I- e*1 is -alse t$e o*erator ne!er e!aluates e*2 %ecause t$e result o- t$eo*erator )ill %e -alse regardless o- t$e !alue o- e*2. In contrast t$e M o*erator al)ayse!aluates %ot$ e*1 and e*2 %e-ore returning an ans)er.
#eres a sam*le source code t$at uses logical and %oolean +D
public class 2est+E{
public static void main( String[] args {
int i = C%int j = ;C%boolean test= false%
//demonstrate VVtest = (i ;C VV (j44 P%System.out.println(i%System.out.println(j%System.out.println(test%
//demonstrate Vtest = (i ;C V (j44 P%
System.out.println(i%System.out.println(j%System.out.println(test%
&&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 80/244
Introduction to Programming I 70
T$e out*ut o- t$e *rogram is
C;C
falseC;;false
+ote t$at t$e KK on t$e line containing t$e MM o*erator is not e!aluated since t$e -irste*ression 4i109 is already e?ual to -alse.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 81/244
Introduction to Programming I 71
<,+9,<,. JJ 6&ogica& OR7 and J 6boo&ean &ogica& inc&usi)e OR7
#ere is t$e trut$ ta%le -or NN and N
-1 -2 4esult
T"E T"E T"E
T"E F='E T"E
F='E T"E T"E
F='E F='E F='E
Table 1%: Truth table for N and NN
T$e %asic di--erence %et)een NN and N o*erators is t$at NN su**orts s$ortcircuite!aluations 4or *artial e!aluations9 )$ile N doesnt. $at does t$is meanG
@i!en an e*ression
e5p; WW e5p<
NN )ill e!aluate t$e e*ression e*1 and immediately return a true !alue is e*1 is true.I- e*1 is true t$e o*erator ne!er e!aluates e*2 %ecause t$e result o- t$e o*erator )ill%e true regardless o- t$e !alue o- e*2. In contrast t$e N o*erator al)ays e!aluates %ot$e*1 and e*2 %e-ore returning an ans)er.
#eres a sam*le source code t$at uses logical and %oolean &"
public class 2estQ{
public static void main( String[] args {
int i = C%int j = ;C%boolean test= false%
//demonstrate WWtest = (i U ;C WW (j44 P%System.out.println(i%System.out.println(j%System.out.println(test%
//demonstrate Wtest = (i U ;C W (j44 P%
System.out.println(i%System.out.println(j%System.out.println(test%
&&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 82/244
Introduction to Programming I 72
T$e out*ut o- t$e *rogram is
C;C
trueC;;true
+ote t$at t$e KK on t$e line containing t$e NN o*erator is not e!aluated since t$e -irste*ression 4i109 is already e?ual to true.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 83/244
Introduction to Programming I 73
<,+9,<,- K 6boo&ean &ogica& exc&usi)e OR7
#ere is t$e trut$ ta%le -or O
-1 -2 4esult
T"E T"E F='E
T"E F='E T"E
F='E T"E T"E
F='E F='E F='E
Table 1+: Truth table for O
T$e result o- an eclusi!e &" o*eration is T"E i- and only i- one o*erand is true andt$e ot$er is -alse. +ote t$at %ot$ o*erands must al)ays %e e!aluated in order tocalculate t$e result o- an eclusi!e &".
#eres a sam*le source code t$at uses t$e logical eclusi!e &" o*erator
public class 2estXQ{
public static void main( String[] args {
boolean val; = true% booleanval< = true%System.out.println(val; Y val<%
val; = false% val< = true%System.out.println(val; Y val<%
val; = false% val< = false%System.out.println(val; Y val<%
val; = true% val< = false%System.out.println(val; Y val<%
&&
T$e out*ut o- t$e *rogram is
falsetruefalsetrue
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 84/244
Introduction to Programming I 7
<,+9,<,< 6&ogica& /OT7
T$e logical +&T ta:es in one argument )$erein t$at argument can %e an e*ression!aria%le or constant. #ere is t$e trut$ ta%le -or
-1 4esult
T"E F='E
F='E T"E
Table 1*: Truth table for P
#eres a sam*le source code t$at uses t$e logical +&T o*erator
public class 2est+2{
public static void main( String[] args {
boolean val; = true%boolean val< = false%System.out.println($val;%System.out.println($val<%
&
b
T$e out*ut o- t$e *rogram is
falsetrue
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 85/244
Introduction to Programming I 7,
%.15.* Conditional Operator F)G
T$e conditional o*erator 2 is a ternary o*erator. T$is means t$at it ta:es in t$reearguments t$at toget$er -orm a conditional e*ression. T$e structure o- an e*ression
using a conditional o*erator is
e5p;Ze5p<7e5pF
)$erein e*1 is a %oolean e*ression )$ose result must eit$er %e true or -alse.
I- e*1 is true e*2 is t$e !alue returned. I- it is -alse t$en e*3 is returned.
For eam*le gi!en t$e code
public class 3onditionalperator{
public static void main( String[] args {
String status = ""%int grade = JC%
//get status of t!e studentstatus = (grade = IC!")assed""9ail"%
//print statusSystem.out.println( status %
&&
T$e out*ut o- t$is *rogram )ill %e
)assed
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 86/244
Introduction to Programming I 76
#ere is t$e -lo)c$art o- $o) G; )or:s
Figure %.2: Flowchart using the (: operator
#ere is anot$er *rogram t$at uses t$e G; o*erator
class 3onditionalperator{
public static void main( String[] args {
int score = C%c!ar ans#er = ?a?%
score = (ans#er == ?a? Z ;C 7 C%System.out.println("Score = " 4 score %
&&
T$e out*ut o- t$e *rogram is
Score = ;C
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 87/244
Introduction to Programming I 7H
%.15. Operator $recedence
&*erator *recedence de-ines t$e com*iler`s order o- e!aluation o- o*erators so as tocome u* )it$ an unam%iguous result.
Figure %.: -perator )recedence
@i!en a com*licated e*ressionIO<*N4G/<4JJ;C
)e can re)rite t$e e*ression and *lace some *arent$esis %ase on o*erator *recedence
((IO<*N4(G/<4JJ;C%
Coding <uidelinesTo a$oid confusion in e$aluating mathematical operationsB ;eep your expressionssimple and use parenthesis.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 88/244
Introduction to Programming I 77
%.11 0-ercises
%.11.1 ,eclaring and printing variables
@i!en t$e ta%le %elo) declare t$e -ollo)ing !aria%les )it$ t$e corres*onding data ty*esand initiali>ation !alues. &ut*ut to t$e screen t$e !aria%le names toget$er )it$ t$e!alues.
Dariable name ,ata +#pe Initial value
num%er integer 10
letter c$aracter a
result %oolean true
str 'tring $ello
T$e -ollo)ing s$ould %e t$e e*ected screen out*ut
+umber = ;Cletter = aresult = truestr = !ello
%.11.2 <etting t(e average of t(ree numbers
reate a *rogram t$at out*uts t$e a!erage o- t$ree num%ers. =et t$e !alues o- t$e t$reenum%ers %e 10 20 and ,. T$e e*ected screen out*ut is
number ; = ;Cnumber < = <Cnumber F = GNverage is = <N
%.11.3 Output greatest value
@i!en t$ree num%ers )rite a *rogram t$at out*uts t$e num%er )it$ t$e greatest !alueamong t$e t$ree. se t$e conditional G; o*erator t$at )e $a!e studied so -ar 4I/T; ou)ill need to use t)o sets o- 2 to sol!e t$is9. For eam*le gi!en t$e num%ers 10 23 and, your *rogram s$ould out*ut
number ; = ;Cnumber < = <F
number F = N2!e !ig!est number is = <F
%.11.% Operator precedence
@i!en t$e -ollo)ing e*ressions re)rite t$em %y )riting some *arent$esis %ased on t$ese?uence on $o) t$ey )ill %e e!aluated.1. a 8 % O c O d L e K - L g U $ K i
2. 3 U 10 U2 8 1, L 2 K O 2 O 23. r O s U t 8 u L ! K ) O L yKK
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 89/244
Introduction to Programming I 7<
4 ?etting Input #rom the Neyboard
*.1 Objectives+o) t$at )e!e studied some %asic conce*ts in Ja!a and )e!e )ritten some sim*le*rograms lets ma:e our *rograms more interacti!e %y getting some in*ut -rom t$euser. In t$is section )ell %e discussing t)o met$ods o- getting in*ut t$e -irst one ist$roug$ t$e use o- t$e Bu--ered"eader class and t$e ot$er one in!ol!es a gra*$ical userinter-ace %y using J&*tionPane.
t t$e end o- t$e lesson t$e student s$ould %e a%le to;
• reate an interacti!e Ja!a *rogram t$at gets in*ut -rom t$e :ey%oard
• se t$e Bu--ered"eader class to get in*ut -rom t$e :ey%oard using a console
• se t$e J&*tionPane class to get in*ut -rom t$e :ey%oard using a gra*$ical user
inter-ace
*.2 :sing Buffered4eader to getinput In t$is section )e )ill use t$e :ufferedQeader class -ound in t$e java.io *ac:age
in order to get in*ut -rom t$e :ey%oard.
#ere are t$e ste*s to get in*ut -rom t$e :ey%oard;
1. dd t$is at t$e to* o- your code;
im*ort a!a.io.U[
2. dd t$is statement;
:ufferedQeader data,n = ne# :ufferedQeader(ne# ,nputStreamQeader( System.in %
3. Declare a tem*orary 'tring !aria%le to get t$e in*ut and in!o:e t$e read=ine49
met$od to get in*ut -rom t$e :ey%oard. ou $a!e to ty*e it inside a trycatc$ %loc:.
try{String temp = data,n.readTine(%
&catc!( ,05ception e {
System.out.println(A0rror in getting inputB%&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 90/244
Introduction to Programming I <0
#ere is t$e com*lete source code;
import java.io.:ufferedQeader%import java.io.,nputStreamQeader%
import java.io.,05ception%
public class Ret,nput9romeyboard{
public static void main( String[] args {
#u$$ered%eader data&n = ne #u$$ered%eader(ne&nput)tream%eader( )ystem*in ;
String name = ""%
System.out.print(")lease 0nter our +ame7"%
try
-
name = data&n*read.ine(;-catch( &/01ception e )ystem*out*println("0rror2";
System.out.println("Hello " 4 name 4"$"%-
&
+o) lets try to e*lain eac$ line o- code;
T$e statements
import java.io.:ufferedQeader%import java.io.,nputStreamQeader%import java.io.,05ception%
indicate t$at )e )ant to use t$e classes #u$$ered%eader &nput)tream%eader and
&/01ception )$ic$ is inside t$e ava*io pac%age. T$e Ja!a **lication
Programming Inter-ace 4PI9 contains $undreds o- *rede-ined classes t$at you can use inyour *rograms. T$ese classes are organi>ed into )$at )e call pac%ages,
Pac%ages contain classes t$at $a!e related *ur*ose. Just li:e in our eam*le t$eava*io *ac:age contains classes t$at allo) *rograms to in*ut and out*ut data. T$e
statements can also %e re)ritten as
import java.io.*%
)$ic$ )ill load all t$e classes -ound in t$e *ac:age and t$en )e can use t$ose classesinside our *rogram.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 91/244
T$e net t)o statements
public class Ret,nput9romeyboard{
public static void main( String[] args {
)ere already discussed in t$e *re!ious lesson. T$is means )e declare a class namedRet,nput9romeyboard and )e declare t$e main
met$od.
In t$e statement
:ufferedQeader data,n = ne# :ufferedQeader(ne#,nputStreamQeader( System.in %
)e are declaring a !aria%le named dataIn )it$ t$e class ty*e 0u##eredReader. Dont
)orry a%out )$at t$e synta means -or no). e )ill co!er more a%out t$is later in t$ecourse.
+o) )e are declaring a 'tring !aria%le )it$ t$e identi-ier name
String name = ""%
T$is is )$ere )e )ill store t$e in*ut o- t$e user. T$e !aria%le name is initiali>ed to anem*ty 'tring RR. It is al)ays good to initiali>e your !aria%les as you declare t$em.
T$e net line ust out*uts a 'tring on t$e screen as:ing -or t$e users name.
System.out.print(")lease 0nter our +ame7"%
+o) t$e -ollo)ing %loc: de-ines a trycatc$ %loc:
try{
name = data,n.readTine(%&catc!( ,05ception e
{ System.out.println("0rror$"%
&
T$is assures t$at t$e *ossi%le ece*tions t$at could occur in t$e statement
name = data,n.readTine(%
)ill %e catc$ed. e )ill co!er more a%out ece*tion $andling in t$e latter *art o- t$iscourse %ut -or no) ust ta:e note t$at you need to add t$is code in order to use t$eread=ine49 met$od o- Bu--ered"eader to get in*ut -rom t$e user.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 92/244
+o) going %ac: to t$e statement
name = data,n.readTine(%
t$e met$od call data,n.readTine( gets in*ut -rom t$e user and )ill return a 'tring!alue. T$is !alue )ill t$en %e sa!ed to our name !aria%le )$ic$ )e )ill use in our -inal
statement to greet t$e user
System.out.println("Hello " 4 name 4 "$"%
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 93/244
*.3 :sing 7Option$ane to get input not$er )ay to get in*ut -rom t$e user is %y using t$e ption)ane class )$ic$ is
-ound in t$e java5.s#ing *ac:age. Jption)ane ma:es it easy to *o* u* a standarddialog %o t$at *rom*ts users -or a !alue or in-orms t$em o- somet$ing.
@i!en t$e -ollo)ing code
import java5.s#ing.ption)ane%
public class Ret,nput9romeyboard{
public static void main( String[] args {String name = ""%name = option)ane.s!o#,nputEialog(")lease enter your
name"%
String msg = "Hello " 4 name 4 "$"%
ption)ane.s!o#MessageEialog(null msg%
&
T$is )ill out*ut
&
Figure +.1: @etting 6nput Lsing -ption)ane
Figure +.2: 6nput florence on the -ption)ane
Figure +.: Showing =essage Lsing -ption)ane
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 94/244
T$e -irst statement
import java5.s#ing.ption)ane%
indicates t$at )e )ant to im*ort t$e class ption)ane -rom t$e java5.s#ing
*ac:age. e can also )rite t$is as
import java5.s#ing.*%
T$e statement
name = ption)ane.s!o#,nputEialog(")lease enter your name"%
creates a ption)ane in*ut dialog )$ic$ )ill dis*lay a dialog )it$ a message atet-ield and an &A %utton as s$o)n in t$e -igure. T$is returns a 'tring )$ic$ )e )ill
sa!e in t$e name !aria%le.
+o) )e create t$e )elcome message )$ic$ )e )ill store in t$e msg
!aria%le
String msg = "Hello " 4 name 4 "$"%
T$e net line dis*lays a dialog )$ic$ contains a message and an &A %utton.
ption)ane.s!o#MessageEialog(null msg%
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 95/244
*.% 0-ercises
*.%.1 &ast 3 !ords FBuffered4eader versionG
sing Bu--ered"eader as: -or t$ree )ords -rom t$e user and out*ut t$ose t$ree )ordson t$e screen. For eam*le
0nter #ord;7Roodbye0nter #ord<7and0nter #ordF7Hello
Roodbye and Hello
*.%.2 &ast 3 !ords F7Option$ane versionG
sing J&*tionPane as: -or t$ree )ords -rom t$e user and out*ut t$ose t$ree )ords on
t$e screen. For eam*le
Figure +.%: First 6nput
Figure +.+: Second 6nput
Figure +.*: Third 6nput
Figure +./: Show =essage
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 96/244
8 "ontro& Structures
.1 ObjectivesIn t$e *re!ious sections )e $a!e gi!en eam*les o- se?uential *rograms )$ereinstatements are eecuted one a-ter anot$er in a -ied order. In t$is section )e )ill %ediscussing control structures )$ic$ allo)s us to c$ange t$e ordering o- $o) t$estatements in our *rograms are eecuted.
t t$e end o- t$e lesson t$e student s$ould %e a%le to;
• se decision control structures 4i- else s)itc$9 )$ic$ allo)s selection o- s*eci-ic
sections o- code to %e eecuted
• se re*etition control structures 4)$ile do)$ile -or9 )$ic$ allo) eecuting
s*eci-ic sections o- code a num%er o- times
• se %ranc$ing statements 4%rea: continue return9 )$ic$ allo)s redirection o-
*rogram -lo)
.2 ,ecision Control StructuresDecision control structures are Ja!a statements t$at allo)s us to select and eecutes*eci-ic %loc:s o- code )$ile s:i**ing ot$er sections.
.2.1 if statement T$e i-statement s*eci-ies t$at a statement 4or %loc: o- code9 )ill %e eecuted if andonly if a certain boolean statement is true.
T$e i-statement $as t$e -orm
if( boolean\e5pression statement%
or
if( boolean\e5pression {
statement;%statement<%. . .
&
)$ere %ooleanCe*ression is eit$er a %oolean e*ression or %oolean !aria%le.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 97/244
Figure *.1: Flowchart of 6fStatement
if( grade IC System.out.println("3ongratulations$"%
or
int grade = IJ%
if( grade IC { System.out.println("3ongratulations$"% System.out.println("ou passed$"%
&
Coding <uidelines
1. The booleanHe-pression part of a statement should e$aluate to a boolean $alue.That means that the execution of the condition should either result to a $alue of trueor a false.
2. 6ndent the statements inside the ifbloc;.ForexampleB if, booleanJexpression
AAstatement1G AAstatement2G
H
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 98/244
.2.2 if"else statement
T$e i-else statement is used )$en )e )ant to eecute a certain statement i- a conditionis true and a di--erent statement i- t$e condition is -alse.
T$e i-else statement $as t$e -orm
if( boolean\e5pression statement%
elsestatement%
or can also %e )ritten as
if( boolean\e5pression {statement;%statement<%
. . .&else{
&
statement;%statement<%. . .
For eam*le gi!en t$e code sni**et
int grade = IJ%
if( grade IC System.out.println("3ongratulations$"%else System.out.println("Sorry you failed"%
or
int grade = IJ%
if( grade IC { System.out.println("3ongratulations$"% System.out.println("ou passed$"%
&else{
&System.out.println("Sorry you failed"%
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 99/244
Figure *.2: Flowchart of 6fElse Statement
Coding <uidelines
1. To a$oid confusionB always place the statement or statements of an if or ifelsebloc; inside brac;ets H.
2. >ou can ha$e nested ifelse bloc;s. This means that you can ha$e other ifelsebloc;s inside another ifelse bloc;.For exampleB
if, booleanJexpression
if, booleanJexpression . . .
H
Helse . . .
H
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 100/244
Introduction to Programming I 100
.2.3 if"else"if statement
T$e statement in t$e elseclause o- an i-else %loc: can %e anot$er i-else structures.T$is cascading o- structures allo)s us to ma:e more com*le selections.
T$e i-else i- statement $as t$e -orm
if( boolean\e5pression; statement;%
else if( boolean\e5pression< statement<%
elsestatementF%
Ta:e note t$at you can $a!e many elsei- %loc:s a-ter an i-statement. T$e else%loc: iso*tional and can %e omitted. In t$e eam*le s$o)n a%o!e i- %ooleanCe*ression1 istrue t$en t$e *rogram eecutes statement1 and s:i*s t$e ot$er statements. I-
%ooleanCe*ression2 is true t$en t$e *rogram eecutes statement 2 and s:i*s to t$estatements -ollo)ing statement3.
Figure *.: Flowchart of 6fElse6f Statement
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 101/244
For eam*le gi!en t$e code sni**et
int grade = IJ%
if( grade PC { System.out.println("Lerygood$"%
&else if( grade IC {
System.out.println("Lery good$"%&else{
&System.out.println("Sorry you failed"%
.2.% Common 0rrors !(en using t(e if"else statements
1. T$e condition inside t$e i-statement does not e!aluate to a %oolean !alue. Foream*le
//'Q+Rint number = C%if( number {
//some statements !ere&
T$e !aria%le num%er does not $old a Boolean !alue.
2. sing S instead o- SS -or com*arison. For eam*le
//'Q+Rint number = C%if( number = C {
//some statements !ere&
T$is s$ould %e )ritten as
//3QQ032int number = C%if( number == C {
//some statements !ere
&
3. riting e&sei# instead o- e&se i# .
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 102/244
.2.* 0-ample for if"else"else if
public class Rrade{
public static void main( String[] args {double grade = P<.C%
if( grade = PC {System.out.println( "05cellent$" %
&else if( (grade U PC VV (grade = JC{
System.out.println("Rood job$" %&else if( (grade U JC VV (grade = IC{
System.out.println("Study !arder$" %&else{
&&
&
System.out.println("Sorry you failed."%
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 103/244
.2. s!itc( statement
not$er )ay to indicate a %ranc$ is t$roug$ t$e s!itch :ey)ord. T$e s)itc$ constructallo)s %ranc$ing on multi*le outcomes.
T$e s)itc$ statement $as t$e -orm
s#itc!( s#itc!\e5pression {case case\selector;7
statement;% //statement<% //bloc- ;. . . //brea-%
case case\selector<7statement;% //statement<% //bloc- <. . . //
brea-%. . .default7
statement;% //statement<% //bloc- n. . . //brea-%
&
)$ere s)itc$Ce*ression is an integer or character e*ression and caseCselector1caseCselector2 and so on are uni?ue integer or c$aracter constants.
$en a s)itc$ is encountered Ja!a -irst e!aluates t$e s)itc$Ce*ression and um*s to
t$e case )$ose selector matc$es t$e !alue o- t$e e*ression. T$e *rogram eecutes t$estatements in order -rom t$at *oint on until a %rea: statement is encountered s:i**ingt$en to t$e -irst statement a-ter t$e end o- t$e s)itc$ structure.
I- none o- t$e cases are satis-ied t$e de-ault %loc: is eecuted. Ta:e note $o)e!ert$at t$e de-ault *art is o*tional. s)itc$ statement can $a!e no de-ault %loc:.
/OTES2• nli:e )it$ t$e i# statement t$e multi*le statements are eecuted in t$e s)itc$
statement )it$out needing t$e curly %races.• $en a case in a s)itc$ statement $as %een matc$ed all t$e statements associated
)it$ t$at case are eecuted. +ot only t$at t$e statements associated )it$ t$e
succeeding cases are also eecuted.• To *re!ent t$e *rogram -rom eecuting statements in t$e su%se?uent cases )e use a
brea% statement as our last statement.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 104/244
Coding <uidelines
1. eciding whether to use an if statement or a switch statement is a <udgment call.
>ou can decide which to useB based on readability and other factors.2. 3n if statement can be used to ma;e decisions based on ranges of $alues
or conditionsB whereas a switch statement can ma;e decisions based only on a singleinteger or character $alue. 3lsoB the $alue pro$ided to each case statement must beuni#ue.
Figure *.%: Flowchart of Switch Statements
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 105/244
.2.6 0-ample for s!itc(
public class Rrade{
public static void main( String[] args {int grade = P<%
s#itc!(grade{case ;CC7
case PC7
case JC7
default7
&&
&
System.out.println( "05cellent$" %brea-%
System.out.println("Rood job$" %brea-%
System.out.println("Study !arder$" %brea-%
System.out.println("Sorry you failed."%
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 106/244
.3 4epetition Control Structures"e*etition control structures are Ja!a statements t$at allo)s us to eecute s*eci-ic
%loc:s o- code a num%er o- times. T$ere are t$ree ty*es o- re*etition control structurest$e )$ile do)$ile and -or loo*s.
.3.1 !(ile loop
T$e )$ile loo* is a statement or %loc: o- statements t$at is re*eated as long as somecondition is satis-ied.
T$e )$ile statement $as t$e -orm
#!ile( boolean\e5pression {statement;%statement<%. . .
&
T$e statements inside t$e )$ile loo* are eecuted as long as t$e %ooleanCe*ressione!aluates to true.
For eam*le gi!en t$e code sni**et
int i = G%#!ile ( i C {
System.out.print(i%i%
&
T$e sam*le code s$o)n )ill *rint GF<; on t$e screen. Ta:e note t$at i- t$e linecontaining t$e statement i% is remo!ed t$is )ill result to an in#inite &oop or a
loo* t$at does not terminate. T$ere-ore )$en using )$ile loo*s or any :ind o- re*etitioncontrol structures ma:e sure t$at you add some statements t$at )ill allo) your loo* toterminate at some *oint.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 107/244
T$e -ollo)ing are ot$er eam*les o- )$ile loo*s
Examp&e +2
int 5 = C%#!ile (5U;C{
System.out.println(5%544%
&
Examp&e .2
//infinite loop#!ile(true
System.out.println(A!elloB%
Examp&e -2
//no loops// statement is not even e5ecuted#!ile (false
System.out.println(A!elloB%
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 108/244
.3.2 do"!(ile loop
T$e do)$ile loo* is similar to t$e )$ileloo*. T$e statements inside a do)$ile loo* areeecuted se!eral times as long as t$e condition is satis-ied.
T$e main di--erence %et)een a )$ile and do)$ile loo* is t$at t$e statements inside ado)$ile loo* are eecuted at &east once,
T$e do)$ile statement $as t$e -orm
do{
statement;%statement<%. . .
&#!ile( boolean\e5pression %
T$e statements inside t$e do)$ile loo* are -irst eecuted and t$en t$e condition in t$e%ooleanCe*ression *art is e!aluated. I- t$is e!aluates to true t$e statements inside t$edo)$ile loo* are eecuted again.
#ere are a -e) eam*les t$at uses t$e do)$ile loo*;
Examp&e +2
int 5 = C%do{
System.out.println(5%544%
&#!ile (5U;C%
T$is eam*le )ill out*ut C;<FGNIDJP on t$e screen.
Examp&e .2
//infinite loopdo{
System.out.println(A!elloB%& #!ile (true%
T$is eam*le )ill result to an in-inite loo* t$at *rints !ello on screen.
Examp&e -2
//one loop// statement is e5ecuted oncedoSystem.out.println(A!elloB%
#!ile (false%
T$is eam*le )ill out*ut !ello on t$e screen.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 109/244
Coding <uidelines
1. Common programming mista;es when using the dowhile loop is forgetting to
write the semicolon after the while expression.do
...
Hwhile,booleanJexpression AA58-"@Qforgot semicolon G2. ust li;e in while loopsB ma;e sure that your dowhile loops will terminate at
some point.
.3.3 for loop
T$e -or loo* li:e t$e *re!ious loo*s allo)s eecution o- t$e same code a num%er o-times.
T$e -or loo* $as t$e -orm
for (,nitialiKation05pression% Toop3ondition% Step05pression{statement;%statement<%. . .
&
)$ere
InitialiEation0-pression initiali>es t$e loo* !aria%le.&oopCondition " com*ares t$e loo* !aria%le to some limit !alue.Step0-pression u*dates t$e loo* !aria%le.
sim*le eam*le o- t$e -or loo* is
int i%for( i = C% i U ;C% i44 {
System.out.print(i%&
In t$is eam*le t$e statement iS0 -irst initiali>es our !aria%le. -ter t$at t$e conditione*ression i10 is e!aluated. I- t$is e!aluates to true t$en t$e statement inside t$e -orloo* is eecuted. +et t$e e*ression iKK is eecuted and t$en t$e conditione*ression is again e!aluated. T$is goes on and on until t$e condition e*ressione!aluates to -alse.
T$is eam*le is e?ui!alent to t$e )$ile loo* s$o)n %elo)
int i = C%#!ile( i U ;C {
System.out.print(i%i44%
&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 110/244
Introduction to Programming I 110
.% Branc(ing StatementsBranc$ing statements allo)s us to redirect t$e -lo) o- *rogram eecution. Ja!a o--ers
t$ree %ranc$ing statements; %rea: continue and return.
.%.1 brea8 statement
T$e %rea: statement $as t)o -orms; unla%eled 4)e sa) its unla%eled -orm in t$e s)itc$statement9 and la%eled.
8,<,+,+ 1n&abe&ed brea% statement
T$e unla%eled %rea: terminates t$e enclosing s)itc$ statement and -lo) o- controltrans-ers to t$e statement immediately -ollo)ing t$e s)itc$. ou can also use t$eunla%eled -orm o- t$e brea- statement to terminate a -or )$ile or do)$ile loo*.
For eam*le
String names[] = {":ea!" ":ianca" "Tance" ":elle""+ico" "Ka" "Rem" "0t!an"&%
String searc!+ame = "Ka"%boolean found+ame = false%
for( int i=C% iU names.lengt!% i44 {if( names[i].e@uals( searc!+ame {
found+ame = true% brea3;
&&
if( found+ame {System.out.println( searc!+ame 4 " found$" %
&else{
&System.out.println( searc!+ame 4 " not found." %
In t$is eam*le i- t$e searc$ string R>aR is -ound t$e -or loo* )ill sto* and -lo) o-control trans-ers to t$e statement -ollo)ing t$e -or loo*.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 111/244
8,<,+,. Labe&ed brea% statement
T$e la%eled -orm o- a %rea: statement terminates an outer statement )$ic$ is identi-ied%y t$e la%el s*eci-ied in t$e %rea: statement. T$e -ollo)ing *rogram searc$es -or a !alue
in a t)odimensional array. T)o nested -or loo*s tra!erse t$e array. $en t$e !alue is-ound a la%eled %rea: terminates t$e statement la%eled searc$ )$ic$ is t$e outer -orloo*.
int[][] numbers = {{; < F& {G N I&{D J P&&%
int searc!+um = N%boolean found+um = false%
search.abelfor( int i=C% iUnumbers.lengt!% i44 {
for( int j=C% jUnumbers[i].lengt!% j44 {if( searc!+um == numbers[i][j] {
found+um = true% brea3 search.abel;
&&
&
if( found+um {System.out.println( searc!+um 4 " found$" %
&else{
&System.out.println( searc!+um 4 " not found$" %
T$e %rea: statement terminates t$e la%eled statement[ it does not trans-er t$e -lo) o-control to t$e la%el. T$e -lo) o- control trans-ers to t$e statement immediately -ollo)ingt$e la%eled 4terminated9 statement.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 112/244
.%.2 continue statement
T$e continue statement $as t)o -orms; unla%eled and la%eled. ou can use t$e continuestatement to s:i* t$e current iteration o- a -or )$ile or do)$ile loo*.
8,<,.,+ 1n&abe&ed continue statement
T$e unla%eled -orm s:i*s to t$e end o- t$e innermost loo*s %ody and e!aluates t$e%oolean e*ression t$at controls t$e loo* %asically s:i**ing t$e remainder o- t$isiteration o- t$e loo*.
T$e -ollo)ing eam*le counts t$e num%er o- RBea$Rs in t$e array.
String names[] = {":ea!" ":ianca" "Tance" ":ea!"&%int count = C%
for( int i=C% iUnames.lengt!% i44 {
if( $names[i].e@uals(":ea!" {continue% //s-ip ne5t statement
&
count44%&
System.out.println("2!ere are " 4 count 4 " :ea!s in t!elist"%
8,<,.,. Labe&ed continue statement
T$e la%eled -orm o- t$e continue statement s:i*s t$e current iteration o- an outer loo*
mar:ed )it$ t$e gi!en la%el.
outer.oopfor( int i=C% iUN% i44 {
for( int j=C% jUN% j44 {System.out.println(",nside for(j loop"% //message;if( j == < continue outer.oop;
&
System.out.println(",nside for(i loop"% //message<&
In t$is eam*le message 2 ne!er gets *rinted since )e $a!e t$e statement continue
outerloo* )$ic$ s:i*s t$e iteration.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 113/244
.%.3 return statement
T$e return statement is used to eit -rom t$e current met$od. T$e -lo) o- control returnsto t$e statement t$at -ollo)s t$e original met$od call. T$e return statement $as t)o
-orms; one t$at returns a !alue and one t$at doesnt.
To return a !alue sim*ly *ut t$e !alue 4or an e*ression t$at calculates t$e !alue9 a-tert$e return :ey)ord. For eam*le
return 44count%
orreturn "Hello"%
T$e data ty*e o- t$e !alue returned %y return must matc$ t$e ty*e o- t$e met$odsdeclared return !alue. $en a met$od is declared !oid use t$e -orm o- return t$atdoesnt return a !alue. For eam*le
return%
e )ill co!er more a%out return statements later )$en )e discuss a%out met$ods.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 114/244
.* 0-ercises
.*.1 <rades
@et t$ree eam grades -rom t$e user and com*ute t$e a!erage o- t$e grades. &ut*ut t$ea!erage o- t$e t$ree eams. Toget$er )it$ t$e a!erage also include a smiley -ace in t$eout*ut i- t$e a!erage is greater t$an or e?ual to 60 ot$er)ise out*ut ;4.1. se Bu--ered"eader to get in*ut -rom t$e user and 'ystem.out to out*ut t$eresult.
2. se J&*tionPane to get in*ut -rom t$e user and to out*ut t$e result.
.*.2 umber in !ords
@et a num%er as in*ut -rom t$e user and out*ut t$e e?ui!alent o- t$e num%er in )ords.T$e num%er in*utted s$ould range -rom 110. I- t$e user in*uts a num%er t$at is not int$e range out*ut RIn!alid num%erR.
1. se an i-else statement to sol!e t$is *ro%lem2. se a s)itc$ statement to sol!e t$is *ro%lem
.*.3 undred +imes
reate a *rogram t$at *rints your name a $undred times. Do t$ree !ersions o- t$is*rogram using a )$ile loo* a do)$ile loo* and a -orloo*.
.*.% $o!ers
om*ute t$e *o)er o- a num%er gi!en t$e %ase and e*onent. Do t$ree !ersions o- t$is*rogram using a )$ile loo* a do)$ile loo* and a -orloo*.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 115/244
6.1 Objectives
; =a)a Arrays
In t$is section )e )ill %e discussing a%out Ja!a rrays. First )e are going to de-ine)$at arrays are and t$en )e are going to discuss on $o) to declare and use t$em.
t t$e end o- t$e lesson t$e student s$ould %e a%le to;
• Declare and create arrays
• ccess array elements
• Determine t$e num%er o- elements in an array
• Declare and create multidimensional arrays
6.2 Introduction to arra#sIn t$e *re!ious sections )e $a!e discussed on $o) to declare di--erent !aria%les usingt$e *rimiti!e data ty*es. In declaring !aria%les )e o-ten use a uni?ue identi-ier or nameand a dataty*e. In order to use t$e !aria%le )e call it %y its identi-ier name.
For eam*le )e $a!e $ere t$ree !aria%les o- ty*e int )it$ di--erent identi-iers -or
eac$ !aria%le.
int number;%
int number<%int numberF%
number; = ;%number< = <%numberF = F%
s you can see it seems li:e a tedious tas: in order to ust initiali>e and use t$e!aria%les es*ecially i- t$ey are used -or t$e same *ur*ose. In Ja!a and ot$er*rogramming languages t$ere is one ca*a%ility )$erein )e can use one !aria%le to storea list o- data and mani*ulate t$em more e--iciently. T$is ty*e o- !aria%le is called anarray.
Figure /.1: Example of an 6nteger 3rray
n array stores multiple data items of the same datatype in a contiguous %loc: o-memory di!ided into a num%er o- slots. T$in: o- an array as a stretc$ed !aria%le L alocation t$at still $as one identi-ier name %ut can $old more t$an one !alue.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 116/244
6.3 ,eclaring /rra#srrays must %e declared li:e all !aria%les. $en declaring an array you list t$e data
ty*e -ollo)ed %y a set o- s?uare %rac:etsXY -ollo)ed %y t$e identi-ier name. Foream*le
int []ages%
or you can *lace t$e %rac:ets a-ter t$e identi-ier. For eam*le
int ages[]%
-ter declaring )e must create t$e array and s*eci-y its lengt$ )it$ a constructorstatement. T$is *rocess in Ja!a is called instantiation 4t$e Ja!a )ord -or creates9. Inorder to instantiate an o%ect )e need to use a constructor -or t$is. e )ill co!er morea%out instantiating o%ects and constructors later. Ta:e note t$at t$e si>e o- an array
cannot %e c$anged once you!e initiali>ed it. For eam*le
//declarationint ages[]%
//instantiate objectages = ne# int[;CC]%
or can also %e )ritten as
88declare and instantiateo%ectint ages[] = ne#
int[;CC]%
In t$e eam*le t$e declaration tells t$eJa!a om*iler t$at t$e identi-ier ages )ill
%e used as t$e name o- an array containingintegers and to create or instantiate a ne)array containing 100 elements.
Instead o- using t$e ne) :ey)ord toinstantiate an array you can alsoautomatically declare construct and assign!alues at once.
Figure /.2: 6nstantiating 3rrays
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 117/244
Eam*les are
//creates an array of boolean variables #it! ientifier//results. 2!is array contains G elements t!at are
//initialiKed to values {true false true false&boolean results[] ={ true false true false &%
//creates an array of G double variables initialiKed//to t!e values {;CC PC JC DN&%double []grades = {;CC PC JC DN&%
//creates an array of Strings #it! identifier days and//initialiKed. 2!is array contains D elements
String days@ GMonH> GTueH> G'edH> GThuH> GFriH> GSatH> GSunHQ
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 118/244
6.% /ccessing an arra# element To access an array element or a *art o- t$e array you use a num%er called an index or
a su%scri*t.
n index number or subscript is assigned to eac$ mem%er o- t$e array allo)ing t$e*rogram and t$e *rogrammer to access indi!idual !alues )$en necessary. Indenum%ers are a&!ays integers. T$ey begin !ith ero and progress sequentia&&y by!ho&e numbers to the end o# the array. Ta:e note t$at t$e elements inside yourarray is -rom 9 to 6sieO#Array3+7,
For eam*le gi!en t$e array )e declared a )$ile ago )e $a!e
//assigns ;C to t!e first element in t!e arrayages[C] = ;C%
//prints t!e last element in t!e arraySystem.out.print(ages[PP]%
Ta:e note t$at once an array is declared and constructed t$e stored !alue o- eac$mem%er o- t$e array )ill %e initiali>ed to >ero -or num%er data. #o)e!er re-erence dataty*es suc$ as 'trings are not initiali>ed to %lan:s or an em*ty string Q. T$ere-ore youmust *o*ulate t$e 'tring arrays e*licitly.
T$e -ollo)ing is a sam*le code on $o) to *rint all t$e elements in t$e array. T$is uses a-or loo* so our code is s$orter.
public class rraySample{public static void main( String[] args {
int[] ages = ne# int[;CC]%
for( int i=C% iU;CC% i44 { System.out.print( ages[i]%
&&
&
Coding <uidelines
1. 6t is usually better to initialiIe or instantiate the array right away after you declare it.
For exampleB the declarationBint Darr ' new int1&&DGis preferred o$erB
int DarrGarr ' new int1&&DG
2. The elements of an nelement array ha$e indexes from & to n1. "ote that there isno array element arrnDP This will result in an arrayindexoutofbounds exception.
. >ou cannot resiIe an array.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 119/244
6.* /rra# lengt(In order to get t$e num%er o- elements in an array you can use t$e &ength -ield o- an
array. T$e lengt$ -ield o- an array returns t$e si>e o- t$e array. It can %e used %y )riting
array+ame.lengt!
For eam*le gi!en t$e *re!ious eam*le )e can re)rite it as
public class rraySample{
public static void main( String[] args {
int[] ages = ne# int[;CC]%
for( int i=C% iUages*length% i44 {System.out.print( ages[i] %
&&
&
Coding <uidelines
1. 5hen creating for loops to process the elements of an arrayB use the arrayob<ectRs lengt( field in the condition statement of the for loop. This will allow theloop to ad<ust automatically for differentsiIed arrays.
2. eclare the siIes of arrays in a a$a program using named constants to ma;ethem easy to change. For exampleB
final int 3883>JS6E ' 1&&&G AAdeclare a constant
. . .intD ages ' new int3883>JS6EDG
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 120/244
Introduction to Programming I 120
6. Multidimensional /rra#s(ultidimensional arrays are im*lemented as arrays o- arrays. (ultidimensional arrays
are declared %y a**ending t$e a**ro*riate num%er o- %rac:et *airs a-ter t$e array name.For eam*le
// integer array N;< 5 ;<J elementsint[][] t#oE = ne# int[N;<][;<J]%
// c!aracter array J 5 ;I 5 <Gc!ar[][][] t!reeE = ne# c!ar[J][;I][<G]%
// String array G ro#s 5 < columnsString[][] dogs = {{ "terry" "bro#n" &
{ "ristin" "#!ite" &{ "toby" "gray"&{ "fido" "blac-"&
b[
To access an element in a multidimensional array is ust t$e same as accessing t$eelements in a one dimensional array. For eam*le to access t$e -irst element in t$e -irstro) o- t$e array dogs )e )rite
System.out.print( dogs[C][C] %
T$is )ill *rint t$e 'tring RterryR on t$e screen.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 121/244
Introduction to Programming I 121
6.6 0-ercises
6.6.1 ,a#s of t(e ee8
reate an array o- 'trings )$ic$ are initiali>ed to t$e H days o- t$e )ee:. For Example,
String days[] = {AMondayB A2uesdayB.&%
sing a )$ileloo* *rint all t$e contents o- t$e array. 4do t$e same -or do)$ile and -orloo*9
6.6.2 <reatest number
sing Bu--ered"eader or J&*tionPane as: -or 10 num%ers -rom t$e user. se an array tostore t$e !alues o- t$ese 10 num%ers. &ut*ut on t$e screen t$e num%er )it$ t$egreatest !alue.
6.6.3 /ddressboo8 0ntries
@i!en t$e -ollo)ing multidimensional array t$at contains address%oo: entries;
String entry = {{"9lorence" "DFN;<FG" "Manila"&{"oyce" "PJFFFFF" "^ueKon 3ity"&{":ecca" "GNIFF<<" "Manila"&&%
Print t$e -ollo)ing entries on screen in t$e -ollo)ing -ormat;
+ame 7 9lorence2el. _ 7 DFN;<FGddress 7 Manila
+ame 7 oyce2el. _ 7 PJFFFFFddress 7 ^ueKon 3ity
+ame 7 :ecca2el. _ 7 GNIFF<<ddress 7 Manila
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 122/244
Introduction to Programming I 122
: "ommand3&ine Arguments
@.1 ObjectivesIn t$is section )e )ill study on $o) to *rocess in*ut -rom t$e commandline %y usingarguments *ass onto a Ja!a *rogram.
t t$e end o- t$e lesson t$e student s$ould %e a%le to;
• Ano) and e*lain )$at a commandline argument is
• @et in*ut -rom t$e user using commandline arguments
• =earn $o) to *ass arguments to your *rograms in +etBeans
@.2 Command"line arguments Ja!a a**lication can acce*t any num%er o- arguments -rom t$e commandline.ommandline arguments allo) t$e user to a--ect t$e o*eration o- an a**lication -or onein!ocation. T$e user enters commandline arguments )$en in!o:ing t$e a**lication ands*eci-ies t$em a-ter t$e name o- t$e class to run.
For eam*le su**ose you $a!e a Ja!a a**lication called 'ort t$at sorts -i!e num%ersyou run it li:e t$is;
Figure 0.1: 8unning with Command4ine 3rguments
Ta:e note t$at t$e arguments are se*arated %y s*aces.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 123/244
Introduction to Programming I 123
In t$e Ja!a language )$en you in!o:e an a**lication t$e runtime system *asses t$ecommandline arguments to t$e a**lications main met$od !ia an array o- 'trings. Eac$'tring in t$e array contains one o- t$e commandline arguments. "emem%er t$edeclaration -or t$e main met$od
public static void main( String[] args
T$e arguments t$at are *assed to your *rogram are sa!ed into an array o- 'tring )it$t$e args identi-ier.
In t$e *re!ious eam*le t$e commandline arguments *assed to t$e 'ort a**lication isan array t$at contains -i!e strings )$ic$ are; R,R RR R3R R2R and R1R. ou can deri!et$e num%er o- commandline arguments )it$ t$e arrays lengt$ attri%ute.
For eam*le
int numberfrgs = args.lengt!%
I- your *rogram needs to su**ort a numeric commandline argument it must con!ert a'tring argument t$at re*resents a num%er suc$ as R3R to a num%er. #eres a codesni**et t$at con!erts a commandline argument to an integer
int firstrg = C%if (args.lengt! C{
firstrg = ,nteger.parse,nt(args[C]%&
*arseInt t$ro)s a +um%erFormatEce*tion 4E""&"9 i- t$e -ormat o- argsX0Y isnt !alid
4not a num%er9.
Coding <uidelines9efore using commandline argumentsB always chec; if the number of argumentsbefore accessing the array elements so that there will be no exception generated.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 124/244
Introduction to Programming I 12
@.3 Command"line arguments in etBeansTo illustrate on $o) to *ass some arguments to your *rograms in +etBeans let us create
a Ja!a *rogram t$at )ill *rint t$e num%er o- arguments and t$e -irst argument *assed toit.
public class 3ommandTine05ample{
public static void main( String[] args {
System.out.println("+umber of arguments=" 4args.lengt!%
System.out.println("9irst rgument="4 args[C]%&
&
+o) run net%eans and create a ne) *roect and name t$is ommand=ineEam*le. o*y
t$e code s$o)n a%o!e and com*ile t$e code. +o) -ollo) t$ese ste*s to *ass argumentsto your *rogram using +etBeans.
lic: on Proects 4encircled %elo)9.
Figure 0.2: -pening )ro<ect File
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 125/244
Introduction to Programming I 12,
"ig$tclic: on t$e ommand=ineEam*le icon and a *o*u* menu )ill a**ear. lic: on
Pro*erties.
Figure 0.: -pening )roperties
T$e Proect Pro*erties dialog )ill t$en a**ear.
Figure 0.%: )roperties ialog
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 126/244
Introduction to Programming I 126
+o) clic: on "un "unning Proect.
Figure 0.+: Clic; -n 8unning )ro<ect
&n t$e rguments tet%o ty*e t$e arguments you )ant to *ass to your *rogram. Int$is case )e ty*ed in t$e arguments , 3 2 1. T$en clic: on t$e &A %utton.
Figure 0.*: Set the Command4ine 3rguments
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 127/244
Introduction to Programming I 12H
+o) try to "+ your *rogram.
Figure 0./: 8unning the )rogram in with the Shortcut 9utton
s you can see $ere t$e out*ut to your *rogram is t$e num%er o- arguments )$ic$ is ,and t$e -irst argument )$ic$ is ,.
Figure 0.0: )rogram -utput
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 128/244
Introduction to Programming I 127
@.% 0-ercises
@.%.1 $rint arguments
@et in*ut -rom t$e user using commandline arguments and *rint all t$e arguments tot$e screen. For eam*le i- t$e user entered
java Hello #orld t!at is all
your *rogram s$ould *rint
Hello#orldt!atisall
@.%.2 /rit(metic Operations
@et t)o num%ers -rom t$e user using commandline arguments and *rint sumdi--erence *roduct and ?uotient o- t$e t)o num%ers. For eam*le i- t$e user entered
java rit!meticperation <C G
your *rogram s$ould *rint
sum = <Gdifference = ;Iproduct = JC@uotient = N
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 129/244
Introduction to Programming I 12<
'or%ing !ith the =a)a "&ass Library
.1 ObjectivesIn t$is section )e )ill introduce some %asic conce*ts o- o%ectoriented *rogramming.=ater on )e )ill discuss t$e conce*t o- classes and o%ects and $o) to use t$eseclasses and t$eir mem%ers. om*arison con!ersion and casting o- o%ects )ill also %eco!ered. For no) )e )ill -ocus on using classes t$at are already de-ined in t$e Ja!aclass li%rary )e )ill discuss later on $o) to create your o)n classes.
t t$e end o- t$e lesson t$e student s$ould %e a%le to;
• E*lain o%ectoriented *rogramming and some o- its conce*ts
• Di--erentiate %et)een classes and o%ects
• Di--erentiate %et)een instance !aria%les8met$ods and class4static9
!aria%les8met$ods
• E*lain )$at met$ods are and $o) to call and *ass *arameters to met$ods
• Identi-y t$e sco*e o- a !aria%le
• ast *rimiti!e data ty*es and o%ects
• om*are o%ects and determine t$e class o- an o%ects
.2 Introduction to Object"Oriented $rogramming&%ect&riented *rogramming or &&P re!ol!es around t$e conce*t o- obCects as t$e%asic elements o- your *rograms. $en )e com*are t$is to t$e *$ysical )orld )e can-ind many o%ects around us suc$ as cars lion *eo*le and so on. T$ese o%ects arec$aracteri>ed %y t$eir properties 6or attributes7 and beha)iors.
For eam*le a car o%ect $as t$e *ro*erties type of transmission manufacturer andcolor . Its %e$a!iors are turningB bra;ing and accelerating. 'imilarly )e can de-inedi--erent *ro*erties and %e$a!ior o- a lion. Please re-er to t$e ta%le %elo) -or t$eeam*les.
Object $roperties Be(avior
ar ty*e o- transmissionmanu-acturercolor
turning%ra:ingaccelerating
=ion eig$t
olor$ungry or not $ungrytamed or )ild
roaringslee*ing$unting
Table 1/: Example of 8eallife -b<ects
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 130/244
Introduction to Programming I 130
it$ t$ese descri*tions t$e o%ects in t$e *$ysical )orld can easily %e modeled asso-t)are o%ects using t$e properties as data and t$e beha)iors as methods. T$esedata and met$ods could e!en %e used in *rogramming games or interacti!e so-t)are tosimulate t$e real)orld o%ects n eam*le )ould %e a car so-t)are o%ect in a racinggame or a lion so-t)are o%ect in an educational interacti!e so-t)are >oo -or :ids.
.3 Classes and Objects
.3.1 ,ifference Bet!een Classes andObjects
In t$e so-t)are )orld an obCect is a so-t)are com*onent )$ose structure is similar too%ects in t$e real )orld. Eac$ o%ect is com*osed o- a set o- data 4*ro*erties8attri%utes9)$ic$ are !aria%les descri%ing t$e essential c$aracteristics o- t$e o%ect and it also
consists o- a set o- methods 4%e$a!ior9 t$at descri%es $o) an o%ect %e$a!es. T$us ano%ect is a so-t)are %undle o- !aria%les and related met$ods. T$e !aria%les and met$odsin a Ja!a o%ect are -ormally :no)n as instance )ariab&es and instance methods todistinguis$ t$em -rom class !aria%les and class met$ods )$ic$ )ill %e discussed later.
T$e c&ass is t$e -undamental structure in o%ectoriented *rogramming. It can %et$oug$t o- as a tem*late a *rototy*e or a %lue*rint o- an o%ect. It consists o- t)o ty*eso- mem%ers )$ic$ are called #ie&ds 6properties or attributes7 and met$ods. Fieldss*eci-iy t$e data ty*es de-ined %y t$e class )$ile met$ods s*eci-y t$e o*erations. no%ect is an instance o- t$e class.
To di--erentiate %et)een classes and o%ects let us discuss an eam*le. $at )e $a!e$ere is a ar lass )$ic$ can %e used to de-ine se!eral ar &%ects. In t$e ta%le s$o)n
%elo) ar and ar B are o%ects o- t$e ar class. T$e class $as fields *late num%ercolor manu-acturer and current s*eed )$ic$ are -illedu* )it$ corres*onding !alues ino%ects ar and ar B. T$e ar $as also some met$ods ccelerate Turn and Bra:e.
"ar "&ass ObCect "ar A ObCect "ar 0
6 n s t a n c e
s
Plate +um%er B 111 / 123
olor Blue "ed
(anu-acturer (itsu%is$i Toyota
urrent '*eed ,0 :m8$ 100 :m8$
6 n s t a n c e ccelerate (et$od
Turn (et$od
Bra:e (et$od
Table 10: Example of Car class and its ob<ects
$en instantiated eac$ o%ect gets a -res$ set o- state !aria%les. #o)e!er t$e met$odim*lementations are s$ared among o%ects o- t$e same class.
lasses *ro!ide t$e %ene-it o- reusabi&ity. 'o-t)are *rogrammers can use a class o!erand o!er again to create many o%ects.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 131/244
Introduction to Programming I 131
.3.2 0ncapsulation
Enca*sulation is t$e met$od o- $iding certain elements o- t$e im*lementation o- acertain class. By *lacing a %oundary around t$e *ro*erties and met$ods o- our o%ects
)e can *re!ent our *rograms -rom $a!ing side e--ects )$erein *rograms $a!e t$eir!aria%les c$anged in une*ected )ays.
e can *re!ent access to our o%ects data %y declaring t$em declaring t$em in a certain)ay suc$ t$at )e can control access to t$em. e )ill learn more a%out $o) Ja!aim*lements enca*sulation as )e discuss more a%out classes.
.3.3 Class Dariables and Met(ods
In addition to t$e instance !aria%les it is also *ossi%le to de-ine c&ass )ariab&es> )$ic$are !aria%les t$at %elong to t$e )$ole class. T$is means t$at it $as t$e same !alue -orall t$e o%ects in t$e same class. T$ey are also called static member )ariab&es.
To clearly descri%e class !aria%les lets go %ac: to our ar class eam*le. 'u**ose t$atour ar class $as one class !aria%le called ount. I- )e c$ange t$e !alue o- ount to 2all o- t$e o%ects o- t$e ar class )ill $a!e t$e !alue 2 -or t$eir ount !aria%le.
"ar "&ass ObCect "ar A ObCect "ar 0
6 n s t a n c e
s
Plate +um%er B 111 / 123
olor Blue "ed
(anu-acturer (itsu%is$i Toyota
urrent '*eed ,0 :m8$ 100 :m8$
C l a s s
ount S 2
6 n s t a n c e ccelerate (et$od
Turn (et$od
Bra:e (et$od
Table 17: Car classR methods and $ariables
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 132/244
Introduction to Programming I 132
.3.% Class Instantiation
To create an o%ect or an instance o- a class )e use t$e ne! o*erator. For eam*le i-you )ant to create an instance o- t$e class 'tring )e )rite t$e -ollo)ing code
String str< = ne# String(AHello #orld$B%
or also e?ui!alent to
String str< = "Hello"%
Figure 7.1: Classs 6nstantiation
T$e ne) o*erator allocates a memory -or t$at o%ect and returns a re#erence o- t$atmemory location to you. $en you create an o%ect you actually in!o:e t$e classconstructor, T$e constructor is a met$od )$ere you *lace all t$e initiali>ations it $ast$e same name as t$e class.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 133/244
Introduction to Programming I 133
.% Met(ods
.%.1 (at are Met(ods and (# :se Met(ods)
In t$e eam*les )e discussed %e-ore )e only $a!e one met$od and t$at is t$e main49
met$od. In Ja!a )e can de-ine many met$ods )$ic$ )e can call -rom di--erent met$ods.
method is a se*arate *iece o- code t$at can %e called %y a main *rogram or any ot$ermet$od to *er-orm some s*eci-ic -unction.
T$e -ollo)ing are c$aracteristics o- met$ods;• It can return one or no !alues
• It may acce*t as many *arameters it needs or no *arameter at all. Parameters are
also called -unction arguments.• -ter t$e met$od $as -inis$ed eecution it goes %ac: to t$e met$od t$at called it.
+o) )$y do )e need to create met$odsG $y dont )e ust *lace all t$e code inside one%ig met$odG T$e $eart o- e--ecti!e *ro%lem sol!ing is in *ro%lem decom*osition. e cando t$is in Ja!a %y creating met$ods to sol!e a s*eci-ic *art o- t$e *ro%lem. Ta:ing a*ro%lem and %rea:ing it into small managea%le *ieces is critical to )riting large*rograms.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 134/244
Introduction to Programming I 13
.%.2 Calling Instance Met(ods and $assingDariables
+o) to illustrate $o) to call met$ods lets use t$e 'tring class as an eam*le. ou canuse t$e Ja!a PI documentation to see all t$e a!aila%le met$ods in t$e 'tring class.=ater on )e )ill create our o)n met$ods %ut -or no) let us use )$at is a!aila%le.
To call an instance method )e )rite t$e -ollo)ing
namefbject.namefMet!od( parameters %
=ets ta:e t)o sam*le met$ods -ound in t$e class 'tring
Method dec&aration $e#inition
public char char4t(int inde1 "eturns t$e c$aracter at t$e s*eci-ied inde.
n inde ranges -rom 0 to lengt$49 1. T$e -irstc$aracter o- t$e se?uence is at inde 0 t$enet at inde 1 and so on as -or arrayindeing.
public boolean e5uals&gnore6ase()tring another)tring
om*ares t$is 'tring to anot$er 'tring ignoringcase considerations. T)o strings are considerede?ual ignoring case i- t$ey are o- t$e samelengt$ and corres*onding c$aracters in t$e t)ostrings are e?ual ignoring case.
Table 2&: Sample =ethods of class String
sing t$e met$ods
String str; = "Hello"%c!ar 5 = str<.c!art(C% //#ill return t!e c!aracter H
//and store it to variable 5
String str< = "!ello"%
//t!is #ill return a boolean value trueboolean result = str;.e@uals,gnore3ase( str; %
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 135/244
Introduction to Programming I 13,
.%.3 $assing Dariables in Met(ods
In our eam*les )e already tried *assing !aria%les to met$ods. #o)e!er )e $a!entdi--erentiated %et)een t$e di--erent ty*es o- !aria%le *assing in Ja!a. T$ere are t)o
ty*es o- *assing data to met$ods t$e -irst one is *ass%y!alue and t$en *ass%yre-erence.
,<,-,+ Pass3by3)a&ue
$en a *ass%y!alue occurs t$e met$od ma:es a co*y o- t$e !alue o- t$e !aria%le*assed to t$e met$od. T$e met$od cannot accidentally modi-y t$e original argumente!en i- it modi-ies t$e *arameters during calculations.
For eam*le
public class 2est)ass:yLalue{
public static void main( String[] args {int i = ;C%//print t!e value of iSystem.out.println( i %
//call met!od test//and pass i to met!od testtest( i ; )ass i as parameter
#!ic! is copied to j
//print t!e value of i. i not c!angedSystem.out.println( i %
&
public static void test( int
77change value o$ parameter = 88;
--
In t$e gi!en eam*le )e called t$e met$od test and *assed t$e !alue o- i as *arameter.T$e !alue o- i is co*ied to t$e !aria%le o- t$e met$od . 'ince is t$e !aria%le c$anged int$e test met$od it )ill not a--ect t$e !aria%le !alue i- i in main since it is a di--erent co*yo- t$e !aria%le.
By de-ault all *rimiti!e data ty*es )$en *assed to a met$od are *ass%y!alue.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 136/244
,<,-,. Pass3by3re#erence
$en a *ass%yre-erence occurs t$e re-erence to an o%ect is *assed to t$e callingmet$od. T$is means t$at t$e met$od ma:es a co*y o- t$e re-erence o- t$e !aria%le
*assed to t$e met$od. #o)e!er unli:e in *ass%y!alue t$e met$od can modi-y t$eactual o%ect t$at t$e re-erence is *ointing to since alt$oug$ di--erent re-erences areused in t$e met$ods t$e location o- t$e data t$ey are *ointing to is t$e same.
For eam*le
class 2est)ass:yQeference{
public static void main( String[] args {//create an array of integersint []ages = {;C ;; ;<&%
//print array values
for( int i=C% iUages.lengt!% i44 {System.out.println( ages[i] %&
)ass ages as parameter#!ic! is copied tovariable arr
//call test and pass reference to arraytest( ages ;
//print array values againfor( int i=C% iUages.lengt!% i44 {
System.out.println( ages[i] %&
&
public static void test( int[] arr
77change values o$ array$or( int i=9; i<arr*length; i++ arr[i] = i + :9;
--
&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 137/244
Figure 7.2: )assbyreference example
Coding<uidelines
3 common misconception about passbyreference in a$a is when creating a swapmethod using a$a references. Ta;e note that a$a manipulates ob<ects Rby referenceBRbut it passes ob<ect references to methods Rby $alue.R 3s a resultB you cannot write astandard swap method to swap ob<ects.
.%.% Calling Static Met(ods
'tatic met$ods are met$ods t$at can %e in!o:ed )it$out instantiating a class 4means)it$out in!o:ing t$e ne) :ey)ord9. 'tatic met$ods %elongs to t$e class as a )$ole andnot to a certain instance 4or o%ect9 o- a class. 'tatic met$ods are distinguis$ed -rominstance met$ods in a class de-inition %y t$e :ey)ord static.
To call a static met$od ust ty*e
3lassname.staticMet!od+ame(params%
Eam*les o- static met$ods )e!e used so -ar in our eam*lesare
//prints data to screen)ystem*out*println(AHello #orldB%
//converts t!e String ;C to an integerint i = &nteger*parse&nt(A;CB%
//Qeturns a String representation of t!e integer argument as an
//unsigned integer base ;IString !e50@uivalent = &nteger*toe1)tring( ;C %
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 138/244
.%.* Scope of a variable
In addition to a !aria%les data ty*e and name a !aria%le $as sco*e. T$e scopedetermines )$ere in t$e *rogram t$e !aria%le is accessi%le. T$e sco*e also determines
t$e li-etime o- a !aria%le or $o) long t$e !aria%le can eist in memory. T$e sco*e isdetermined %y )$ere t$e !aria%le declaration is *laced in t$e *rogram.
To sim*li-y t$ings ust t$in: o- t$e sco*e as anyt$ing %et)een t$e curly %races Z...b.T$e outer curly %races is called t$e outer %loc:s and t$e inner curly %races is calledinner %loc:s.
I- you declare !aria%les in t$e outer %loc: t$ey are !isi%le 4i.e. usa%le9 %y t$e *rogramlines inside t$e inner %loc:s. #o)e!er i- you declare !aria%les in t$e inner %loc: youcannot e*ect t$e outer %loc: to see it.
!aria%les sco*e is inside t$e %loc: )$ere it is declared starting -rom t$e *oint )$ere it
is declared and in t$e inner %loc:s.
For eam*le gi!en t$e -ollo)ing code sni**et
public class Scope05ample
{
public static void main( String[] args {
int i = C%
int j = C%
//... some code !ere
0A {
int - = C%
int m = C%$
"
E int n = C%
&
&
T$e code )e $a!e $ere re*resents -i!e sco*es indicated %y t$e lines and t$e letters
re*resenting t$e sco*e. @i!en t$e !aria%les i:m and n and t$e -i!e sco*es BDand E )e $a!e t$e -ollo)ing sco*es -or eac$ !aria%le;
T$e sco*e o- !aria%le i is .T$e sco*e o- !aria%le is B.T$e sco*e o- !aria%le : is .T$e sco*e o- !aria%le m is D.T$e sco*e o- !aria%le n is E.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 139/244
+o) gi!en t$e t)o met$ods main and test in our *re!ious eam*les
class 2est)ass:yQeference{
public static void main( String[] args {//create an array of integersint []ages = {;C ;; ;<&%
//print array valuesfor( int i=C% iUages.lengt!% i44 {
System.out.println( ages[i] %&
A//call test and pass reference to arraytest( ages %
//print array values againfor( int i=C% iUages.lengt!% i44 {
" System.out.println( ages[i] %&
&
public static void test( int[] arr {//c!ange values of arrayfor( int i=C% iUarr.lengt!% i44 { $
arr[i] = i 4 NC%&
&&
In t$e main met$od t$e sco*e o- t$e !aria%les are
agesXY sco*e
i in B sco*e Bi in L sco*e
In t$e test met$od t$e sco*e o-t$e !aria%les are
arrXY sco*e D
i in E sco*e E
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 140/244
Introduction to Programming I 10
$en declaring !aria%les only one !aria%le )it$ a gi!en identi-ier or name can %edeclared in a sco*e. T$at means t$at i- you $a!e t$e -ollo)ing declaration
{int test = ;C%int test = <C%
&
your com*iler )ill generate an error since you s$ould $a!e uni?ue names -or your!aria%les in one %loc:. #o)e!er you can $a!e t)o !aria%les o- t$e same name i- t$eyare not declared in t$e same %loc:. For eam*le
int test = C%System.out.print( test %//..some code !ere{
int test = <C%
System.out.print( test %&
$en t$e -irst 'ystem.out.*rint is in!o:e it *rints t$e !alue o- t$e -irst test !aria%lesince it is t$e !aria%le seen at t$at sco*e. For t$e second 'ystem.out.*rint t$e !alue 20is *rinted since it is t$e closest test !aria%le seen at t$at sco*e.
Coding<uidelines
3$oid ha$ing $ariables of the same name declared inside one method to a$oidconfusion.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 141/244
Introduction to Programming I 11
.* Casting= Converting and ComparingObjects
In t$is section )e are going to learn $o) to do typecasting. Ty*ecasting or casting ist$e *rocess o- con!erting a data o- a certain data ty*e to anot$er data ty*e. e )ill alsolearn $o) to con!ert *rimiti!e data ty*es to o%ects and !ice !ersa. nd -inally )e aregoing to learn $o) to com*are o%ects.
.*.1 Casting $rimitive +#pes
asting %et)een *rimiti!e ty*es ena%les you to con!ert t$e !alue o- one data -rom onety*e to anot$er *rimiti!e ty*e. T$is commonly occurs %et)een numeric ty*es.
T$ere is one *rimiti!e data ty*e t$at )e cannot do casting t$oug$ and t$at is t$e
boo&ean data ty*e.
n eam*le o- ty*ecasting is )$en you )ant to store an integer data to a !aria%le o-data ty*e dou%le. For eam*le
int num,nt = ;C%double numEouble = num,nt% //implicit cast
In t$is eam*le since t$e destination !aria%le 4dou%le9 $olds a larger !alue t$an )$at)e )ill *lace inside it t$e data is im*licitly casted to data ty*e dou%le.
not$er eam*le is )$en )e )ant to ty*ecast an int to a c$ar !alue or !ice !ersa. c$aracter can %e used as an int %ecause eac$ c$aracter $as a corres*onding numeric
code t$at re*resents its *osition in t$e c$aracter set. I- t$e !aria%le i $as t$e !alue 6,t$e cast 4c$ar9i *roduces t$e c$aracter !alue . T$e numeric code associated )it$ aca*ital is 6, according to t$e 'II c$aracter set and Ja!a ado*ted t$is as *art o- itsc$aracter su**ort. For eam*le
c!ar val3!ar = ??%int val,nt = val3!ar%System.out.print( val&nt % //e5plicit cast7 output IN
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 142/244
Introduction to Programming I 12
$en )e con!ert a data t$at $as a large ty*e to a smaller ty*e )e must use an exp&icitcast. E*licit casts ta:e t$e -ollo)ing -orm;
(data2ypevalue
)$ere
dataType is t$e name o- t$e data ty*e youre con!erting to$alueB is an e*ression t$at results in t$e !alue o- t$e source ty*e.
For eam*le
double valEouble = ;C.;<%int val,nt = (intvalouble; //convert valEouble to int type
double 5 = ;C.<%int y = <%
int result = (int(17y% //typecast result of operation toint
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 143/244
.*.2 Casting Objects
Instances o- classes also can %e cast into instances o- ot$er classes )it$ onerestriction; The source and destination c&asses must be re&ated by inheritance
one c&ass must be a subc&ass o# the other, ell co!er more a%out in$eritance later.
nalogous to con!erting a *rimiti!e !alue to a larger ty*e some o%ects mig$t not needto %e cast e*licitly. In *articular %ecause a su%class contains all t$e same in-ormationas its su*erclass you can use an instance o- a su%class any)$ere a su*erclass ise*ected.
For eam*le consider a met$od t$at ta:es t)o arguments one o- ty*e &%ect andanot$er o- ty*e indo). ou can *ass an instance o- any class -or t$e &%ect argument%ecause all Ja!a classes are su%classes o- &%ect. For t$e indo) argument you can*ass in its su%classes suc$ as Dialog FileDialog and Frame. T$is is true any)$ere in a*rogram not ust inside met$od calls. I- you $ad a !aria%le de-ined as class indo) you
could assign o%ects o- t$at class or any o- its su%classes to t$at !aria%le )it$out casting.
Figure 7.: Sample Class !ierarchy
T$is is true in t$e re!erse and you can use a su*erclass )$en a su%class is e*ected.T$ere is a catc$ $o)e!er; 0ecause subc&asses contain more beha)ior than theirsuperc&asses> thereUs a &oss in precision in)o&)ed, T$ose su*erclass o%ects mig$tnot $a!e all t$e %e$a!ior needed to act in *lace o- a su%class o%ect. For eam*le i- you$a!e an o*eration t$at calls met$ods in o%ects o- t$e class Integer using an o%ect o-class +um%er )ont include many met$ods s*eci-ied in Integer. Errors occur i- you try tocall met$ods t$at t$e destination o%ect doesnt $a!e.
To use su*erclass o%ects )$ere su%class o%ects are e*ected you must cast t$eme*licitly. ou )ont lose any in-ormation in t$e cast %ut you gain all t$e met$ods and
!aria%les t$at t$e su%class de-ines. To cast an o%ect to anot$er class you use t$e sameo*eration as -or *rimiti!e ty*es;
To cast
(classnameobject
)$ere
classnameB is t$e name o- t$e destination class
ob<ectB is a re-erence to t$e source o%ect.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 144/244
• /ote2 t$at casting creates a re-erence to t$e old o%ect o- t$e ty*e classname[ t$e old
o%ect continues to eist as it did %e-ore.
Figure 7.%: Class !ierarchy for superclass Employee
T$e -ollo)ing eam*le casts an instance o- t$e class VicePresident to an instance o- t$eclass Em*loyee[ VicePresident is a su%class o- Em*loyee )it$ more in-ormation )$ic$$ere de-ines t$at t$e VicePresident $as eecuti!e )as$room *ri!ileges
0mployee emp = ne# 0mployee(%Lice)resident veep = ne# Lice)resident(%emp = veep% // no cast needed for up#ard useveep = (Lice)residentemp% // must cast e5plicitly3asting
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 145/244
.*.3 Converting $rimitive +#pes to Objects and DiceDersa
&ne t$ing you cant do under any circumstance is cast -rom an o%ect to a *rimiti!e dataty*e or !ice !ersa. Primiti!e ty*es and o%ects are !ery di--erent t$ings in Ja!a and youcant automatically cast %et)een t$e t)o or use t$em interc$angea%ly.
s an alternati!e t$e Ca)a,&ang *ac:age includes classes t$at corres*ond to eac$*rimiti!e data ty*e; Float Boolean Byte and so on. (ost o- t$ese classes $a!e t$esame names as t$e data ty*es ece*t t$at t$e class names %egin )it$ a ca*ital letter4'$ort instead o- s$ort Dou%le instead o- dou%le and t$e li:e9. lso t)o classes $a!enames t$at di--er -rom t$e corres*onding data ty*e; $aracter is used -or c$ar !aria%lesand Integer -or int !aria%les. 6"a&&ed 'rapper "&asses7
Ja!a treats t$e data ty*es and t$eir class !ersions !ery di--erently and a *rogram )ontcom*ile success-ully i- you use one )$en t$e ot$er is e*ected.
sing t$e classes t$at corres*ond to eac$ *rimiti!e ty*e you can create an o%ect t$at$olds t$e same !alue.
Examp&es2
//2!e follo#ing statement creates an instance of t!e ,nteger// class #it! t!e integer value DJC; (primitive bject&nteger data6ount = ne &nteger(9?;
//2!e follo#ing statement converts an ,nteger object to// its primitive data type int. 2!e result is an int #it!//value DJC;
int ne6ount = data6ount*int@alue(;
// common translation you need in programs// is converting a String to a numeric type suc! as an int// bjectprimitive)tring pennsylvania = "A:999";int penn = &nteger*parse&nt(pennsylvania;
• "A1TIO/2 T$e Void class re*resents not$ing in Ja!a so t$eres no reason it )ould %e
used )$en translating %et)een *rimiti!e !alues and o%ects. Its a *lace$older -or t$e
!oid :ey)ord )$ic$ is used in met$od de-initions to indicate t$at t$e met$od does
not return a !alue.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 146/244
.*.% Comparing Objects
In our *re!ious discussions )e learned a%out o*erators -or com*aring !aluese?ualnot e?ual less t$an and so on. (ost o- t$ese o*erators )or: only on *rimiti!e ty*es not
on o%ects. I- you try to use ot$er !alues as o*erands t$e Ja!a com*iler *roduces errors.
T$e ece*tions to t$is rule are t$e o*erators -or e?uality; SS 4e?ual9 and S 4not e?ual9.$en a**lied to o%ects t$ese o*erators dont do )$at you mig$t -irst e*ect. Instead o-c$ec:ing )$et$er one o%ect $as t$e same !alue as t$e ot$er o%ect t$ey determine)$et$er %ot$ sides o- t$e o*erator re-er to t$e same o%ect.
To com*are instances o- a class and $a!e meaning-ul results you must im*lements*ecial met$ods in your class and call t$ose met$ods. good eam*le o- t$is is t$e'tring class.
It is *ossi%le to $a!e t)o di--erent 'tring o%ects t$at contain t$e same !alues. I- you
)ere to em*loy t$e SS o*erator to com*are t$ese o%ects $o)e!er t$ey )ould %econsidered une?ual. lt$oug$ t$eir contents matc$ t$ey are not t$e same o%ect.
To see )$et$er t)o 'tring o%ects $a!e matc$ing !alues a met$od o- t$e class callede?uals49 is used. T$e met$od tests eac$ c$aracter in t$e string and returns true i- t$et)o strings $a!e t$e same !alues.
T$e -ollo)ing code illustrates t$is
class 0@uals2est {public static void main(String[] arguments {String str; str<%str; = "9ree t!e bound periodicals."%
str< = str;%
System.out.println("String;7 " 4 str;%System.out.println("String<7 " 4 str<%System.out.println("Same objectZ " 4 (str; == str<%
str< = ne# String(str;%
System.out.println("String;7 " 4 str;%System.out.println("String<7 " 4 str<%System.out.println("Same objectZ " 4 (str; == str<%System.out.println("Same valueZ " 4 str;.e@uals(str<%
&&
T$is *rograms out*ut is as -ollo)s
&TPT;String;7 9ree t!e bound periodicals.String<7 9ree t!e bound periodicals.Same objectZ trueString;7 9ree t!e bound periodicals.String<7 9ree t!e bound periodicals.Same objectZ falseSame valueZ 2rue
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 147/244
+o) lets discuss t$e code.
String str; str<%str; = "9ree t!e bound periodicals."%
Figure 7.+: 9oth references point to the same ob<ect
T$e -irst *art o- t$is *rogram declares t)o !aria%les 4str1 and str29 assigns t$e literalRFree t$e %ound *eriodicals.R to str1 and t$en assigns t$at !alue to str2. s you learnedearlier str1 and str2 no) *oint to t$e same o%ect and t$e e?uality test *ro!es t$at.
str< = ne# String(str;%
In t$e second *art o- t$is *rogram you create a ne) 'tring o%ect )it$ t$e same !alueas str1 and assign str2 to t$at ne) 'tring o%ect. +o) you $a!e t)o di--erent stringo%ects in str1 and str2 %ot$ )it$ t$e same !alue. Testing t$em to see )$et$er t$eyret$e same o%ect %y using t$e SS o*erator returns t$e e*ected ans)er; -alset$ey arenot t$e same o%ect in memory. Testing t$em using t$e e?uals49 met$od also returns t$ee*ected ans)er; truet$ey $a!e t$e same !alues.
Figure 7.*: 8eferences now point to different ob<ects
• /OTE2 $y cant you ust use anot$er literal )$en you c$ange str2 rat$er t$an using
ne)G 'tring literals are o*timi>ed in Ja!a[ i- you create a string using a literal andt$en use anot$er literal )it$ t$e same c$aracters Ja!a :no)s enoug$ to gi!e you t$e
-irst 'tring o%ect %ac:. Bot$ strings are t$e same o%ects[ you $a!e to go out o- your)ay to create t)o se*arate o%ects.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 148/244
.*.* ,etermining t(e Class of an Object
ant to -ind out )$at an o%ects class isG #eres t$e )ay to do it -or an o%ect assignedto t$e !aria%le :ey;
1. T$e get"&ass67 method returns a lass o%ect 4)$ere lass is itsel- a class9 t$at $asa met$od called get+ame49. In turn get+ame49 returns a string re*resenting t$ename o- t$e class.
For Eam*le
String name = -ey.get3lass(.get+ame(%
., The instanceO# operator
T$e instance&- $as t)o o*erands; a re-erence to an o%ect on t$e le-t and a class
name on t$e rig$t. T$e e*ression returns true or -alse %ased on )$et$er t$e o%ect isan instance o- t$e named class or any o- t$at classs su%classes.
For Eam*le
boolean e5; = "2e5as" instanceof String% // truebject pt = ne# )oint(;C ;C%boolean e5< = pt instanceof String% // false
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 149/244
. 0-ercises
..1 ,efining terms
In your o)n )ords de-ine t$e -ollo)ing terms;
1. lass2. &%ect3. Instantiate. Instance Varia%le,. Instance (et$od6. lass Varia%les or static mem%er !aria%lesH. onstructor
..2 7ava Scavenger unt
Pi*oy is a ne)%ie in t$e Ja!a *rogramming language. #e ust $eard t$at t$ere are
already readytouse PIs in Ja!a t$at one could use in t$eir *rograms and $es eager totry t$em out. T$e *ro%lem is Pi*oy does not $a!e a co*y o- t$e Ja!a Documentationand $e also doesnt $a!e an internet access so t$eres no )ay -or $im to !ie) t$e Ja!aPIs.
our tas: is to $el* Pi*oy loo: -or t$e PIs 4**lication Programming Inter-ace9. ous$ould state t$e class )$ere t$e met$od %elongs t$e met$od declaration and a sam*leusage o- t$e said met$od.
For eam*le i- Pi*oy )ants to :no) t$e met$od t$at con!erts a 'tring to integer yourans)er s$ould %e;
"&ass2 IntegerMethod $ec&aration2 *u%lic static int *arseInt4 'tring !alue 9Samp&e 1sage2
'tring strValue S R100R[int !alue S Integer.*arseInt4 strValue 9[
(a:e sure t$at t$e sni**et o- code you )rite in your sam*le usage com*iles and out*utst$e correct ans)er so as not to con-use Pi*oy. 6int2 A&& methods are in the Ca)a,&ang pac%age7, In cases )$ere you can -ind more met$ods t$at can accom*lis$t$e tas: gi!e only one.
/o! &etUs start the search1. =oo: -or a met$od t$at c$ec:s i- a certain 'tring ends )it$ a certain su--i. For
eam*le i- t$e gi!en string is R#elloR t$e met$od s$ould return true t$e su--i gi!enis RloR and -alse i- t$e gi!en su--i is Ral*R.
2. =oo: -or t$e met$od t$at determines t$e c$aracter re*resentation -or a s*eci-ic digitin t$e s*eci-ied radi. For eam*le i- t$e in*ut digit is 1, and t$e radi is 16 t$emet$od )ould return t$e c$aracter F since F is t$e $eadecimal re*resentation -ort$e num%er 1, 4%ase 109.
3. =oo: -or t$e met$od t$at terminates t$e currently running Ja!a Virtual (ac$ine
. =oo: -or t$e met$od t$at gets t$e -loor o- a dou%le !alue. For eam*le i- I in*ut a3.13 t$e met$od s$ould return t$e !alue 3.
,. =oo: -or t$e met$od t$at determines i- a certain c$aracter is a digit. For eam*le i- Iin*ut 3 it returns t$e !alue true.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 150/244
Introduction to Programming I 1,0
+9 "reating your o!n "&asses
15.1 Objectives+o) t$at )e!e studied on $o) to use eisting classes -rom t$e Ja!a class li%rary )e )illno) %e studying on $o) to )rite our o)n classes. For t$is section in order to easilyunderstand $o) to create classes )e )ill ma:e a sam*le class )$erein )e )ill add moredata and -unctionality as )e go along t$e )ay.
e )ill create a class t$at contains in-ormation o- a 'tudent and o*erations needed -or acertain student record.
T$ings to ta:e note o- -or t$e synta de-ined in t$is section and -or t$e ot$er sections;
U means t$at t$ere may %e 0 or more occurrences o- t$e line
)$ereit )as a**lied to.descri*tion indicates t$at you $a!e to su%stitute an actual !alue -or t$is *art
instead o- ty*ing it as it is.XY indicates t$at t$is *art is o*tional
t t$e end o- t$e lesson t$e student s$ould %e a%le to;
• reate t$eir o)n classes
• Declare attri%utes and met$ods -or t$eir classes
• se t$e t$is re-erence to access instance data
• reate and call o!erloaded met$ods
• Im*ort and create *ac:ages
• se access modi-iers to control access to class mem%ers
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 151/244
Introduction to Programming I 1,1
15.2 ,efining #our o!n classesBe-ore )riting your class t$in: -irst on )$ere you )ill %e using your class and $o) your
class )ill %e used. T$in: o- an a**ro*riate name -or t$e class and list all t$e in-ormationor *ro*erties t$at you )ant your class to contain. lso list do)n t$e met$ods t$at you)ill %e using -or your class.
To de-ine a class )e )rite
Umodifier class Uname {UattributeEeclaration*UconstructorEeclaration*Umet!odEeclaration*
&
)$eremodifierQ is an access modi-ier )$ic$ may %e com%ined )it$ ot$er ty*es o- modi-ier.
Coding<uidelines
8emember that for a tople$el classB the only $alid access modifiers are public and pac;age ,i.e.B if no access modifier prefixes the class ;eyword.
In t$is section )e )ill %e creating a class t$at )ill contain a student record. 'ince )e!ealready identi-ied t$e *ur*ose o- our class )e can no) name it. n a**ro*riate name -orour class )ould %e StudentQecord.
+o) to de-ine our class )e )rite
public class )tudent%ecord {
//#e?ll add more code !ere later&
)$ere*u%lic means t$at our class is accessi%le to ot$er classes outside t$e
*ac:ageclass t$is is t$e :ey)ord used to create a class in Ja!a
'tudent"ecord a uni?ue identi-ier t$at descri%es our class
"oding ?uide&ines2
1. Thin; of an appropriate name for your class. onRt <ust call your class U> orany random names you can thin; of.
2. Class names should start with a C3)6T34 letter.
. The filename of your class should ha$e the S3=E "3=E as your public class name.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 152/244
Introduction to Programming I 1,2
15.3 ,eclaring /ttributesTo declare a certain attri%ute -or our class )e )rite
Umodifier Utype Uname [= Udefault\value]%
+o) let us )rite do)n t$e list o- attri%utes t$at a student record can contain. For eac$in-ormation also list )$at data ty*es )ould %e a**ro*riate to use. For eam*le youdont )ant to $a!e a data ty*e int -or a students name or a 'tring -or a studentsgrade.
T$e -ollo)ing are some sam*le in-ormation )e )ant to add to t$e student record.
name 'tringaddress 'tringage int
mat$ grade dou%leenglis$ grade dou%lescience grade dou%lea!erage grade dou%le
ou can add more in-ormation i- you )ant to its all really u* to you. But -or t$iseam*le )e )ill %e using t$ese in-ormation.
15.3.1 Instance Dariables
+o) t$at )e $a!e a list o- all t$e attri%utes )e )ant to add to our class let us no) addt$em to our code. 'ince )e )ant t$ese attri%utes to %e uni?ue -or eac$ o%ect 4or -oreac$ student9 )e s$ould declare t$em as instance !aria%les.
For eam*le
)$ere
public class )tudent%ecord {
private String name% private String address% private int age% private double mat!Rrade% private double englis!Rrade% private double scienceRrade% private double average%//#e?ll add more code !ere later
&
*ri!ate $ere means t$at t$e !aria%les are only accessi%le )it$in t$e class. &t$er o%ectscannot access t$ese !aria%les directly. e )ill co!er more a%out accessi%ility later.
"oding ?uide&ines2
1. eclare all your instance $ariables on the top of the class declaration.
2. eclare one $ariable for each line.. 6nstance $ariablesB li;e any other $ariables should start with a S=344 letter.%. Lse an appropriate data type for each $ariable you declare.+. eclare instance $ariables as pri$ate so that only class methods can access
them directly.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 153/244
15.3.2 Class Dariables or Static Dariables
side -rom instance !aria%les )e can also declare class !aria%les or !aria%les t$at%elong to t$e class as a )$ole. T$e !alue o- t$ese !aria%les are t$e same -or all t$e
o%ects o- t$e same class. +o) su**ose )e )ant to :no) t$e total num%er o- studentrecords )e $a!e -or t$e )$ole class )e can declare one static !aria%le t$at )ill $old t$is!alue. =et us call t$is as studentount.
To declare a static !aria%le
public class )tudent%ecord {
//instance variables #e !ave declared
private static int student6ount;
//#e?ll add more code !ere later
&
)e use t$e :ey)ord static to indicate t$at a !aria%le is a static !aria%le.
'o -ar our )$ole code no) loo:s li:e t$is.
public class )tudent%ecord {
private String name%private String address%private int age%private double mat!Rrade%private double englis!Rrade%private double scienceRrade%
private double average%
private static int student3ount%
//#e?ll add more code !ere later&
15.% ,eclaring Met(odsBe-ore )e discuss )$at met$ods )e )ant our class to $a!e let us -irst ta:e a loo: at t$egeneral synta -or declaring met$ods.
To declare met$ods )e )rite
Umodifier Ureturn2ype Uname(Uparameter* {Ustatement*
&
)$eremodi-ier can carry a num%er o- di--erent modi-iers
returnTy*e can %e any data ty*e 4including !oid9name can %e any !alid identi-ier*arameter ;;S *arameterCty*e *arameterCnameXY
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 154/244
15.%.1 /ccessor met(ods
In order to im*lement enca*sulation t$at is )e dont )ant any o%ects to ust accessour data anytime )e declare t$e -ields or attri%utes o- our classes as *ri!ate. #o)e!er
t$ere are times )$erein )e )ant ot$er o%ects to access *ri!ate data. In order to do t$is)e create accessor met$ods.
Accessor methods are used to read !alues -rom class !aria%les 4instance8static9. naccessor met$od usually starts )it$ a getV/ameO#Instance*ariab&eW, It also returnsa !alue.
For our eam*le )e )ant an accessor met$od t$at can read t$e name address englis$grade mat$ grade and science grade o- t$e student.
+o) lets ta:e a loo: at one im*lementation o- an accessor met$od
public class StudentQecord{private String name%
77
public )tring getBame(return name;
-&
)$ere
*u%lic means t$at t$e met$od can %e called -rom o%ects outside t$e class'tring is t$e return ty*e o- t$e met$od. T$is means t$at t$e met$od s$ould
return a !alue o- ty*e 'tringget+ame t$e name o- t$e met$od
49 t$is means t$at our met$od does not $a!e any *arameters
T$e statement
return name%
in our *rogram signi-ies t$at it )ill return t$e !alue o- t$e instance !aria%le name to t$ecalling met$od. Ta:e note t$at t$e return ty*e o- t$e met$od s$ould $a!e t$e same dataty*e as t$e data in t$e return statement. ou usually encounter t$e -ollo)ing error i- t$et)o does not $a!e t$e same data ty*e
StudentQecord.java7;G7 incompatible typesfound 7 intre@uired7 java.lang.String
return age%Y
; error
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 155/244
not$er eam*le o- an accessor met$od is t$e get!erage met$od
public class StudentQecord{
private String name%77
public double get4verage(
double result = 9;result = ( mathCrade+englishCrade+scienceCrade 78;
return result;-
&
T$e get!erage met$od com*utes t$e a!erage o- t$e 3 grades and returns t$e
result.
15.%.2 Mutator Met(ods
+o) )$at i- )e )ant ot$er o%ects to alter our dataG $at )e do is )e *ro!ide met$odst$at can )rite or c$ange !alues o- our class !aria%les 4instance8static9. e call t$esemet$ods mutator methods, mutator met$od is usuallyu )ritten assetV/ameO#Instance*ariab&eW,
+o) lets ta:e a loo: at one im*lementation o- a mutator met$od
public class StudentQecord
{private String name%
77
public void setBame( )tring temp name = temp;
-&
)$ere
*u%lic means t$at t$e met$od can %e called -rom o%ects outside t$e class!oid imeans t$at t$e met$od does not return any !alue
set+ame t$e name o- t$e met$od4'tring tem*9 *arameter t$at )ill %e used inside our met$od
T$e statement
name = temp%
assigns t$e !alue o- tem* to name and t$us c$anges t$e data inside t$e instance!aria%le name.
Ta:e note t$at mutator met$ods dont return !alues. #o)e!er it contains some *rogramargument or arguments t$at )ill %e used inside t$e met$od.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 156/244
15.%.3 Multiple 4eturn statements
ou can $a!e multi*le return statements -or a met$od as long as t$ey are not on t$esame %loc:. ou can also use constants to return !alues instead o- !aria%les.
For eam*le consider t$e met$od
public String get+umber,n'ords( int num {
String default+um = "Kero"%
if( num == ; {return "one"; //return a constant
&else if( num == <{
return "to"; //return a constant&
//return a variablereturn default+um%
&
15.%.% Static met(ods
For t$e static !aria%le studentount )e can create a static met$od to access its !alue.
public class StudentQecord{
private static int student3ount%
public static int get)tudent6ount(
return student6ount;-
&
)$ere*u%lic means t$at t$e met$od can %e called -rom o%ects outside t$e
classstatic means t$at t$e met$od is static and s$ould %e called %y
ty*ingXlass+ameY.Xmet$od+ameY. For eam*le in t$is case)e call t$e met$od StudentQecord.getStudent3ount(
int is t$e return ty*e o- t$e met$od. T$is means t$at t$e met$ods$ould return a !alue o- ty*e int
get'tudentount t$e name o- t$e met$od
49 t$is means t$at our met$od does not $a!e any*arameters
For no) get'tudentount )ill al)ays return t$e !alue >ero since )e $a!ent doneanyt$ing yet in our *rogram in order to set its !alue. e )ill try to c$ange t$e !alue o-studentount later on )$en )e discuss constructors.
Coding<uidelines
1. =ethod names should start with a S=344letter.
2. =ethod names should be$erbs
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 157/244
. 3lways pro$ide documentation before the declaration of the method. >ou canuse <a$adocs style for this. )lease see example.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 158/244
15.%.* Sample Source Code for Student4ecord class
#ere is t$e code -or our 'tudent"ecord class
public class StudentQecord{
private String name%private String address%private int age%private double mat!Rrade%private double englis!Rrade%private double scienceRrade%private double average%
private static int student3ount%
/*** Qeturns t!e name of t!e student
*/public String get+ame({return name%
&
/*** 3!anges t!e name of t!e student*/public void set+ame( String temp {name = temp%
&
// ot!er code !ere ....
/*** 3omputes t!e average of t!e englis! mat! and science* grades*/public double getverage({
double result = C%result = ( mat!Rrade4englis!Rrade4scienceRrade /F%
return result%&
/*** returns t!e number of instances of StudentQecords*/public static int getStudent3ount({return student3ount%
&&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 159/244
+o) $eres a sam*le code o- a class t$at uses our 'tudent"ecord class.
public class StudentQecord05ample{
public static void main( String[] args {
//create t!ree objects for Student recordStudentQecord annaQecord = ne# StudentQecord(%StudentQecord bea!Qecord = ne# StudentQecord(%StudentQecord crisQecord = ne# StudentQecord(%
//set t!e name of t!e studentsannaQecord.set+ame("nna"%bea!Qecord.set+ame(":ea!"%crisQecord.set+ame("3ris"%
//print anna?s nameSystem.out.println( annaQecord.get+ame( %
//print number of students
System.out.println("3ount="4StudentQecord.getStudent3ount(%&
&
T$e out*ut o- t$is *rogram is
nnaStudent 3ount = C
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 160/244
15.* +(e t(is referenceT$e this re-erence is used to access t$e instance !aria%les s$ado)ed %y t$e *arameters.
To understand t$is %etter lets ta:e -or eam*le t$e setge met$od. 'u**ose )e $a!et$e -ollo)ing declaration -or setge.
public void setge( int age {age = age% //'Q+R$$$
&
T$e *arameter name in t$is declaration is age )$ic$ $as t$e same name as t$e instance!aria%le age. 'ince t$e *arameter age is t$e closest declaration to t$e met$od t$e !alueo- t$e *arameter age )ill %e used. 'o in t$e statement
age = age%
)e are ust assigning t$e !alue o- t$e *arameter age to itsel- T$is is not )$at )e )antto $a**en in our code. In order to correct t$is mista:e )e use t$e this re-erence. Touse t$e t$is re-erence )e ty*e
t!is.Unamef2!e,nstanceLariable
'o -or eam*le )e can no) re)rite our code to
public void setge( int age {this*age = age;
b
T$is met$od )ill t$en assign t$e !alue o- t$e *arameter age to t$e instance !aria%le o-
t$e o%ect 'tudent"ecord.
/OTE2 Bou can on&y use the this re#erence #or instance )ariab&es and /OT staticor c&ass )ariab&es,
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 161/244
Introduction to Programming I 160
15. Overloading Met(odsIn our classes )e )ant to sometimes create met$ods t$at $as t$e same names %ut
-unction di--erently de*ending on t$e *arameters t$at are *assed to t$em. T$is ca*a%ilityis *ossi%le in Ja!a and it is called Method O)er&oading.
Method o)er&oading allo)s a met$od )it$ t$e same name %ut di--erent *arameters to$a!e di--erent im*lementations and return !alues o- di--erent ty*es. "at$er t$an in!entne) names all t$e time met$od o!erloading can %e used )$en t$e same o*eration $asdi--erent im*lementations.
For eam*le in our 'tudent"ecord class )e )ant to $a!e a met$od t$at *rintsin-ormation a%out t$e student. #o)e!er )e )ant t$e *rint met$od to *rint t$ingsdi--erently de*ending on t$e *arameters )e *ass to it. For eam*le )$en )e *ass a'tring )e )ant t$e *rint met$od to *rint out t$e name address and age o- t$e student.$en )e *ass 3 dou%le !alues )e )ant t$e met$od to *rint t$e students name and
grades.
e $a!e t$e -ollo)ing o!erloaded met$ods inside our 'tudent"ecord class
public void print( )tring temp { System.out.println("+ame7" 4 name%System.out.println("ddress7" 4 address%System.out.println("ge7" 4 age%
&
public void print(double eCrade, double mCrade, double sCradeSystem.out.println("+ame7" 4 name%System.out.println("Mat! Rrade7" 4 mRrade%System.out.println("0nglis! Rrade7" 4 eRrade%System.out.println("Science Rrade7" 4 sRrade%
&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 162/244
Introduction to Programming I 161
$en )e try to call t$is in t$e -ollo)ing main met$od
public static void main( String[] args {
StudentQecord annaQecord = ne# StudentQecord(%
annaQecord.set+ame("nna"%annaQecord.setddress(")!ilippines"%annaQecord.setge(;N%annaQecord.setMat!Rrade(JC%annaQecord.set0nglis!Rrade(PN.N%annaQecord.setScienceRrade(;CC%
//overloaded met!odsannaQecord.print( annaQecord.get+ame( %annaQecord.print( annaQecord.get0nglis!Rrade(
annaQecord.getMat!Rrade(annaQecord.getScienceRrade(%
&
)e )ill $a!e t$e out*ut -or t$e -irst call to *rint
+ame7nnaddress7)!ilippinesge7;N
)e )ill $a!e t$e out*ut -or t$e second call to *rint
+ame7nnaMat! Rrade7JC.C0nglis! Rrade7PN.NScience Rrade7;CC.C
l)ays remem%er t$at o!erloaded met$ods $a!e t$e -ollo)ing *ro*erties – t$e same name
– di##erent parameters
– return ty*es can %e di--erent or t$e same
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 163/244
Introduction to Programming I 162
15.6 ,eclaring Constructorse $a!e discussed %e-ore t$e conce*t o- constructors. onstructors are im*ortant in
instantiating an o%ect. It is a met$od )$ere all t$e initiali>ations are *laced.
T$e -ollo)ing are t$e *ro*erties o- a constructor;
1. onstructors $a!e t$e same name as the c&ass2. constructor is ust li:e an ordinary met$od $o)e!er only t$e -ollo)ing in-ormation
can %e *laced in t$e $eader o- t$e constructorsco*e or accessi%ility identi-ier 4li:e *u%lic...9 constructors name and *arameters i- it$as any.
3. onstructors does not ha)e any return )a&ue
. Bou cannot ca&& a constructor direct&y it can only %e called %y using t$e ne!o*erator during class instantiation.
To declare a constructor )e )rite
Umodifier Uclass+ame (Uparameter* {Ustatement*
&
15.6.1 ,efault Constructor
E!ery class $as a de-ault constructor. T$e de#au&t constructor is t$e constructor)it$out any *arameters. I- t$e class does not s*eci-y any constructors t$en an im*licitde-ault constructor is created.
For eam*le in our 'tudent"ecord class t$e de-ault constructor )ould loo: li:e t$is
public StudentQecord(
{//some code !ere
&
15.6.2 Overloading Constructors
s )e $a!e mentioned constructors can also %e o!erloaded -or eam*le )e $a!e $ere-our o!erloaded constructors
public StudentQecord({//some initialiKation code !ere
&
public StudentQecord(String temp{t!is.name = temp%
&
public StudentQecord(String name String address{t!is.name = name%t!is.address = address%
&
public StudentQecord(double mRrade double eRradedouble sRrade{
mat!Rrade = mRrade%englis!Rrade = eRrade%scienceRrade = sRrade%
&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 164/244
Introduction to Programming I 163
15.6.3 :sing Constructors
To use t$ese constructors )e $a!e t$e -ollo)ing code
public static void main( String[] args {
//create t!ree objects for Student recordStudentQecord annaQecord=ne# StudentQecord("nna"%
StudentQecord bea!Qecord=ne# StudentQecord(":ea!"")!ilippines"%
StudentQecord crisQecord=ne#StudentQecord(JCPC;CC%
//some code !ere&
+o) %e-ore )e mo!e on let us go %ac: to t$e static !aria%le studentount )e $a!edeclared a )$ile ago. T$e *ur*ose o- t$e studentount is to count t$e num%er o- o%ectst$at are instantiated )it$ t$e class 'tudent"ecord. 'o )$at )e )ant to do $ere ise!erytime an o%ect o- class 'tudent"ecord is instantiated )e increment t$e !alue o-studentount. good location to modi-y and increment t$e !alue o- studentount is int$e constructors %ecause it is al)ays called e!erytime an o%ect is instantiated. Foream*le
public StudentQecord({//some initialiKation code !erestudent6ount++; 77add a student
&
public StudentQecord(String temp{ t!is.name = temp%student6ount++; 77add a student
&
public StudentQecord(String name String address{t!is.name = name%t!is.address = address%student6ount++; 77add a student
&
public StudentQecord(double mRrade double eRradedouble sRrade{
mat!Rrade = mRrade%englis!Rrade = eRrade%
scienceRrade = sRrade%student6ount++; 77add a student
&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 165/244
Introduction to Programming I 16
15.6.% +(e t(isFG Constructor Call
onstructor calls can %e c$ained meaning you can call anot$er constructor -rom insideanot$er constructor. e use t$e this67 call -or t$is. For eam*le gi!en t$e -ollo)ing
code
;7 public StudentQecord({<7 t!is("some string"%F7G7 &N7I7 public StudentQecord(String temp{D7 t!is.name = temp%J7 &P7;C7 public static void main( String[] args ;;7 {;<7;F7 StudentQecord annaQecord = ne# StudentQecord(%;G7 &
@i!en t$e code a%o!e )$en t$e statement at line 13 is called it )ill call t$e de-aultconstructor line 1. $en statement in line 2 is eecuted it )ill t$en call t$e constructort$at $as a 'tring *arameter 4in line 69.
T$ere are a -e) t$ings to remem%er )$en using t$e this constructor call;
1. $en using t$e t$is constructor call IT M1ST O""1R AS TE FIRST STATEME/T
in a constructor., It can O/LB 0E 1SE$ I/ A "O/STR1"TOR $EFI/ITIO/. T$e t$is call can t$en %e
-ollo)ed %y any ot$er rele!ant statements.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 166/244
Introduction to Programming I 16,
15.@ $ac8agesPac:ages are Ja!a`s means o- grou*ing related classes and inter-aces toget$er in a single
unit 4inter-aces )ill %e discussed later9. T$is *o)er-ul -eature *ro!ides -or a con!enientmec$anism -or managing a large grou* o- classes and inter-aces )$ile a!oiding *otentialnaming con-licts.
[email protected] Importing $ac8ages
To %e a%le to use classes outside o- t$e *ac:age you are currently )or:ing in you needto im*ort t$e *ac:age o- t$ose classes. By de-ault all your Ja!a *rograms im*ort t$e
a!a.lang.U *ac:age t$at is )$y you can use classes li:e 'tring and Integers inside t$e*rogram e!ent$oug$ you $a!ent im*orted any *ac:ages.
T$e synta -or im*orting *ac:ages is as -ollo)s
import UnameOfPackage> %
For eam*le i- you )ant to use t$e class olor inside *ac:age a)t you $a!e to ty*e t$e-ollo)ing
import java.a#t.3olor%import java.a#t.*%
T$e -irst statement im*orts t$e s*eci-ic class olor )$ile t$e ot$er im*orts all o- t$eclasses in t$e a!a.a)t *ac:age.
not$er )ay to im*ort classes -rom ot$er *ac:ages is t$roug$ e*licit *ac:agere-erencing. T$is is done %y using t$e *ac:age name to declare an o%ect o- a class.
java.a#t.3olor color%
[email protected] Creating #our o!n pac8ages
To create our o)n *ac:age )e )rite
pac-age Upac-age+ame%
'u**ose )e )ant to create a *ac:age )$ere )e )ill *lace our 'tudent"ecord classtoget$er )it$ ot$er related classes. e )ill call our *ac:age sc$oollasses.
T$e -irst t$ing you $a!e to do is create a -older named sc$oollasses. o*y all t$e
classes t$at you )ant to %elong to t$is *ac:age inside t$is -older. -ter co*ying add t$e-ollo)ing code at t$e to* o- t$e class -ile. For eam*le
pac3age school6lasses;
public class StudentQecord{
private String name%private String address%private int age%7
Pac:ages can also %e nested. In t$is case t$e Ja!a inter*reter e*ects t$e directory
structure containing t$e eecuta%le classes to matc$ t$e *ac:age $ierarc$y.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 167/244
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 168/244
Ta:e note t$at you can set t$e class*at$ any)$ere. ou can also set more t$an oneclass*at$ )e ust $a!e to se*arate t$em %y [4-or )indo)s9 and ; 4-or ni %asedsystems9. For eam*le
set classpat!=376my3lasses%E76%076My)rograms6ava
and -or ni %ased systems
e5port classpat!=/usr/local/java7/usr/my3lasses
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 169/244
15. /ccess Modifiers$en creating our classes and de-ining t$e *ro*erties and met$ods in our class )e )ant
to im*lement some :ind o- restriction to access t$ese data. For eam*le i- you )ant acertain attri%ute to %e c$anged only %y t$e met$ods inside t$e class you may )ant to$ide t$is -rom ot$er o%ects using your class. In Ja!a )e $a!e )$at )e call accessmodi#iers in order to im*lement t$is.
T$ere are -our di--erent ty*es o- mem%er access modi-iers in Ja!a; *u%lic *ri!ate*rotected and de-ault. T$e -irst t$ree access modi-iers are e*licitly )ritten in t$e code toindicate t$e access ty*e -or t$e -ourt$ one )$ic$ is de-ault no :ey)ord is used.
15..1 default access Falso called pac8age accessibilit#G
T$is s*eci-ies t$at only classes in t$e same *ac:age can $a!e access to t$e class!aria%les and met$ods. T$ere are no actual :ey)ord -or t$e de-ault modi-ier[ it is a**lied
in t$e a%sence o- an access modi-ier. For eam*le
public class StudentQecord{
//default access to instance variableint name%
//default access to met!odString get+ame({
return name%&
&
In t$is eam*le t$e instance !aria%le name and t$e met$od get+ame49 can %e accessed
-rom ot$er o%ects as long as t$e o%ect %elongs to t$e same *ac:age )$ere t$e class'tudent"ecord %elongs to.
15..2 public access
T$is s*eci-ies t$at class mem%ers are accessi%le to anyone %ot$ inside and outside t$eclass. ny o%ect t$at interacts )it$ t$e class can $a!e access to t$e *u%lic mem%ers o-t$e class. For eam*le
public class StudentQecord{
//default access to instance variablepublic int name%
//default access to met!odpublic String get+ame({
return name%&
&
In t$is eam*le t$e instance !aria%le name and t$e met$od get+ame49 can %e accessed-rom ot$er o%ects.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 170/244
15..3 protected access
T$is s*eci-ies t$at t$e class mem%ers are accessi%le only to met$ods in t$at class andt$e su%classes o- t$e class. For eam*le
public class StudentQecord{
//default access to instance variableprotected int name%
//default access to met!odprotected String get+ame({
return name%&
&
In t$is eam*le t$e instance !aria%le name and t$e met$od get+ame49 can %e accessedonly -rom met$ods inside t$e class and -rom su%classes o- 'tudent"ecord. e )illdiscuss a%out su%classes on t$e net c$a*ter.
15..% private access
T$is s*eci-ies t$at t$e class mem%ers are only accessi%le %y t$e class t$ey are de-inedin. For eam*le
public class StudentQecord{
//default access to instance variableprivate int name%
//default access to met!od
private String get+ame({return name%
&&
In t$is eam*le t$e instance !aria%le name and t$e met$od get+ame49 can %e accessedonly -rom met$ods inside t$e class.
Coding <uidelinesThe instance $ariables of a class should normally be declared pri$ateB and the classwill <ust pro$ide accessor and mutator methods to these $ariables.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 171/244
Introduction to Programming I 1H0
15.15 0-ercises
15.15.1 /ddress Boo8 0ntr#
our tas: is to create a class t$at contains an address %oo: entry. T$e -ollo)ing ta%ledescri%es t$e in-ormation t$at an adress%oo: entry $as.
Attributes5Properties $escription
+ame +ame o- t$e *erson in t$e address%oo:
ddress ddress o- t$e *erson
Tele*$one +um%er Tele*$one num%er o- t$e *erson
Email ddress Persons Email address
Table 21: 3ttributes and 3ttributes escriptions
For t$e met$ods create t$e -ollo)ing;
1. Pro!ide t$e necessary accessor and mutator met$ods -or all t$e attri%utes.2. onstructors
15.15.2 /ddressBoo8
reate a class address %oo: t$at can contain 100 entries o- ddressBoo:Entry o%ects4use t$e class you created in t$e -irst eercise9. ou s$ould *ro!ide t$e -ollo)ingmet$ods -or t$e address %oo:.
1. dd entry2. Delete entry3. Vie) all entries. *date an entry
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 172/244
Introduction to Programming I 1H1
++ Inheritance> Po&ymorphism and
Inter#aces11.1 ObjectivesIn t$is section )e )ill %e discussing on $o) a class can in$erit t$e *ro*erties o- aneisting class. class t$at does t$is is called a su%class and its *arent class is called t$esu*erclass. e )ill also %e discussing a s*ecial *ro*erty o- Ja!a )$erein it canautomatically a**ly t$e *ro*er met$ods to eac$ o%ect regardless o- )$at su%class t$eo%ect came -rom. T$is *ro*erty is :no)n as *olymor*$ism. Finally )e are going todiscusss a%out inter-aces t$at $el*s reduce *rogramming e--ort.
t t$e end o- t$e lesson t$e student s$ould %e a%le to;
•
De-ine su*er classes and su%classes• &!erride met$ods o- su*erclasses
• reate -inal met$ods and -inal classes
11.2 In(eritanceIn Ja!a all classes including t$e classes t$at ma:e u* t$e Ja!a PI are su%classed -romt$e ObCect su*erclass. sam*le class $ierarc$y is s$o)n %elo).
ny class a%o!e a s*eci-ic class in t$e class $ierarc$y is :no)n as a superc&ass. $ile
any class %elo) a s*eci-ic class in t$e class $ierarc$y is :no)n as a su%class o- t$atclass.
Figure 11.1: Class !ierarchy
In$eritance is a maor ad!antage in o%ectoriented *rogramming since once a %e$a!ior4met$od9 is de-ined in a su*erclass t$at %e$a!ior is automatically in$erited %y allsu%classes. T$us you can encode a met$od only once and t$ey can %e used %y allsu%classes. su%class only need to im*lement t$e di--erences %et)een itsel- and t$e*arent.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 173/244
Introduction to Programming I 1H2
11.2.1 ,efining Superclasses and Subclasses
To deri!e a class )e use t$e extends :ey)ord. In order to illustrate t$is lets create asam*le *arent class. 'u**ose )e $a!e a *arent class called Person.
public class )erson{
protected String name% protected String address%
/*** Eefault constructor*/public )erson({
System.out.println(A,nside )erson73onstructorB%name = ""%address = ""%
&
/*** 3onstructor #it! < parameters*/public )erson( String name String address {
t!is.name = name%t!is.address = address%
&
/*** ccessor met!ods*/public String get+ame({
return name%
&
public String getddress({return address%
&
public void set+ame( String name {t!is.name = name%
&
public void setddress( String add {t!is.address = add%
&
&
+otice t$at t$e attri%utes name and address are declared as protected. T$e reason )edid t$is is t$at )e )ant t$ese attri%utes to %e accessi%le %y t$e su%classes o- t$esu*erclass. I- )e declare t$is as *ri!ate t$e su%classes )ont %e a%le to use t$em. Ta:enote t$at all t$e *ro*erties o- a su*erclass t$at are declared as pub&ic> protected andde#au&t can %e accessed %y its su%classes.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 174/244
Introduction to Programming I 1H3
+o) )e )ant to create anot$er class named 'tudent. 'ince a student is also a *erson)e decide to ust etend t$e class Person so t$at )e can in$erit all t$e *ro*erties andmet$ods o- t$e eisting class Person. To do t$is )e )rite
public class Student e5tends )erson{
public Student({System.out.println(A,nside Student73onstructorB%//some code !ere
&
// some code !ere&
$en a 'tudent o%ect is instantiated t$e de-ault constructor o- its su*erclass is in!o:edim*licitly to do t$e necessary initiali>ations. -ter t$at t$e statements inside t$esu%class are eecuted. To illustrate t$is consider t$e -ollo)ing code
public static void main( String[] args {Student anna = ne# Student(%
&
In t$e code )e create an o%ect o- class 'tudent. T$e out*ut o- t$e *rogram is
,nside )erson73onstructor,nside Student73onstructor
T$e *rogram -lo) is s$o)n %elo).
Figure 11.2: )rogram Flow
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 175/244
Introduction to Programming I 1H
11.2.2 +(e super 8e#!ord
su%class can also exp&icit&y call a constructor o- its immediate su*erclass. T$is is done%y using t$e super constructor call. su*er constructor call in t$e constructor o- a
su%class )ill result in t$e eecution o- rele!ant constructor -rom t$e su*erclass %ased ont$e arguments *assed.
For eam*le gi!en our *re!ious eam*le classes Person and 'tudent )e s$o) aneam*le o- a su*er constructor call. @i!en t$e -ollo)ing code -or 'tudent
public Student({super( ")omeBame", ")ome4ddress" ;System.out.println(",nside Student73onstructor"%
&
T$is code calls t$e second constructor o- its immediate su*erclass 4)$ic$ is Person9 andeecutes it. not$er sam*le code s$o)n %elo)
public Student({super(;System.out.println(",nside Student73onstructor"%
&
T$is code calls t$e de-ault constructor o- its immediate su*erclass 4)$ic$ is Person9 andeecutes it.
T$ere are a -e) t$ings to remem%er )$en using t$e su*er constructor call;
1. T$e su*er49 call ('T &" T#E FI"'T 'TTE(E+T I+ &+'T"T&".
2. T$e su*er49 call can only %e used in a constructor de-inition.3. T$is im*lies t$at t$e t$is49 construct and t$e su*er49 calls ++&T B&T# &" I+T#E '(E &+'T"T&".
not$er use o- su*er is to re-er to mem%ers o- t$e su*erclass 4ust li:e t$e this
re-erence 9. For eam*le
public Student({
super*name = DsomenameE;super*address = Dsome addressE;
b
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 176/244
Introduction to Programming I 1H,
11.2.3 Overriding Met(ods
I- -or some reason a deri!ed class needs to $a!e a di--erent im*lementation o- a certainmet$od -rom t$at o- t$e su*erclass overriding met$ods could *ro!e to %e !ery use-ul.
su%class can o!erride a met$od de-ined in its su*erclass %y *ro!iding a ne)im*lementation -or t$at met$od.
'u**ose )e $a!e t$e -ollo)ing im*lementation -or t$e get+ame met$od in t$e Personsu*erclass
public class )erson
Z77public String get+ame({
System.out.println(")arent7 get+ame"%return name%
&7
&
To o!erride t$e get+ame met$od in t$e su%class 'tudent )e )rite
public class Student e5tends )erson
Z77public String get+ame({
System.out.println("Student7 get+ame"%return name%
&7
&
'o )$en )e in!o:e t$e get+ame met$od o- an o%ect o- class 'tudent t$e o!erriddenmet$od )ould %e called and t$e out*ut )ould %e
Student7 get+ame
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 177/244
Introduction to Programming I 1H6
11.2.% 9inal Met(ods and 9inal Classes
In Ja!a it is also *ossi%le to declare classes t$at can no longer %e su%classed. T$eseclasses are called #ina& c&asses. To declare a class to %e -inal )e ust add t$e -inal
:ey)ord in t$e class declaration. For eam*le i- )e )ant t$e class Person to %e declared-inal )e )rite
public $inal class )erson{
//some code !ere&
(any o- t$e classes in t$e Ja!a PI are declared -inal to ensure t$at t$eir %e$a!iorcannot %e o!erridden. Eam*les o- t$ese classes are Integer Dou%le and 'tring.
It is also *ossi%le in Ja!a to create met$ods t$at cannot %e o!erridden. T$ese met$odsare )$at )e call #ina& methods. To declare a met$od to %e -inal )e ust add t$e -inal:ey)ord in t$e met$od declaration. For eam*le i- )e )ant t$e get+ame met$od inclass Person to %e declared -inal )e )rite
public $inal String get+ame({return name%
&
'tatic met$ods are automatically -inal. T$is means t$at you cannot o!erride t$em.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 178/244
Introduction to Programming I 1HH
11.3 $ol#morp(ism+o) gi!en t$e *arent class Person and t$e su%class 'tudent o- our *re!ious eam*le
)e add anot$er su%class o- Person )$ic$ is Em*loyee. Belo) is t$e class $ierarc$y -ort$at
Person
'tudent Em*loyee
Figure 11.: !ierarchy for )erson class and itRsclasses
In Ja!a )e can create a re-erence t$at is o- ty*e su*erclass to an o%ect o- its su%class.For eam*le
public static main( String[] args {
)erson ref%
Student studentbject = ne# Student(%0mployee employeebject = ne# 0mployee(%
ref = studentbject% //)erson ref points to a// Student object
//some code !ere&
+o) su**ose )e $a!e a get+ame met$od in our su*erclass Person and )e o!erride t$ismet$od in %ot$ t$e su%classes 'tudent and Em*loyee
public class )erson{
public String get+ame({ System.out.println(A)erson +ame7B 4name% return name%
&&
public class Student e5tends )erson{
public String get+ame({ System.out.println(AStudent +ame7B 4name% return name%
&&
public class 0mployee e5tends )erson{
public String get+ame({ System.out.println(A0mployee +ame7B 4name% return name%
&&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 179/244
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 180/244
Introduction to Programming I 1H<
11.% /bstract Classes+o) su**ose )e )ant to create a su*erclass )$erein it $as certain met$ods in it t$at
contains some im*lementation and some met$ods )$erein )e ust )ant to %eo!erridden %y its su%classes.
For eam*le )e )ant to create a su*erclass named =i!ingT$ing. T$is class $as certainmet$ods li:e %reat$ eat slee* and )al:. #o)e!er t$ere are some met$ods in t$issu*erclass )$erein )e cannot generali>e t$e %e$a!ior. Ta:e -or eam*le t$e )al:met$od. +ot all li!ing t$ings )al: t$e same )ay. Ta:e t$e $umans -or instance )e$umans )al: on t)o legs )$ile ot$er li!ing t$ings li:e dogs )al: on -our legs. #o)e!ert$ere are many c$aracteristics t$at li!ing t$ings $a!e in common t$at is )$y )e )ant tocreate a general su*erclass -or t$is.
Figure 11.%: 3bstract class
In order to do t$is )e can create a su*erclass t$at $as some met$ods )it$im*lementations and ot$ers )$ic$ do not. T$is :ind o- class is called an a%stract class.
n abstract c&ass is a class t$at cannot %e instantiated. It o-ten a**ears at t$e to* o-an o%ectoriented *rogramming class $ierarc$y de-ining t$e %road ty*es o- actions*ossi%le )it$ o%ects o- all su%classes o- t$e class.
T$ose met$ods in t$e a%stract classes t$at do not $a!e im*lementation are calledabstract methods. To create an a%stract met$od ust )rite t$e met$od declaration)it$out t$e %ody and use t$e a%stract :ey)ord. For eam*le
public abstract void someMet!od(%
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 181/244
Introduction to Programming I 170
+o) lets create an eam*le a%stract class.
public abstract class .ivingGhing{
public void breat!({System.out.println("Tiving 2!ing breat!ing..."%
&
public void eat({System.out.println("Tiving 2!ing eating..."%
&
7HHH abstract method al3H Ie ant this method to be overridden by subclasses o$H .ivingGhingH7
public abstract void al3(;&
$en a class etends t$e =i!ingT$ing a%stract class it is re?uired to o!erride t$ea%stract met$od )al:49 or else t$at su%class )ill also %ecome an a%stract class andt$ere-ore cannot %e instantiated. For eam*le
public class Human e1tends .ivingGhing{
public void al3( )ystem*out*println("uman
al3s***";-
&
I- t$e class #uman does not o!erride t$e )al: met$od )e )ould encounter t$e -ollo)ingerror message
Human.java7;7 Human is not abstract and does not overrideabstract met!od #al-( in Tiving2!ingpublic class Human e5tends Tiving2!ing
Y; error
Coding<uidelines
Lse abstract classes to define broad types of beha$iors at the top of an ob<ectoriented programming class hierarchyB and use its subclasses to pro$ide implementationdetails of the abstract class.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 182/244
Introduction to Programming I 171
11.* Interfacesn inter#ace is a s*ecial :ind o- %loc: containing met$od signatures 4and *ossi%ly
constants9 only. Inter-aces de-ine t$e signatures o- a set o- met$ods )it$out t$e %ody.
Inter-aces de-ine a standard and *u%lic )ay o- s*eci-ying t$e %e$a!ior o- classes. T$eyallo) classes regardless o- t$eir location in t$e class $ierarc$y to im*lement common%e$a!iors. +ote t$at inter-aces e$i%it *olymor*$ism as )ell since *rogram may call aninter-ace met$od and t$e *ro*er !ersion o- t$at met$od )ill %e eecuted de*ending ont$e ty*e o- o%ect *assed to t$e inter-ace met$od call.
11.*.1 (# do !e use Interfaces)
e need to use inter-aces i- we want unrelated classes to implement similar methods.
T$ru inter-aces )e can actually ca*ture similarities among unrelated classes )it$outarti-icially -orcing a class relations$i*.
=ets ta:e as an eam*le a class Line )$ic$ contains met$ods t$at com*utes t$e lengt$o- t$e line and com*ares a Line o%ect to o%ects o- t$e same class. +o) su**ose )e$a!e anot$er class MyInteger )$ic$ contains met$ods t$at com*ares a MyIntegero%ect to o%ects o- t$e same class. s )e can see $ere %ot$ o- t$e classes $a!e somesimilar met$ods )$ic$ com*ares t$em -rom ot$er o%ects o- t$e same ty*e %ut t$ey arenot related )$atsoe!er. In order to en-orce a )ay to ma:e sure t$at t$ese t)o classesim*lement some met$ods )it$ similar signatures )e can use an inter-ace -or t$is. ecan create an inter-ace class lets say inter-ace Re&ation )$ic$ $as some com*arisonmet$od declarations. &ur inter-ace "elation can %e declared as
public interface Qelation{
public boolean isRreater( bject a bject b%public boolean isTess( bject a bject b%public boolean is0@ual( bject a bject b%
&
not$er reason -or using an o%ects *rogramming inter-ace is to re$eal an ob<ectRs programming interface without re$ealing its class. s )e can see later on t$e section6nterface $s. Classes )e can actually use an inter-ace as data ty*e.
Finally )e need to use inter-aces to model multiple inheritance )$ic$ allo)s a class to$a!e more t$an one su*erclass. (ulti*le in$eritance is not *resent in Ja!a %ut *resent
in ot$er o%ectoriented languages li:e KK.
11.*.2 Interface vs. /bstract Class
T$e -ollo)ing are t$e main di--erences %et)een an inter-ace and an a%stract class;inter-ace met$ods $a!e no %ody an inter-ace can only de-ine constants and an inter-ace$a!e no direct in$erited relations$i* )it$ any *articular class t$ey are de-inedinde*endently.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 183/244
Introduction to Programming I 172
11.*.3 Interface vs. Class
&ne common c$aracteristic o- an inter-ace and class is t$at t$ey are %ot$ ty*es. T$ismeans t$at an inter-ace can %e used in *laces )$ere a class can %e used. For eam*le
gi!en a class Person and an inter-ace PersonInter-ace t$e -ollo)ing declarations are!alid;
)erson,nterface pi = ne# )erson(%)erson pc = ne# )erson(%
#o)e!er you cannot create an instance -rom an inter-ace. n eam*le o- t$isis;
)erson,nterface pi = ne# )erson,nterface(% //3M),T0//0QQQ$$$
not$er common c$aracteristic is t$at %ot$ inter-ace and class can de-ine met$ods.
#o)e!er an inter-ace does not $a!e an im*lementation code )$ile t$e class $a!e one.
11.*.% Creating Interfaces
To create an inter-ace )e )rite
public interface [,nterface+ame]{
//some met!ods #it!out t!e body&
s an eam*le lets create an inter-ace t$at de-ines relations$i*s %et)een t)o o%ects
according to t$e natural orderQ o- t$e o%ects.
public interface Qelation{
public boolean isRreater( bject a bject b%public boolean isTess( bject a bject b%public boolean is0@ual( bject a bject b%
&
+o) to use t$e inter-ace )e use t$e imp&ements :ey)ord. For eam*le
/*** 2!is class defines a line segment*/
public class Tine implements Qelation{
private double 5;%private double 5<%private double y;%private double y<%
public Tine(double 5; double 5< double y; double y<{t!is.5; = 5;%t!is.5< = 5<%t!is.y; = y;%t!is.y< = y<%
&
public double getTengt!({
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 184/244
Introduction to Programming I 173
double lengt! = Mat!.s@rt((5<5;*(5<5; 4(y<y;* (y<y;%
return lengt!%&
public boolean isRreater( bject a bject b{double aTen = ((Tinea.getTengt!(%double bTen = ((Tineb.getTengt!(%return (aTen bTen%
&
public boolean isTess( bject a bject b{double aTen = ((Tinea.getTengt!(%double bTen = ((Tineb.getTengt!(%return (aTen U bTen%
&
public boolean is0@ual( bject a bject b{
double aTen = ((Tinea.getTengt!(%double bTen = ((Tineb.getTengt!(%return (aTen == bTen%
&&
$en your class tries to im*lement an inter-ace al)ays ma:e sure t$at you im*lementall t$e met$ods o- t$at inter-ace or else you )ould encounter t$is error
Tine.java7G7 Tine is not abstract and does not overrideabstract met!od isRreater(java.lang.bjectjava.lang.bject inQelationpublic class Tine implements Qelation
Y; error
Coding
<uidelines
Lse interfaces to create the same standard method definitions in may different classes.-nce a set of standard method definition is createdB you can write a single method tomanipulate all of the classes that implement the interface.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 185/244
Introduction to Programming I 17
11.*.* 4elations(ip of an Interface to a Class
s )e $a!e seen in t$e *re!ious section a class can im*lement an inter-ace as long as it*ro!ides t$e im*lementation code -or all t$e met$ods de-ined in t$e inter-ace.
not$er t$ing to note a%out t$e relations$i* o- inter-aces to classes is t$at a class canonly E/TE+D &+E su*er class %ut it can I(P=E(E+T (+ inter-aces. n eam*le o- aclass t$at im*lements many inter-aces is
public class )erson implements )erson,nterfaceTiving2!ing'!atever,nterface {
//some code !ere&
not$er eam*le o- a class t$at etends one su*er class and im*lements an inter-ace is
public class 3omputerScienceStudent e5tends Studentimplements )erson,nterface
Tiving2!ing {
//some code !ere&
Ta:e note t$at an inter-ace is not *art o- t$e class in$eritance $ierarc$y. nrelatedclasses can im*lement t$e same inter-ace.
11.*. In(eritance among Interfaces
Inter-aces are not *art o- t$e class $ierarc$y. #o)e!er inter-aces can $a!e in$eritancerelations$i* among themsel$es. For eam*le su**ose )e $a!e t)o inter-acesStudentInter#ace and PersonInter#ace. I- 'tudentInter-ace etends PersonInter-aceit )ill in$erit all o- t$e met$od declarations in PersonInter-ace.
public interface )erson,nterface {. . .
&
public interface Student,nterface e5tends )erson,nterface {. . .
&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 186/244
Introduction to Programming I 17,
11. 0-ercises
11..1 0-tending Student4ecord
In t$is eercise )e )ant to create a more s*eciali>ed student record t$at containsadditional in-ormation a%out a om*uter 'cience student. our tas: is to etend t$e'tudent"ecord class t$at )as im*lemented in t$e *re!ious lessons. dd some attri%utesand met$ods t$at you t$in: are needed -or a om*uter 'cience student record. Try too!erride some eisting met$ods in t$e su*erclass 'tudent"ecord i- you really need to.
11..2 +(e S(ape abstract class
Try to create an a%stract class called '$a*e )it$ a%stract met$ods getrea49 andget+ame49. rite t)o o- its su%classes ircle and '?uare. ou can add additionalmet$ods to its su%classes i- you )ant to.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 187/244
Introduction to Programming I 176
+. 0asic Exception and&ing
12.1 ObjectivesIn t$is section )e are going to study a tec$ni?ue used in Ja!a to $andle unusualconditions t$at interru*t t$e normal o*eration o- t$e *rogram. T$is tec$ni?ue is calledexception hand&ing.
t t$e end o- t$e lesson t$e student s$ould %e a%le to;
• De-ine ece*tions
• #andle ece*tions using a sim*le trycatc$-inally %loc:
12.2 (at are 0-ceptions) n ece*tion is an e!ent t$at interru*ts t$e normal *rocessing -lo) o- a *rogram. T$ise!ent is usually some error o- some sort. T$is causes our *rogram to terminatea%normally.
'ome eam*les o- ece*tions t$at you mig$t $a!e encountered in our *re!ious eercisesare; rrayInde&ut&-Bounds ece*tions )$ic$ occurs i- )e try to access a noneistentarray element or may%e a +um%erFormatEce*tion )$ic$ occurs )$en )e try to *assas a *arameter a nonnum%er in t$e Integer.*arseInt met$od.
12.3 andling 0-ceptionsTo $andle ece*tions in Ja!a )e use a trycatc$-inally %loc:. $at )e do in our*rograms is t$at )e *lace t$e statements t$at can *ossi%ly generate an ece*tion insidet$is %loc:.
T$e general -orm o- a trycatc$-inally %loc: is
try{
&
//#rite t!e statements t!at can generate an e5ception//in t!is bloc-
catc!( Ue5ception2ype; Uvar+ame; {
&. . .
//#rite t!e action your program #ill do if an e5ception//of a certain type occurs
catc!( Ue5ception2ypen Uvar+amen {//#rite t!e action your program #ill do if an//e5ception of a certain type occurs
&finally{
//add more cleanup code !ere&
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 188/244
Ece*tions t$ro)n during eecution o- t$e try %loc: can %e caug$t and $andled in acatc$ %loc:. T$e code in t$e -inally %loc: is al)ays eecuted.
T$e -ollo)ing are t$e :ey as*ects a%out t$e synta o- t$e trycatc$-inally construct;• T$e %loc: notation is mandatory.
• For eac$ try %loc: t$ere can %e one or more catc$ %loc:s %ut only one -inally %loc:.
• T$e catc$ %loc:s and -inally %loc:s must al)ays a**ear in conunction )it$ t$e try
%loc: and in t$e a%o!e order.• try %loc: must %e -ollo)ed %y at &east one catc$ %loc: &" one -inally %loc: or %ot$.
• Eac$ catc$ %loc: de-ines an ece*tion $andle. T$e $eader o- t$e catc$ %loc: ta:es
eactly one argument )$ic$ is t$e ece*tion its %loc: is )illing to $andle. T$e
ece*tion must %e o- t$e T$ro)a%le class or one o- its su%classes.
Figure 12.1: Flow of e$ents in a trycatchfinally bloc;
=ets ta:e -or eam*le a code t$at *rints t$e second argument )$en )e try to run t$ecode using commandline arguments. 'u**ose t$ere is no c$ec:ing inside your code -or
t$e num%er o- arguments and )e ust access t$e second argument argsX1Y rig$t a)ay)ell get t$e -ollo)ing ece*tion.
05ception in t!read "main"java.lang.rray,nde5utf:ounds05ception7 ;
at 05ception05ample.main(05ception05ample.java7N
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 189/244
To *re!ent t$is -rom $a**ening )e can *lace t$e code inside a trycatc$ %loc:. T$e-inally %loc: is ust o*tional. For t$is eam*le )e )ont use t$e -inally %loc:.
public class 05ception05ample
{ public static void main( String[] args {
try
System.out.println( args[;] %-catch( 4rray&nde1/ut/$#ounds01ception e1p
System.out.println("05ception caug!t$"%-&
&
'o )$en )e try to run t$e *rogram again )it$out arguments t$e out*ut )ould %e
05ception caug!t$
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 190/244
12.% 0-ercises
12.%.1 Catc(ing 0-ceptions1
@i!en t$e -ollo)ing code;public class 2est05ceptions{
public static void main( String[] args {for( int i=C% true% i44 {
System.out.println("args["4i4"]="4args[i]%
&&
&
om*ile and run t$e TestEce*tions *rogram. T$e out*ut s$ould loo: li:e t$is;
javac 2est05ceptions one t#o t!reeargs[C]=oneargs[;]=t#oargs[<]=t!ree05ception in t!read "main"
java.lang.rray,nde5utf:ounds05ception7 Fat 2est05ceptions.main(;.java7G
(odi-y t$e TestEce*tions *rogram to $andle t$e ece*tion. T$e out*ut o- t$e *rograma-ter catc$ing t$e ece*tion s$ould loo: li:e t$is;
javac 2est05ceptions one t#o t!reeargs[C]=oneargs[;]=t#o
args[<]=t!ree05ception caug!t7java.lang.rray,nde5utf:ounds05ception7 F
^uiting...
12.%.2 Catc(ing 0-ceptions 2
$ances are !ery good t$at some *rograms you!e )ritten %e-ore $a!e encounteredece*tions. 'ince you didnt catc$ t$e ece*tions t$ey sim*ly $alted t$e eecution o-your code. @o %ac: to t$ose *rograms and im*lement ece*tion $andling.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 191/244
Introduction to Programming I 1<0
Appendix A 2 =a)a and /et0eans Insta&&ation
In t$is section )e )ill discuss on $o) to install Ja!a and +etBeans in your system4%untu Da**er8indo)s /P9. I- you are not *ro!ided )it$ t$e Ja!a ,.0 and +etBeans,., installers %y your instructor you can do)nload a co*y o- t$e installers -rom t$e 'un(icrosystems )e%site 4$ tt * ; 8 8 a ! a .s un . c o m 8 9 - or Ja!a and$ tt * ; 8 8 )) ) .+ e t Be a n s .o r g8do ) n l o a d s8 - or +etBeans9. Be-ore starting )it$ t$einstallation co*y t$e installers in your $ard dis: -irst.
For 1buntu $apper2
o*y all t$e installers inside t$e 8usr -older.
For 'indo!s2
Just co*y t$e installers in any tem*orary directory.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 192/244
Introduction to Programming I 1<1
Installing 7ava in :buntu ,apper Step +2 @o to t$e -older )$ere you $a!e your installers
Step .2 Be-ore running your installer ma:e sure it is eecuta%le. To do t$is rig$t clic:on t$e installer clic: on t$e Permissions ta% and t$en lic: on t$e eecute %o. lose
t$e )indo).
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 193/244
Introduction to Programming I 1<2
Step -2 Dou%le clic: on t$e -ile d:1C,C0C06linui,76.%in. dialog %o )ill dis*layclic: on t$e %utton "un In Terminal.
-ter *ressing E+TE" you )ill see t$e license agreement dis*layed on t$e console.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 194/244
Introduction to Programming I 1<3
Just *ress enter until you see t$e ?uestion; Do you agree to t$e a%o!e license termsGXyes or noY. Just ty*e; yes and *ress E+TE". Just )ait -or t$e installer to -inis$un*ac:ing all its contents and installing Ja!a.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 195/244
Introduction to Programming I 1<
Step <2 "reating symbo&ic &in%s
In order to run a!a commands any)$ere )e need to create sym%olic lin:s -or all t$ecommands in JDA inside t$e 8usr8local8%in directory. To do t$is go to t$edirectory;/usr/local/bin. Ty*e; cd /usr/local/bin
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 196/244
Introduction to Programming I 1<,
To ma:e t$e sym%olic lin:s to t$e commands ty*e;sudo ln s /usr/java/jd-;.N.C\C;/bin/* .
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 197/244
Introduction to Programming I 1<6
Installing 7ava in indo!sStep +2 1sing 'indo!s Exp&orer> go to the #o&der !here your =a)a insta&&er is
&ocated
Figure 12.2: Folder containing installers
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 198/244
J.E.D.I
Introduction to Programming I 1<H
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 199/244
Introduction to Programming I 1<7
J.E.D.I
Step .2 Run the insta&&er
To run t$e installer ust dou%leclic: on t$e installer icon. J2'E installer dialog )illt$en a**ear. lic: on t$e radio %utton la%eled RI acce*t t$e terms in t$e license
agreementR and *ress +E/T.
Figure 12.: 4icense agreement
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 200/244
Introduction to Programming I 1<<
J.E.D.I
lic: on +E/T to continue installation.
Figure 12.%: Custom setup
lic: on FI+I'# to com*lete installation.
Figure 12.+: Finish installation
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 201/244
Introduction to Programming I 200
J.E.D.I
Installing etBeans in :buntu ,apper
Step +2 @o to t$e -older )$ere you $a!e your installers
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 202/244
Introduction to Programming I 201
J.E.D.I
Step .2 Be-ore running your installer ma:e sure it is eecuta%le.
To do t$is rig$t clic: on t$e installer clic: on t$e Permissions ta% and t$en lic: on t$e
eecute %o. lose t$e )indo).
Step -2 Dou%le clic: on t$e -ile net%eans,C,%etalinu.%in. lic: on "un in Terminal.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 203/244
Introduction to Programming I 202
J.E.D.I
+et%eans ,., dialog )ill t$en a**ear. lic: on +E/T.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 204/244
Introduction to Programming I 203
J.E.D.I
lic: on t$e radio %utton t$at says RI acce*t t$e terms in t$e license agreementR. ndt$en clic: on +E/T.
For t$e directory name c$ange it to; 8usr8a!a8net%eans.0 t$en clic: on +E/T.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 205/244
Introduction to Programming I 20
J.E.D.I
For t$e JDA directory c$oose 8usr8a!a8d:1.,.0C01 and t$en clic: on +E/T.
T$e net dialog ust s$o)s in-ormation a%out +etBeans t$atyou )ill install. Just clic:again on +E/T.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 206/244
Introduction to Programming I 20,
J.E.D.I
+o) ust )ait -or +etBeans to -inis$ its installation. lic: on FI+I'# to com*lete t$einstallation.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 207/244
J.E.D.I
Introduction to Programming I 206
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 208/244
Introduction to Programming I 20H
J.E.D.I
Step <2 reating sym%olic lin:s
In order to run +etBeans any)$ere )e need to create sym%olic lin: -or it. To do t$is go-irst to t$e directory;/usr/local/bin. Ty*e; cd /usr/local/bin
(a:e a sym%olic lin: to t$e +etBeans eecuta%le %y ty*ing;sudo ln s /!ome/florence/netbeans/bin/netbeans .
+o) you can run +etBeans in any directory %y ty*ing; netbeans V
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 209/244
Introduction to Programming I 207
J.E.D.I
Installing etBeans in indo!s
Step +2 1sing 'indo!s Exp&orer> go to the #o&der !here your /et0eans insta&&eris &ocated
Figure 12.*: "et9eans installer file
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 210/244
Introduction to Programming I 20<
J.E.D.I
Step .2 Run the insta&&er
To run t$e installer ust dou%leclic: on t$e installer icon. -ter clic:ing on t$e net%eans
,C,%eta%in)indo)s icon t$e +etBeans installation )i>ard )ill a**ear. lic: on +E/T
to enter installation *rocess.
Figure 12./: "et9eans installation
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 211/244
Introduction to Programming I 210
J.E.D.I
T$e agreement *age )ill t$e a**ear. $oose to EPT and clic: +E/T to continue.
Figure 12.0: 4icense 3greement
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 212/244
Introduction to Programming I 211
J.E.D.I
T$en you )ill %e gi!en t$e c$oice on )$ic$ directory to *lace t$e +etBeans. ou canmo!e on %y clic:ing +E/T or you can clic: on B"&'E to c$oose a di--erent directory.
Figure 12.7: Choose directory where to install "et9eans
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 213/244
Introduction to Programming I 212
J.E.D.I
+et is c$oosing t$e 'tandard Edition JDAs -rom your mac$ine. I- you $a!e -inis$edinstalling Ja!a t$e d:1.,.0C01 c$ould a**ear -rom your c$oices. lic: on +E/T tocontinue.
Figure 12.1&: Choose K to use
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 214/244
Introduction to Programming I 213
J.E.D.I
It )ill t$en in-orm you t$e location and si>e o- +etBeans )$ic$ )ill %e installed to yourmac$ine. lic: on +E/T to -inis$ installation.
Figure 12.11: 6nstallation Summary
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 215/244
Introduction to Programming I 21
J.E.D.I
ou $a!e installed +etBeans on your com*uter. lic: on FI+I'# to com*lete installation.
Figure 12.12: Successful installation
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 216/244
Introduction to Programming I 21,
J.E.D.I
Appendix 02 ?etting to %no! your ProgrammingEn)ironment 6'indo!s (P )ersion7
In t$is section )e )ill %e discussing on $o) to )rite com*ile and run Ja!a *rograms.T$ere are t)o )ays o- doing t$is t$e -irst one is %y using a console and a tet editor.T$e second one is %y using +etBeans )$ic$ is an Integrated $e)e&opmentEn)ironment or I$E.
n IDE is a *rogramming en!ironment integrated into a so-t)are a**lication t$at*ro!ides a @I %uilder a tet or code editor a com*iler and8or inter*reter and ade%ugger.
Be-ore going into details let us -irst ta:e a loo: at t$e -irst Ja!a *rogram you )ill %e)riting.
M# 9irst 7ava $rogram
public class Hello{
/*** My first java program*/public static void main(String[] args {
//prints t!e string "Hello #orld" on screenSystem.out.println("Hello #orld$"%
&&
Be-ore )e try to e*lain )$at t$e *rogram means lets -irst try to )rite t$is *rogram in a-ile and try to run it.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 217/244
Introduction to Programming I 216
J.E.D.I
:sing a +e-t 0ditor and
Console
For t$is eam*le )e )ill %e using t$e tet editor R+ote*adR4-or indo)s9 to edit t$eJa!a source code. ou can use ot$er tet editors i- you )ant to. ou )ill also need too*en t$e ('D&' *rom*t )indo) to com*ile and eecute your Ja!a *rograms.
Step +2 Start /otepad
To start +ote*ad in indo)s clic: on start ll Programs ccessories +ote*ad.
Figure 12.1%: "otepad 3pplication
Figure 12.1: Clic; on startQ 3ll )rogramsQ 3ccessoriesQ "otepad
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 218/244
Introduction to Programming I 21H
J.E.D.I
Step .2 Open the "ommand Prompt !indo!
To o*en t$e ('D&' command *rom*t in indo)s clic: on start ll *rogramsccessories ommand Prom*t.
Figure 12.1+: startQ 3ll programsQ 3ccessories QCommand )rompt
Figure 12.1*: =S-S Command )rompt
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 219/244
Introduction to Programming I 217
J.E.D.I
Step -2 'rite your the source code o# your =a)a program in /otepad
Step <2 Sa)e your =a)a Program
e )ill sa!e our *rogram on a -ile named R#ello.a!aR and )e )ill %e sa!ing it inside a-older named (JVP"&@"('.
To o*en t$e Sa)e dialog %o clic: on t$e File menu -ound on t$e menu%ar and t$en
clic: on 'a!e.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 220/244
Introduction to Programming I 21<
J.E.D.I
-ter doing t$e *rocedure descri%ed a%o!e a dialog %o )ill a**ear as s$o)n in Figure%elo).
Figure 12.1/: This ialog appears after clic;ing on File Q Sa$e
lic: on t$e MB $O"1ME/TS %utton to o*en t$e (y Documents -older )$ere )e )ill %esa!ing all your Ja!a *rograms.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 221/244
Introduction to Programming I 220
J.E.D.I
Figure 12.10: Clic; on the button encircled. This will open your =y ocuments folder
+o) )ell create a ne) -older inside t$e (y Documents -older )$ere )e )ill sa!e your*rograms. e s$all name t$is -older (JVP"&@"('. lic: on t$e %utton encircled int$e -igure %elo) to create t$e -older.
Figure 12.17: Clic;ing on the encircled button will create a "ew Folder.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 222/244
Introduction to Programming I 221
J.E.D.I
-ter t$e -older is created you can ty*e in t$e desired name -or t$is -older. In t$is casety*e in (JVP"&@"(' and t$en *ress E+TE".
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 223/244
Introduction to Programming I 222
J.E.D.I
+o) t$at )e!e created t$e -older )$ere )e )ill sa!e all t$e -iles dou%le clic: on t$at-older to o*en it. ou )ill see a similar -igure as s$o)n %elo). T$e -older s$ould %eem*ty -or no) since its a ne)ly created -older and )e $a!ent sa!ed anyt$ing in it yet.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 224/244
Introduction to Programming I 223
J.E.D.I
+o) clic: on t$e dro* do)n list %o R'a!e as ty*eR so t$at )e can c$oose )$at :ind o--ile )e )ant to sa!e. lic: on t$e Rll FilesR o*tion.
+o) in t$e Filename tet%o ty*e in t$e -ilename o- your *rogram )$ic$ is
R#ello.a!aR and t$en clic: on t$e 'VE %utton.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 225/244
Introduction to Programming I 22
J.E.D.I
+o) t$at you!e sa!ed your -ile notice $o) t$e title o- t$e -rame c$anges -rom ntitled+ote*ad to #ello.a!a+ote*ad. Ta:e note t$at i- you )ant to ma:e c$anges in your -ileyou can ust edit it and t$en sa!e it again %y clic:ing on File 'a!e.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 226/244
Introduction to Programming I 22,
J.E.D.I
Step 42 "ompi&ing your program
+o) t$e net ste* is to com*ile your *rogram. @o to t$e ('D&' command *rom*t)indo) )e ust o*ened a )$ile ago.
Ty*ically )$en you o*en t$e command *rom*t )indo) it o*ens u* and ta:es youdirectly to )$at is called your home #o&der. To see )$at is inside t$at $ome -older ty*e$IR or dir and t$en *ress E+TE". $at you )ill see is a list o- -iles and -olders insideyour $ome -older.
Figure 12.2&: 4ist of files and folders shown after executing the command 68.
+o) you can see $ere t$at t$ere is a -older named R(y DocumentsR )$ere )e createdyour (JVP"&@"(' -older. +o) lets go inside t$at directory.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 227/244
Introduction to Programming I 226
J.E.D.I
To go inside a directory you ty*e in t$e command; cd @directory name, T$e RcdRcommand stands -or c$ange directory. In t$is case since t$e name o- our directory is(y Documents you ty*e in; cd My $ocuments,
Figure 12.21: 6nside the =y ocuments folder
+o) t$at you are inside t$e R(y DocumentsR -older try ty*ing in t$e RdirR commandagain and tell me )$at you see.
Figure 12.22: The contents of =y ocuments
+o) *er-orm t$e same ste*s descri%ed %e-ore to go inside t$e (JVP"&@"(' -older.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 228/244
Introduction to Programming I 22H
J.E.D.I
Figure 12.2: 6nside the =>3?3)8-@83=S folder
&nce inside t$e -older )$ere your Ja!a *rograms are let us no) start com*iling yourJa!a *rogram. Ta:e note t$at you s$ould ma:e sure t$at t$e -ile is inside t$e -older)$ere you are in. In order to do t$at eecute t$e dir command again to see i- your -ileis inside t$at -older.
To com*ile a Ja!a *rogram )e ty*e in t$e command; Ca)ac @#i&ename. 'o in t$iscase ty*e in; Ca)ac e&&o,Ca)a,
Figure 12.2%: Compile program by usingthe javac command
During com*ilation a!ac adds a -ile to t$e dis: called @#i&ename,c&ass> or in t$is case
e&&o,c&ass )$ic$ is t$e actual %ytecode.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 229/244
Introduction to Programming I 227
J.E.D.I
Step 82 Running the Program
+o) assuming t$at t$ere are no *ro%lems during com*ilation 4)ell e*lore more o- t$e*ro%lems encountered during com*ilation in t$e net section9 )e are no) ready to run
your *rogram.
To run your Ja!a *rogram ty*e in t$e command; Ca)a @#i&ename !ithout theextension so in t$e case o- our eam*le ty*e in; Ca)a e&&o
ou can see on t$e screen t$at you $a!e ust run your -irst Ja!a *rogram t$at *rints t$emessage R#ello )orldR.
Figure 12.2+: -utput of the program
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 230/244
Introduction to Programming I 22<
J.E.D.I
Setting t(e $at(
'ometimes )$en you try to in!o:e t$e a!ac or a!a command you encounter t$e
message; UCa)acU is not recognied as an interna& or externa& command> operab&eprogram or batch #i&e. T$is means t$at eit$er you $a!ent installed Ja!a in your systemyet or you $a!e to con-igure t$e *at$ on )$ere t$e Ja!a commands are installed so t$atyour system )ill :no) )$ere to -ind t$em.
Figure 12.2*: System did not recogniIe the <a$ac command
I- you are sure t$at you!e already installed Ja!a in your system try setting t$e PT#!aria%le to *oint to )$ere t$e Ja!a commands are installed. To do t$is ty*e in t$ecommand; set PAT"2XC.sd%+,<,.Y9<Xbin, T$is )ill tell your system to loo: -or t$ecommands in t$e "2XC.sd%+,<,.Y9<Xbin -older )$ic$ is usually t$e de-ault location)$erein your Ja!a -iles are *laced during installation. -ter doing t$is you can no) uset$e Ja!a commands.
Figure 12.2/: Setting the path and running <a$a
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 231/244
Introduction to Programming I 230
J.E.D.I
:sing etBeans
+o) t$at )e!e tried doing our *rograms t$e com*licated )ay lets no) see $o) to doall t$e *rocesses )e!e descri%ed in t$e *re!ious sections %y using ust one a**lication.
In t$is *art o- t$e lesson )e )ill %e using /et0eans )$ic$ is an Integrated$e)e&opment En)ironment or I$E. n IDE is a *rogramming en!ironment integratedinto a so-t)are a**lication t$at *ro!ides a @I %uilder a tet or code editor a com*ilerand8or inter*reter and a de%ugger.
Step +2 Run /et0eans
To run +etBeans clic: on start ll Programs +etBeans ,., Beta +etBeans IDE
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 232/244
Introduction to Programming I 231
J.E.D.I
-ter you!e o*en +etBeans IDE you )ill see a gra*$ical user inter-ace 4@I9 similar to)$at is s$o)n %elo).
Figure 12.20: "et9eans 6E
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 233/244
Introduction to Programming I 232
J.E.D.I
Step .2 Ma%e a proCect
+o) lets -irst ma:e a *roect. lic: on File +e) Proect.
-ter doing t$is a +e) Proect dialog )ill a**ear.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 234/244
Introduction to Programming I 233
J.E.D.I
+o) clic: on Ja!a **lication and clic: on t$e +E/T %utton.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 235/244
Introduction to Programming I 23
J.E.D.I
+o) a +e) **lication dialog )ill a**ear. Edit t$e Proect +ame *art and ty*e inR#ello**licationR.
Figure 12.27: Change )ro<ect "ame
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 236/244
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 237/244
Introduction to Programming I 236
J.E.D.I
Step -2 Type in your program
Be-ore ty*ing in your *rogram let us -irst descri%e t$e main )indo) a-ter creating t$e*roect.
s s$o)n %elo) +etBeans automatically creates t$e %asic code -or your Ja!a *rogram.ou can ust add your o)n statements to t$e generated code. &n t$e le-t side o- t$e)indo) you can see a list o- -olders and -iles t$at +etBeans generated a-ter creating t$e*roect. T$is can all %e -ound in your (JVP"&@"(' -older )$ere you set t$eProect location.
+o) try to modi-y t$e code generated %y +etBeans. Ignore t$e ot$er *arts o- t$e*rogram -or no) as )e )ill e*lain t$e details o- t$e code later. Insert t$e code;
System.out.println("Hello #orld$"%
a-ter t$e statement 88T&D& code a**lication logic $ere.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 238/244
Introduction to Programming I 23H
J.E.D.I
Step <2 "ompi&e your program
+o) to com*ile your *rogram ust clic: on Build Build (ain Proect. &r you couldalso use t$e s$ortcut %utton to com*ile your code.
Figure 12.&: Shortcut button to compile code
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 239/244
Introduction to Programming I 237
J.E.D.I
I- t$ere are no errors in your *rogram you )ill see a %uild success-ul message on t$eout*ut )indo).
Figure 12.1: -utput window <ust below the window where youtype your source code
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 240/244
Introduction to Programming I 23<
J.E.D.I
Step 42 Run your program
To run your *rogram clic: on "un "un (ain Proect. &r you could also use t$es$ortcut %utton to run your *rogram.
Figure 12.2: Shortcut button to run program
T$e out*ut o- your *rogram is dis*layed in t$e out*ut )indo).
Figure 12.: -utput of !ello.<a$a
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 241/244
Introduction to Programming I 20
J.E.D.I
Appendix $ 2 Machine Prob&ems
Mac(ine $roblem 1 $(one
Boo8 rite a *rogram t$at )ill create an *$one%oo: )$erein you can add entries in t$e*$one%oo: de&ete entries )ie! a&& entries and search -or entries. In !ie)ing allentries t$e user s$ould $a!e a c$oice )$et$er to !ie) t$e entries in a&phabetica& orderor in increasing order o- tele*$one num%ers. In searc$ing -or entries t$e user s$ouldalso $a!e an o*tion to searc$ entries by name or by te&ephone num%ers. In searc$ing%y name t$e user s$ould also $a!e an o*tion i- $e8s$e )ants to searc$ %y -irst name orlast name.
(I+ (E+
1 dd *$one%oo: entry
2 Delete *$one%oo: entry3 Vie) all entries
a al*$a%etical order% increasing order o- tele*$one num%ers
'earc$ entriesa %y name% %y tele*$one num%er
, L uit
T$e -ollo)ing )ill a**ear )$en one o- t$e c$oices in t$e main menu is c$osen.
dd *$one%oo: entry
Enter +ame;Enter Tele*$one num%er;4U i- entry already eists )arn user a%out t$is9
Vie) all entries
Dis*lays all entries in al*$a%etical orderDis*lays all entries in increasing order o- tele*$one fs
'earc$ entries
'earc$ *$one%oo: entry %y name'earc$ *$one%oo: entry %y tele*$one num%er
uit
close *$one%oo:
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 242/244
Mac(ine $roblem 2Mines!eeper
T$is is a one *layer game o- a sim*li-ied !ersion o- t$e *o*ular com*uter gamemines)ee*er. First t$e user is as:ed i- $e or s$e )ants to *lay on a ,, grid or 1010grid. ou $a!e t)o 2dimensional arrays t$at contains in-ormation a%out your grid. nentry in t$e array s$ould eit$er contain a 0 or 1. 1 signi-ies t$at t$ere is a %om% int$at location and a 0 i- none.
For eam*le gi!en t$e array;
int %om%=ist,%y,XYXYSZZ0 0 1 0 0b
Z0 0 0 0 0bZ0 1 0 0 0bZ0 0 0 1 1b
Z0 1 1 0 0bb[
@i!en t$e %om% list )e $a!e 6 %om%s on our list. T$e %om%s are located in 4ro)col9
cells 4029 4219 4339 439 419 and 429.
I- t$e user c$ooses a cell t$at contains a %om% t$e game ends and all t$e %om%s aredis*layed. I- t$e user c$ooses a cell t$at does not contain a %om% a num%er a**ears att$at location indicating t$e num%er o- neig$%ors t$at contain %om%s. T$e game s$ouldend )$en all t$e cells t$at do not contain %om%s $a!e %een mar:ed 4*layer )ins9 or)$en t$e user ste*s on a %om%4*layer loses9.
#eres a sam*le out*ut o- t$e game gi!en t$e %om%=ist,%y,.
elcome to (ines)ee*er$oose si>e o- grid 4Press 1 -or ,, Press 2 -or 10109; 1X Y X Y X Y X Y X YX Y X Y X Y X Y X YX Y X Y X Y X Y X YX Y X Y X Y X Y X YX Y X Y X Y X Y X YEnter ro) and column o- t$e cell you )ant to o*enXro) colY; 1 1X Y X Y X Y X Y X YX Y X2Y X Y X Y X YX Y X Y XY X Y X YX Y X Y X Y X Y X Y
X Y X Y X Y X Y X YEnter ro) and column o- t$e cell you )ant to o*enXro) colY; 3 2X Y X Y X Y X Y X YX Y X2 Y X Y XY X YX Y X Y X Y X Y X YX Y X Y X Y X Y X YX Y X Y X Y X Y X YEnter ro) and column o- t$e cell you )ant to o*enXro) colY; 0 2XY X Y X Y X Y X YX Y X2Y X Y XY X YX Y X/ Y X Y X Y X YX Y X Y XY X Y X Y
X Y X Y X Y X Y X Y&o***s ou ste**ed on a %om%. 'orry game o!er
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 243/244
Mac(ine $roblem 3 umberConversion
reate your o)n scienti-ic calculator t$at )ill con!ert t$e in*utted num%ers to t$e -ournum%er re*resentations 4 Decimal Binary &ctal #eadecimal 9. our *rogram s$ouldout*ut t$e -ollo)ing menu on screen.
(I+ (E+;
Please ty*e t$e num%er o- your c$oice;1 L Binary to Decimal2 L Decimal to &ctal3 L &ctal to #eadecimal L #eadecimal to Binary, L uit
T$e -ollo)ing )ill a**ear )$en one o- t$e c$oices in t$e main menu is c$osen.
$oice 1;
Enter a %inary num%er; 1100011000 %ase 2 S 2 %ase 104goes %ac: to main menu9
$oice 2;
Enter a Decimal num%er; 22 %ase 10 S 30 %ase 74goes %ac: to main menu9
$oice 3;
Enter an &ctal num%er; 3030 %ase 7 S 17 %ase 164goes %ac: to main menu9
$oice ;
Enter a #eadecimal num%er; 1717 %ase 16 S 11000 %ase 2
$oice 1;Enter a %inary num%er; 110In!alid %inary num%erEnter a %inary num%er; 1
1 %ase 2 S 1 %ase 104goes %ac: to main menu9
4user c$ooses ,9@ood%ye
ou can %e more creati!e )it$ your user inter-ace i- you )ant to as long as t$e *rogramout*uts t$e correct con!ersion o- num%ers.
8/12/2019 JEDI Course Notes Intro1 MasterDocument
http://slidepdf.com/reader/full/jedi-course-notes-intro1-masterdocument 244/244
Re#erences
1. Programming =anguage. From i:i*edia at$ tt * ; 88 e n . ) i : i * ed i a .o r g8 ) i : i8 P r og r a m m i ng Cl a n gu a g e
2. Programming =anguage. From e%o*edia at$ tt * ; 88 ))) .) e%o*e d i a .c om 8 T E" ( 8 * 8 * r og r a m m i n gCl a n g u a g e . $t m l