JEDI Course Notes Intro1 MasterDocument
JEDI Course Notes Intro1 MasterDocument
I
Introduction to Programming I 1
Introduction to
Programming I
Student's Manual
Version 1.3
June 2006
Introduction to Programming I 2
J.E.D.I
A u t h o r
Florence Tiu Balagtas
T e a m
Joyce !estro
Florence Balagtas
"ommel Feria
"eginald #utc$erson
"e%ecca &ng
Jo$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 s
Sup port ed Ope rat in g Syst em s
T$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.0., or ne)er
"ed #at Fedora 1ore 3
'olaris2 10 &*erating 'ystem 3*date 1 4'P"15 and 6768660
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 'P0
'olaris2 7 &' 4'P"1 and 6768660 Plat-orm Edition9 and 'olaris < &'
4'P"1 and 6768660 Plat-orm Edition9
Various ot$er =inu6 distri%utions
M in im um a rd ! a re " on# ig ur a ti o n
Note: The NetBeans IDE's minimum screen resolution is 1024x768
pixels.
Operating System Processor Memory $is% Space
(icroso-t .indo)s ,00 (#> Intel Pentium III ,12 (B 7,0 (B o- -ree
dis: s*ace
=inu6 ,00 (#> Intel Pentium III
)or:station or e?ui!alent
,12 (B 0,0 (B o- -ree
dis: s*ace
'olaris &' 4'P"19 3ltra'P"1 II 0,0 (#> ,12 (B 0,0 (B o- -ree
dis: s*ace
'olaris &' 46768660
Plat-orm Edition9
(D &*teron 100 'eries
1.7 @#>
,12 (B 0,0 (B o- -ree
dis: s*ace
(acintos$ &' /
o*erating system
Po)erP1 @0 ,12 (B 0,0 (B o- -ree
dis: s*ace
Recom me nded a rd! are "on#igurati on
Operating System Processor Memory $is% Speed
(icroso-t .indo)s 1.0 @#> Intel Pentium III
)or:station or e?ui!alent
1 @B 1 @B o- -ree dis:
s*ace
=inu6 1.0 @#> Intel Pentium III
)or:station or e?ui!alent
1 @B 7,0 (B o- -ree
dis: s*ace
'olaris &' 4'P"19 3ltra'P"1 IIIi 1 @#> 1 @B 7,0 (B o- -ree
dis: s*ace
'olaris &' 46768660
Plat-orm Edition9
(D &*teron 100 'eries
1.7 @#>
1 @B 7,0 (B o- -ree
dis: s*ace
(acintos$ &' /
o*erating system
Po)erP1 @, 1 @B 7,0 (B o- -ree
dis: 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 3*date 1 or $ig$er 4JDA ,.0B !ersion
1.,.0C01 or $ig$er9B )$ic$ consists o- t$e Ja!a "untime En!ironment *lus
de!elo*er tools -or com*ilingB de%uggingB and running a**lications )ritten in
t$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&arisB 'indo!sB and LinuxB you can do)nload t$e JDA -or your
*lat-orm -rom $tt*; 88 Da! a.s un .c om8D2se 81. ,.08 do )nl oa d.$ tml
For Mac OS (B Ja!a 2 Plat-orm 'tandard Edition 4J2'E9 ,.0 "elease 0B is
re?uired. Eou can do)nload t$e JDA -rom **leFs De!elo*er 1onnection
site. 'tart $ere; $ tt* ;8 8 d e ! e lo * e r. a **l e .co m 8Da ! a 4you must register to
do)nload t$e JDA9.
F o r m o r e in -o r mat ion B *l e a s e ! is it;
$ tt* ;88 ))) .n e t%e a n s . o rg 8co mm u n ity 8re le a ses 80 0 8 r e ln o te s .$ tm l
Tab&e o# "ontents
1 Introduction to 1om*uter Programming..............................................................10
1.1 &%Decti!es............................................................................................... 10
1.2 Introduction............................................................................................. 10
1.3 Basic 1om*onents o- a 1om*uter................................................................ 11
1.3.1 #ard)are.......................................................................................... 11
1.3.1.1 T$e 1entral Processing 3nit.......................................................... 11
1.3.1.2 (emory .................................................................................... 11
1.3.1.3 In*ut and &ut*ut De!ices............................................................. 12
1.3.2 'o-t)are........................................................................................... 12
1.0 &!er!ie) o- 1om*uter Programming =anguages........................................... 13
1.0.1 .$at is a Programming =anguageG....................................................... 13
1.0.2 1ategories o- Programming =anguages..................................................13
1., T$e Program De!elo*ment =i-e 1ycle........................................................... 10
1.,.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...................................... 1H
1.,.0 1oding and De%ugging....................................................................... 17
1.6 +um%er 'ystems and 1on!ersions.............................................................. 1<
1.6.1 Decimal............................................................................................ 1<
1.6.2 Binary.............................................................................................. 1<
1.6.3 &ctal................................................................................................ 1<
1.6.0 #e6adecimal..................................................................................... 1<
1.6., 1on!ersions...................................................................................... 20
1.6.,.1 Decimal to Binary 8 Binary to Decimal............................................ 20
1.6.,.2 Decimal to &ctal 4or #e6adecimal98&ctal 4or #e6adecimal9 to Decimal....
21
1.6.,.3 Binary to &ctal 8 &ctal to Binary.................................................... 22
1.6.,.0 Binary to #e6adecimal 8 #e6adecimal to Binary............................... 23
1.H E6ercises................................................................................................. 20
1.H.1 .riting lgorit$ms............................................................................. 20
1.H.2 +um%er 1on!ersions.......................................................................... 20
2 Introduction to Ja!a........................................................................................ 2,
2.1 &%Decti!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.0 de*loyment en!ironment........................................................... 26
2.2.3 'ome Features o- Ja!a........................................................................ 26
2.2.3.1 T$e Ja!a Virtual (ac$ine.............................................................. 26
2.2.3.2 @ar%age 1ollection...................................................................... 26
2.2.3.3 1ode 'ecurity............................................................................. 2H
2.2.0 P$ases o- a Ja!a Program.................................................................... 27
3 @etting to :no) your Programming En!ironment................................................. 2<
3.1 &%Decti!es............................................................................................... 2<
3.2 Introduction............................................................................................. 2<
3.3 (y First Ja!a Program............................................................................... 2<
3.0 3sing a Te6t Editor and 1onsole................................................................. 30
3.0.1 Errors .............................................................................................. 00
3.0.1.1 'ynta6 Errors............................................................................. 00
3.0.1.2 "unItime Errors.......................................................................... 01
3., 3sing +etBeans........................................................................................ 02
3.6 E6ercises................................................................................................. ,,
3.6.1 #ello .orldJ...................................................................................... ,,
3.6.2 T$e Tree........................................................................................... ,,
0 Programming Fundamentals............................................................................. ,6
0.1 &%Decti!es............................................................................................... ,6
0.2 Dissecting my -irst Ja!a *rogram................................................................ ,6
0.3 Ja!a 1omments........................................................................................ ,7
0.3.1 1KKI'tyle 1omments......................................................................... ,7
0.3.2 1I'tyle 1omments............................................................................. ,7
0.3.3 '*ecial Ja!adoc 1omments................................................................. ,7
0.0 Ja!a 'tatements and %loc:s....................................................................... ,<
0., Ja!a Identi-iers........................................................................................ 60
0.6 Ja!a Aey)ords......................................................................................... 61
0.H Ja!a =iterals............................................................................................ 62
0.H.1 Integer =iterals ................................................................................. 62
0.H.2 FloatingIPoint =iterals ........................................................................ 62
0.H.3 Boolean =iterals ................................................................................ 62
0.H.0 1$aracter =iterals .............................................................................. 63
0.H., 'tring =iterals ................................................................................... 63
0.7 Primiti!e data ty*es.................................................................................. 60
0.7.1 =ogical I %oolean............................................................................... 60
0.7.2 Te6tual L c$ar................................................................................... 60
0.7.3 Integral L %yteB s$ortB int M long.......................................................... 6,
0.7.0 Floating Point L -loat and dou%le.......................................................... 66
0.< Varia%les................................................................................................. 6H
0.<.1 Declaring and Initiali>ing Varia%les....................................................... 6H
0.<.2 &ut*utting Varia%le Data.................................................................... 67
0.<.3 'ystem.out.*rintln49 !s. 'ystem.out.*rint49 ......................................... 67
0.<.0 "e-erence Varia%les !s. Primiti!e Varia%les............................................ 6<
0.10 &*erators.............................................................................................. H0
0.10.1 rit$metic o*erators......................................................................... H0
0.10.2 Increment and Decrement o*erators................................................... H3
0.10.3 "elational o*erators......................................................................... H,
0.10.0 =ogical o*erators.............................................................................. H7
0.10.0.1 MM 4logical +D9 and M 4%oolean logical +D9............................... H<
0.10.0.2 NN 4logical &"9 and N 4%oolean logical inclusi!e &"9.........................71
0.10.0.3 O 4%oolean logical e6clusi!e &"9.................................................. 73
0.10.0.0 J 4logical +&T9.......................................................................... 70
0.10., 1onditional &*erator 4G;9.................................................................. 7,
0.10.6 &*erator Precedence........................................................................ 7H
0.11 E6ercises............................................................................................... 77
0.11.1 Declaring and *rinting !aria%les......................................................... 77
0.11.2 @etting t$e a!erage o- t$ree num%ers................................................. 77
0.11.3 &ut*ut greatest !alue....................................................................... 77
0.11.0 &*erator *recedence........................................................................ 77
, @etting In*ut -rom t$e Aey%oard....................................................................... 7<
,.1 &%Decti!es............................................................................................... 7<
,.2 3sing Bu--ered"eader to get in*ut.............................................................. 7<
,.3 3sing J&*tionPane to get in*ut................................................................... <3
,.0 E6ercises................................................................................................. <,
,.0.1 =ast 3 )ords 4Bu--ered"eader !ersion9.................................................. <,
,.0.2 =ast 3 )ords 4J&*tionPane !ersion9...................................................... <,
6 1ontrol 'tructures........................................................................................... <6
6.1 &%Decti!es............................................................................................... <6
6.2 Decision 1ontrol 'tructures........................................................................ <6
6.2.1 i- statement...................................................................................... <6
6.2.2 i-Ielse statement............................................................................... <7
6.2.3 i-IelseIi- statement........................................................................... 100
6.2.0 1ommon Errors )$en using t$e i-Ielse statements;............................... 101
6.2., E6am*le -or i-IelseIelse i-.................................................................. 102
6.2.6 s)itc$ statement............................................................................. 103
6.2.H E6am*le -or s)itc$........................................................................... 10,
6.3 "e*etition 1ontrol 'tructures.................................................................... 106
6.3.1 )$ile loo*....................................................................................... 106
6.3.2 doI)$ile loo*................................................................................... 107
6.3.3 -or loo*........................................................................................... 10<
6.0 Branc$ing 'tatements............................................................................. 110
6.0.1 %rea: statement.............................................................................. 110
6.0.1.1 3nla%eled %rea: statement......................................................... 110
6.0.1.2 =a%eled %rea: statement............................................................ 111
6.0.2 continue statement.......................................................................... 112
6.0.2.1 3nla%eled continue statement..................................................... 112
6.0.2.2 =a%eled continue statement........................................................ 112
6.0.3 return statement.............................................................................. 113
6., E6ercises............................................................................................... 110
6.,.1 @rades........................................................................................... 110
6.,.2 +um%er in )ords.............................................................................. 110
6.,.3 #undred Times................................................................................ 110
6.,.0 Po)ers........................................................................................... 110
H Ja!a rrays.................................................................................................. 11,
H.1 &%Decti!es............................................................................................. 11,
H.2 Introduction to arrays.............................................................................. 11,
H.3 Declaring rrays..................................................................................... 116
H.0 ccessing an array element...................................................................... 117
H., rray lengt$........................................................................................... 11<
H.6 (ultidimensional rrays........................................................................... 120
H.H E6ercises............................................................................................... 121
H.H.1 Days o- t$e .ee:............................................................................. 121
H.H.2 @reatest num%er.............................................................................. 121
H.H.3 ddress%oo: Entries......................................................................... 121
7 1ommandIline rguments.............................................................................. 122
7.1 &%Decti!es............................................................................................. 122
7.2 1ommandIline arguments........................................................................ 122
7.3 1ommandIline arguments in +etBeans...................................................... 120
7.0 E6ercises............................................................................................... 127
7.0.1 Print arguments............................................................................... 127
7.0.2 rit$metic &*erations....................................................................... 127
< .or:ing )it$ t$e Ja!a 1lass =i%rary................................................................. 12<
<.1 &%Decti!es............................................................................................. 12<
<.2 Introduction to &%DectI&riented Programming............................................. 12<
<.3 1lasses and &%Dects................................................................................ 130
<.3.1 Di--erence Bet)een 1lasses and &%Dects.............................................. 130
<.3.2 Enca*sulation.................................................................................. 131
<.3.3 1lass Varia%les and (et$ods.............................................................. 131
<.3.0 1lass Instantiation........................................................................... 132
<.0 (et$ods................................................................................................ 133
<.0.1 .$at are (et$ods and .$y 3se (et$odsG........................................... 133
<.0.2 1alling Instance (et$ods and Passing Varia%les....................................130
<.0.3 Passing Varia%les in (et$ods............................................................. 13,
<.0.3.1 PassI%yI!alue........................................................................... 13,
<.0.3.2 PassI%yIre-erence...................................................................... 136
<.0.0 1alling 'tatic (et$ods...................................................................... 13H
<.0., 'co*e o- a !aria%le........................................................................... 137
<., 1astingB 1on!erting and 1om*aring &%Dects............................................... 101
<.,.1 1asting Primiti!e Ty*es..................................................................... 101
<.,.2 1asting &%Dects............................................................................... 103
<.,.3 1on!erting Primiti!e Ty*es to &%Dects and Vice Versa............................ 10,
<.,.0 1om*aring &%Dects........................................................................... 106
<.,., Determining t$e 1lass o- an &%Dect..................................................... 107
<.6 E6ercises............................................................................................... 10<
<.6.1 De-ining terms................................................................................. 10<
<.6.2 Ja!a 'ca!enger #unt........................................................................ 10<
10 1reating your o)n 1lasses............................................................................ 1,0
10.1 &%Decti!es............................................................................................ 1,0
10.2 De-ining your o)n classes...................................................................... 1,1
10.3 Declaring ttri%utes.............................................................................. 1,2
10.3.1 Instance Varia%les.......................................................................... 1,2
10.3.2 1lass Varia%les or 'tatic Varia%les.................................................... 1,3
10.0 Declaring (et$ods................................................................................ 1,3
10.0.1 ccessor met$ods........................................................................... 1,0
10.0.2 (utator (et$ods............................................................................ 1,,
10.0.3 (ulti*le "eturn statements.............................................................. 1,6
10.0.0 'tatic met$ods............................................................................... 1,6
10.0., 'am*le 'ource 1ode -or 'tudent"ecord class..................................... 1,H
10., T$e t$is re-erence................................................................................. 1,<
10.6 &!erloading (et$ods............................................................................. 160
10.H Declaring 1onstructors........................................................................... 162
10.H.1 De-ault 1onstructor........................................................................ 162
10.H.2 &!erloading 1onstructors................................................................ 162
10.H.3 3sing 1onstructors......................................................................... 163
10.H.0 T$e t$is49 1onstructor 1all............................................................... 160
10.7 Pac:ages............................................................................................. 16,
10.7.1 Im*orting Pac:ages........................................................................ 16,
10.7.2 1reating your o)n *ac:ages............................................................ 16,
10.7.3 'etting t$e 1=''PT#.................................................................. 166
10.< ccess (odi-iers................................................................................... 167
10.<.1 de-ault access 4also called *ac:age accessi%ility9................................ 167
10.<.2 *u%lic access................................................................................. 167
10.<.3 *rotected access............................................................................ 16<
10.<.0 *ri!ate access................................................................................ 16<
10.10 E6ercises........................................................................................... 1H0
10.10.1 ddress Boo: Entry....................................................................... 1H0
10.10.2 ddressBoo:................................................................................ 1H0
11 In$eritanceB Polymor*$ism and Inter-aces....................................................... 1H1
11.1 &%Decti!es............................................................................................ 1H1
11.2 In$eritance.......................................................................................... 1H1
11.2.1 De-ining 'u*erclasses and 'u%classes............................................... 1H2
11.2.2 T$e su*er :ey)ord......................................................................... 1H0
11.2.3 &!erriding (et$ods........................................................................ 1H,
11.2.0 Final (et$ods and Final 1lasses........................................................ 1H6
11.3 Polymor*$ism...................................................................................... 1HH
11.0 %stract 1lasses................................................................................... 1H<
11., Inter-aces............................................................................................ 171
11.,.1 .$y do )e use Inter-acesG.............................................................. 171
11.,.2 Inter-ace !s. %stract 1lass.............................................................. 171
11.,.3 Inter-ace !s. 1lass.......................................................................... 172
11.,.0 1reating Inter-aces......................................................................... 172
11.,., "elations$i* o- an Inter-ace to a 1lass............................................... 170
11.,.6 In$eritance among Inter-aces........................................................... 170
11.6 E6ercises............................................................................................. 17,
11.6.1 E6tending 'tudent"ecord................................................................ 17,
11.6.2 T$e '$a*e a%stract class................................................................. 17,
12 Basic E6ce*tion #andling.............................................................................. 176
12.1 &%Decti!es............................................................................................ 176
12.2 .$at are E6ce*tionsG............................................................................ 176
12.3 #andling E6ce*tions.............................................................................. 176
12.0 E6ercises............................................................................................. 17<
12.0.1 1atc$ing E6ce*tions1...................................................................... 17<
12.0.2 1atc$ing E6ce*tions 2..................................................................... 17<
**endi6 ; Ja!a and +etBeans Installation......................................................... 1<0
Installing Ja!a in 3%untu Da**er..................................................................... 1<1
Installing Ja!a in .indo)s............................................................................. 1<6
Installing +etBeans in 3%untu Da**er.............................................................. 200
Installing +etBeans in .indo)s....................................................................... 207
**endi6 B; @etting to :no) your Programming En!ironment 4.indo)s /P !ersion9.. 21,
(y First Ja!a Program................................................................................... 21,
3sing a Te6t Editor and 1onsole...................................................................... 216
'etting t$e Pat$........................................................................................ 22<
3sing +etBeans............................................................................................ 230
**endi6 D ; (ac$ine Pro%lems.......................................................................... 200
(ac$ine Pro%lem 1; P$one Boo:...................................................................... 200
(ac$ine Pro%lem 2; (ines)ee*er.................................................................... 201
(ac$ine Pro%lem 3; +um%er 1on!ersion........................................................... 202
Re)ision istory
For *ersion +,-
June 2006
Section $etai&s
**endi6 and BB 1$a*ter 3;@etting
to :no) your *rogramming
en!ironment
')itc$ to +et%eans ,., Beta Version
**endi6 B 1$a*ter 3;@etting to
:no) your *rogramming en!ironment
')itc$ -rom "ed$at =inu6 to 3%untu Da**er
**endi6 F; dditional E6ercises dded 4Teac$erFs manual9Ic8o JEDI mem%er
sc$ool teac$ers
For *ersion +,.
January 2006
Section $etai&s
Version +um%er 1$ange -rom 1.1 to 1.2
1$a*ter 3; @ettting to :no) your
*rogramming en!ironment
**endi6
1$ange +et%eans8net%eans to /et0eans
1$a*ter 0; Programming
Fundamentals
=ist o- Ja!a :ey)ords
1$a*ter 10; 1reating your o)n classes 1oding guidelines; -ilenames s$ould $a!e t$e
same 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 1$ange -rom 1.0 to 1.1
"e!ision #istory dded
**endi6 E; #andsIon =a% E6ercises dded 4c8o 'ang9
1$a*ter 10; 1reating Eour o)n classes dded su%section on #o) to set class*at$ at
*ac:ages section
1$a*ter 11; In$eritanceB Inter-aces
and Polymor*$ism
Polymor*$ism section
dded e6am*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
J.E.D.I
Section $etai&s
Inter-ace !s. %stract 1lass
Inter-ace !s. 1lass
"elations$i* o- an Inter-ace to a 1lass
In$eritance among Inter-aces
Introduction to Programming I <
Introduction to Programming I 10
10
J.E.D.I
+ Introduction to "omputer
Programming
1.1 Objectives
In t$is sectionB )e )ill %e discussing t$e %asic com*onents o- a com*uterB %ot$ $ard)are
and 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. FinallyB di--erent num%er systems and con!ersions -rom
one ty*e to anot$er )ill %e discussed.
t t$e end o- t$e lessonB 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
3nderstand 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-ic
instructions. 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 maDor com*onents. T$e -irst one is t$e ard!are )$ic$ is t$e
tangi%le *art o- t$e com*uter. It is com*osed o- electronic and mec$anical *arts.
T$e second maDor 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.
Introduction to Programming I 11
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 P%rainQ o- t$e com*uter. It contains millions o- e6tremely tiny
electrical *arts. It does t$e -undamental com*uting )it$in t$e system. E6am*les o-
*rocessors are PentiumB t$lon and 'P"1.
+,-,+,. Memory
T$e memory is )$ere data and instructions needed %y t$e 1P3 to do its a**ointed tas:s
can %e -ound. It is di!ided into se!eral storage locations )$ic$ $a!e corres*onding
addresses. T$e 1P3 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 *rograms
and dataB t$at t$e *rocessor is acti!ely )or:ing )it$. It is not used -or longIterm
storage. It is sometimes called t$e "( 4"andom ccess (emory9.
T$e com*uterFs main memory is considered as volatile storage. T$is means t$at once
t$e com*uter is turned o--B 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 and
data -or long term use. E6am*les o- secondary memory are $ard dis:s and cdIrom.
'econdary memory is considered as non"volatile storage. T$is means t$at in-ormation
residing in secondary memory is not erased a-ter t$e com*uter is turned o--.
Main
Memor#
Secondar#
Memor#
$ropert#
Fast 'lo) '*eed
E6*ensi!e 1$ea* Price
=o) #ig$ 1a*acity
Ees +o Volatile
Table 1: Comparison between main memory and secondary memory
Introduction to Programming I 12
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 %y
mo!ing data into and out o- t$e system.
E6am*les o- in*ut de!ices are :ey%oardsB mice and micro*$ones. E6am*les o- out*ut
de!ices are monitorsB *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:B %ut it itsel- is intangi%le. T$e data t$at t$e com*uter
uses 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
E6am*les;
&*erating 'ystems li:e =inu6B .indo)sB 3ni6B 'olarisB (ac&'
., App&ication Programs
Programs t$at *eo*le use to get t$eir )or: done
E6am*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*le
to create *rograms out o- >eros and onesB t$ere must %e a )ay o- translating or
con!erting a language )$ic$ )e understand into mac$ine languageB -or t$is
*ur*oseB t$ere e6ists com*ilers.
Introduction to Programming I 13
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 e6*ressing
instructions to a com*uter. =i:e $uman languagesB eac$ language $as its o)n synta6
and grammar.
Programming languages ena%le a *rogrammer to *recisely s*eci-y )$at data a com*uter
)ill act u*onB $o) t$ese data )ill %e stored8transmittedB and *recisely )$at actions to
ta:e under !arious circumstances.
T$ere are di--erent ty*es o- *rogramming languages t$at can %e used to create
*rogramsB %ut regardless o- )$at language you useB t$ese instructions are translated
into mac$ine language t$at can %e understood %y com*uters.
1.%.2 Categories of $rogramming &anguages
+, igh3&e)e& Programming Languages
$ig$Ile!el *rogramming language is a *rogramming language t$at is more userI
-riendlyB to some e6tent *lat-ormIinde*endentB and a%stract -rom lo)Ile!el
com*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.
E6am*les are Ja!aB 1B 1KKB BasicB Fortran
., Lo!3&e)e& Assemb&y Language
ssem%ly languages are similar to mac$ine languagesB %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$ 1P3 -amilyB and eac$ assem%ly
instruction is translated into one mac$ine instruction %y an assemb&er *rogram.
/ote2 T$e terms R$ig$Ile!elR and Rlo)Ile!elR are in$erently relati!e. &riginallyB assem%ly
language )as considered lo)Ile!el and 1&B&=B 1B etc. )ere considered $ig$Ile!el. (any
*rogrammers today mig$t re-er to t$ese latter languages as lo)Ile!el.
Introduction to Programming I 10
10
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 a
com*uter *rogram. InsteadB t$ey -ollo) an organi>ed *lan or met$odologyB t$at %rea:s
t$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$e
com*uter;
1. Pro%lem De-inition
2. Pro%lem nalysis
3. lgorit$m design and re*resentation 4Pseudocode or -lo)c$art9
0. 1oding and de%ugging
In order to understand t$e %asic ste*s in sol!ing a *ro%lem on a com*uterB let us de-ine
a single *ro%lem t$at )e )ill sol!e ste*I%yIste* as )e discuss t$e *ro%lem sol!ing
met$odologies in detail. T$e *ro%lem )e )ill sol!e )ill %e de-ined in t$e ne6t section.
Introduction to Programming I 1,
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%lemB t$e *ro%lem must %e )ell and clearly de-ined -irst
in terms o- its in*ut and out*ut re?uirements.
clearly de-ined *ro%lem is already $al- t$e solution. 1om*uter *rogramming re?uires
us 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.
P1reate 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-inedB t$e sim*lest and yet t$e most e--icient
and e--ecti!e a**roac$ to sol!e t$e *ro%lem must %e -ormulated.
3suallyB t$is ste* in!ol!es %rea:ing u* t$e *ro%lem into smaller and sim*ler su%I
*ro%lems.
0-ample $roblem.
Determine t$e num%er o- times a name occurs in a list
Input to t(e program.
list o- namesB name to loo: -or
Output of t(e
program.
t$e num%er o- times t$e name occurs in a list
YES
Introduction to Programming I 16
16
J.E.D.I
1.*.3 /lgorit(m design and representation
&nce our *ro%lem is clearly de-inedB )e can no) set to -inding a solution. In com*uter
*rogrammingB it is normally re?uired to e6*ress our solution in a ste*I%yIste* 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 e6*ressed in eit$er uman &anguage 4Englis$B Tagalog9B t$roug$ a
gra*$ical re*resentation li:e a #&o!chart or t$roug$ a pseudocodeB )$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 sectionsB $o) do )e e6*ress our general
solution in suc$ a )ay t$at it is sim*le yet understanda%leG
0-pressing our solution t(roug( uman
language.
1. @et t$e list o- names
2. @et t$e name to loo: -orB letFs call t$is t$e :eyname
3. 1om*are t$e :eyname to eac$ o- t$e names in t$e list
0. I- t$e :eyname is t$e same )it$ a name in t$e listB add 1 to t$e count
,. I- all t$e names $a!e %een com*aredB out*ut t$e result
0-pressing our solution t(roug( a
flo!c(art.
Figure 1.1: Example of a flow chart
Introduction to Programming I 1H
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 1ount S 0
For eac$ name in +ame=ist do t$e -ollo)ing
i- name SS :ey+ame
1ount S 1ount K 1
Dis*lay 1ount
Figure 1.2: Example of a pseudocode
+,4,-,+ F&o!charting Symbo&s and their
meanings
-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$erB 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. Eou can use
any sym%ols in creating your -lo)c$artsB as long as you are consistent in using t$em.
S#mbol 1ame Meaning
"e*resents t$e *rocess o- e6ecuting a de-ined
o*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 !alueB -ormB or location o- in-ormation.
lso -unctions as t$e de-ault sym%ol )$en no
ot$er sym%ol is a!aila%le.
"e*resents an I8& -unctionB )$ic$ ma:es data
a!aila%le -or *rocessing 4in*ut9 or dis*laying
4out*ut9o- *rocessed in-ormation.
"e*resents t$e se?uence o- a!aila%le in-ormation
and e6ecuta%le o*erations.T$e lines connect
ot$er sym%olsB and t$e arro)$eads are
mandatory only -or rig$tItoIle-t and %ottomItoI
to* -lo).
"e*resents t$e addition o- descri*ti!e
in-ormationB commentsB or e6*lanatory notes as
clari-ication. T$e !ertical line and t$e %ro:en line
may %e *laced on t$e le-tB as s$o)nB or on t$e
rig$t.
$ecision Symbo&
Termina& Symbo&
"e*resents a decision t$at determines )$ic$ o- a
num%er o- alternati!e *at$s is to %e -ollo)ed.
"e*resents t$e %eginningB t$e endB or a *oint o-
interru*tion or delay in a *rogram.
S#mbol 1ame Meaning
"e*resents any entry -romB or e6it toB anot$er
*art o- t$e -lo)c$art. lso ser!es as an o--I*age
"onnector
Symbo&
Prede#ined
Process Symbo&
connector.
"e*resents a named *rocess consisting o- one or
more o*erations or *rogram ste*s t$at are
s*eci-ied else)$ere.
Table 2: Flowchart Symbols
1.*.% Coding and ,ebugging
-ter constructing t$e algorit$mB it is no) *ossi%le to create t$e source code. 3sing t$e
algorit$m as %asisB t$e source code can no) %e )ritten using t$e c$osen *rogramming
language.
(ost o- t$e timeB a-ter t$e *rogrammer $as )ritten t$e *rogramB t$e *rogram isnFt 100T
)or:ing rig$t a)ay. T$e *rogrammer $as to add some -i6es to t$e *rogram in case o-
errors 4also called %ugs9 t$at occurs in t$e *rogram. T$is *rocess o- is called
debugging.
T$ere are t)o ty*es o- errors t$at a *rogrammer )ill encounter along t$e )ay. T$e -irst
one is com*ileItime errorB and t$e ot$er is runtime error.
Compile"+ime 0rrors occur i- t$ere is a synta6 error in t$e code. T$e com*iler )ill
detect t$e error and t$e *rogram )onFt e!en com*ile. t t$is *ointB t$e *rogrammer is
una%le to -orm an e6ecuta%le t$at a user can run until t$e error is -i6ed.
Forgetting a semiIcolon at t$e end o- a statement or miss*elling a certain commandB -or
e6am*leB is a com*ileItime error. ItFs somet$ing t$e com*iler can detect as an error.
1om*ilers arenFt *er-ect and so canFt catc$ all errors at com*ile time. T$is is es*ecially
true -or logic errors suc$ as in-inite loo*s. T$is ty*e o- error is called runtime error.
For e6am*leB t$e actual synta6 o- t$e code loo:s o:ay. But )$en you -ollo) t$e codeFs
logicB t$e same *iece o- code :ee*s e6ecuting o!er and o!er again in-initely so t$at it
loo*s. In suc$ a caseB com*ilers arenFt really smart enoug$ to catc$ all o- t$ese ty*es o-
errors at com*ileItimeB and t$ere-oreB t$e *rogram com*iles -ine into an e6ecuta%le -ile.
#o)e!erB and un-ortunatelyB )$en t$e endIuser runs t$e *rogramB t$e *rogram 4or e!en
t$eir )$ole com*uter9 -ree>es u* due to an in-inite loo*. &t$er ty*es o- runItime errors
are )$en an incorrect !alue is com*utedB t$e )rong t$ing $a**ensB etc.
1.2 1umber 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.2.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 0I<. #ere are e6am*les o-
num%ers )ritten in decimal -orm;
12610 4normally )ritten as Dust 1269
1110 4normally )ritten as Dust 119
1.2.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. #ere
are e6am*les o- num%ers )ritten in %inary -orm;
11111102
10112
1.2.3 Octal
+um%ers in octal -orm are in %ase 7. T$is means t$at t$e only legal digits are 0IH. .e
need to )rite t$e su%scri*t
7
to indicate t$at t$e num%er is an octal num%er. #ere are
e6am*les o- num%ers )ritten in octal -orm;
1H67
137
1.2.% e-adecimal
+um%ers in $e6adecimal -orm are in %ase 16. T$is means t$at t$e only legal digits are 0I
< and t$e letters IF 4or aI-B lo)ercase or u**ercase does not matter9. .e need to )rite
t$e su%scri*t
16
to indicate t$at t$e num%er is a $e6adecimal num%er. #ere are
e6am*les o- num%ers )ritten in $e6adecimal -orm;
HE16
B
16
#e6adecimal 0 1 2 3 0 , 6 H 7 < B 1 D E F
Decimal E?ui!alent
0 1 2 3 0 , 6 H 7 < 10 11 12 13 10
1
,
Table : !exadecimal "umbers and their E#ui$alence to decimal numbers
,ecimal Binar# Octal e-adecimal
126
10
1111110
2
1H6
7
HE
16
11
10
1011
2
13
7
B
16
Table %: Summary of Examples
Introduction to Programming I 20
20
.
r
i
t
e
i
t
t
$
i
s
)
a
y
1.2.* Conversions
+,8,4,+ $ecima& to 0inary 5 0inary to $ecima&
To con!ert a decimal num%er to %inaryB continuously di!ide t$e num%er %y 2 and get t$e
remainder 4)$ic$ is eit$er 0 or 19B 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 -rom
t$e last remainderB 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 Dust co*y t$e
!alue to t$e remainder *ortion.
For Example:
126
10
S G
2
3uotient 4emainder
126 8 2 S 63 0
63 8 2 S 31 1
31 8 2 S 1, 1
1, 8 2 S H 1
H 8 2 S 3 1
3 8 2 S 1 1
1 8 2 S 1
'oB )riting t$e remainders -rom t$e %ottom u*B )e get t$e %inary num%er 1111110
.
To con!ert a %inary num%er to decimalB )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 decimal
num%er.
For Example:
111111&
2
' (
1&
)osition * + % 2 1 &
Binary
Digits
+ + + + + + 9
0 6 2
0
S 0
1 6 2
1
S 2
1 6 2
2
S 0
1 6 2
3
S 7
1 6 2
0
S 16
1 6 2
,
S 32
1 6 2
6
S 60
T&T=; 126
.
r
i
t
e
i
t
t
$
i
s
)
a
y
.
r
i
t
e
i
t
t
$
i
s
)
a
y
+,8,4,. $ecima& to Octa& 6or exadecima&75Octa& 6or exadecima&7 to
$ecima&
1on!erting decimal num%ers to &ctal or $e6adecimal is %asically t$e same as con!erting
decimal to %inary. #o)e!erB instead o- $a!ing 2 as t$e di!isorB you re*lace it )it$ 74-or
octal9 or 16 4-or $e6adecimal9.
For Example ,-ctal.:
126
10
S G
7
3uotient 4emainder
126 8 7 S 1, 6
1, 8 7 S 1 H
1 8 7 S 1
'oB )riting t$e remainders -rom t$e %ottom u*B )e get t$e octal num%er 1H6
:
For Example ,!exadecimal.:
126
10
S G
16
3uotient 4emainder
10 4e?ual to $e6
126 8 16 S H
digit E9
H 8 16 S H
'oB )riting t$e remainders -rom t$e %ottom u*B )e get t$e $e6adecimal num%er HE
+8
U U U
1on!erting octal or $e6adecimal num%ers is also t$e same as con!erting %inary num%ers
to decimal. To do t$atB )e )ill Dust re*lace t$e %ase num%er 2 )it$ 7 -or &ctal and 16 -or
$e6adecimal.
For Example ,-ctal.:
1/*
0
' (
1&
)osition 2 1 &
&ctal Digits + ; 8
6 6 7
0
S 6
H 6 7
1
S ,6
1 6 7
2
S 60
T&T=; 126
For Example ,!exadecimal.:
/E
1*
' (
1&
)osition 1 &
#e6 Digits ; E
10 6 16
0
S 10
H 6 16
1
S 112
T&T=; 126
+,8,4,- 0inary to Octa& 5 Octa& to 0inary
To con!ert -rom %inary num%ers to octalB )e *artition t$e %inary num%er into grou*s o- 3
digits 4-rom rig$t to le-t9B and *ad it )it$ >eros i- t$e num%er o- digits is not di!isi%le %y
3. .e t$en con!ert eac$ *artition into its corres*onding octal digit. T$e -ollo)ing is a
ta%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
0 100
, 101
6 110
H 111
Table +: -ctal 1igits 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
1on!erting octal num%ers to %inary is Dust t$e o**osite o- )$at is gi!en a%o!e. 'im*ly
con!ert eac$ octal digit into its %inary re*resentation 4gi!en t$e ta%le9 and concatenate
t$em. T$e result is t$e %inary re*resentation.
+,8,4,< 0inary to exadecima& 5 exadecima& to
0inary
To con!ert -rom %inary num%ers to $e6adecimalB )e *artition t$e %inary num%er into
grou*s o- 0 digits 4-rom rig$t to le-t9B and *ad it )it$ >eros i- t$e num%er o- digits is not
di!isi%le %y 0. .e t$en con!ert eac$ *artition into its corres*onding $e6adecimal digit.
T$e -ollo)ing is a ta%le s$o)ing t$e %inary re*resentation o- eac$ $e6adecimal digit.
e-adecimal
,igit
Binar#
4epresentation
0 0000
1 0001
2 0010
3 0011
0 0100
, 0101
6 0110
H 0111
7 1000
< 1001
1010
B 1011
1 1100
D 1101
E 1110
F 1111
Table *: !exadecimal 1igits and their corresponding binary represenation
For Example:
111111&
2
' (
1*
5 1 1 1 1 1 1 5
; E
E?ui!alent #e6adecimal
num%er
1on!erting $e6adecimal num%ers to %inary is Dust t$e o**osite o- )$at is gi!en a%o!e.
'im*ly con!ert eac$ $e6adecimal digit into its %inary re*resentation 4gi!en t$e ta%le9
and concatenate t$em. T$e result is t$e %inary re*resentation.
1.6 0-ercises
1.6.1 'riting /lgorit(ms
@i!en t$e -ollo)ing set o- tas:sB create an algorit$m to accom*lis$ t$e -ollo)ing tas:s.
Eou may )rite your algorit$ms using *seudocodes or you can use -lo)c$arts.
1. Ba:ing Bread
2. =ogging into your la%oratoryFs com*uter
3. @etting t$e a!erage o- t$ree num%ers
1.6.2 1umber Conversions
1on!ert t$e -ollo)ing num%ers;
1. 1<70
10
to %inaryB $e6adecimal and octal
2. 1001001101
2
to decimalB $e6adecimal and octal
3. H6
7
to %inaryB $e6adecimal and decimal
0. 03F
16
to %inaryB decimal and octal
. Introduction to =a)a
2.1 Objectives
In t$is sectionB )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 lessonB 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$ineB 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:B in $onor o- t$e tree outside @oslingFs )indo)B 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$at
could %e em%edded in !arious consumer electronic *roducts li:e toasters and
re-rigerators. &ne o- t$e -irst *roDects de!elo*ed using Ja!a )as a *ersonal $andI$eld
remote control named 'tar H.
t a%out t$e same timeB 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 &anguageB Ja!a can create all :inds o- a**lications t$at you could
create using any con!entional *rogramming language.
.,.,.,. A de)e&opment en)ironment
s a de)e&opment en)ironmentB Ja!a tec$nology *ro!ides you )it$ a large suite o-
tools; a com*ilerB an inter*reterB a documentation generatorB a class -ile *ac:aging toolB
and so on.
.,.,.,- An app&ication en)ironment
Ja!a tec$nology a**lications are ty*ically generalI*ur*ose *rograms t$at run on any
mac$ine )$ere t$e =a)a runtime en)ironment 4J"E9 is installed.
.,.,.,< A dep&oyment en)ironment
T$ere are t!o main dep&oyment en)ironments2 First> the =RE su**lied %y t$e Ja!a
2
'o-t)are De!elo*ment Ait 4'DA9 contains t$e com*lete set o- class -iles -or all t$e Ja!a
tec$nology *ac:agesB )$ic$ includes %asic language classesB @3I com*onent classesB
and so on. T$e ot$er main de*loyment en!ironment is on your !eb bro!ser. (ost
commercial %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 emulating
so-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-ormIinde*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)areB so
any com*uter )it$ a Ja!a inter*reter can e6ecute t$e com*iled Ja!a *rogramB 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!erB a-ter using t$at allocated memoryB t$ere s$ould %e a )ay to deallocate t$at
memory %loc: in order -or ot$er *rograms to use it again. In 1B 1KK and ot$er
languages t$e *rogrammer is res*onsi%le -or t$is. T$is can %e di--icult at times since
t$ere can %e instances )$erein t$e *rogrammers -orget to deallocate memory and
t$ere-or result to )$at )e call memory lea:s.
In Ja!aB t$e *rogrammer is -reed -rom t$e %urden o- $a!ing to deallocate t$at memory
t$emsel!es %y $a!ing )$at )e call t$e garbage co&&ection thread. T$e gar%age
collection t$read is res*onsi%le -or -reeing any memory t$at can %e -reed. T$is $a**ens
automatically during t$e li-etime o- t$e Ja!a *rogram.
.,.,-,- "ode Security
1ode security is attained in Ja!a t$roug$ t$e im*lementation o- its =a)a Runtime
En)ironment 6=RE7, T$e J"E runs code com*iled -or a JV( and *er-orms class loading
4t$roug$ t$e class loader9B code !eri-ication 4t$roug$ t$e %ytecode !eri-ier9 and -inally
code e6ecution.
T$e "&ass Loader is res*onsi%le -or loading all classes needed -or t$e Ja!a *rogram. It
adds security %y se*arating t$e names*aces -or t$e classes o- t$e local -ile system -rom
t$ose t$at are im*orted -rom net)or: sources. T$is limits any TroDan $orse a**lications
since local classes are al)ays loaded -irst. -ter loading all t$e classesB t$e memory
layout o- t$e e6ecuta%le is t$en determined. T$is adds *rotection against unaut$ori>ed
access to restricted areas o- t$e code since t$e memory layout is determined during
runtime.
-ter loading t$e class and layouting o- memoryB 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%Dects.
-ter all o- t$ese $a!e %een doneB t$e code is t$en -inally e6ecuted.
2.2.% $(ases of a 7ava $rogram
T$e -ollo)ing -igure descri%es t$e *rocess o- com*iling and e6ecuting a Ja!a *rogram.
Figure 2.1: )hases of a 2a$a )rogram
T$e -irst ste* in creating a Ja!a *rogram is %y )riting your *rograms in a te6t editor.
E6am*les o- te6t editors you can use are note*adB !iB emacsB etc. T$is -ile is stored in a
dis: -ile )it$ t$e e6tension .java.
-ter creating and sa!ing your Ja!a *rogramB com*ile t$e *rogram %y using t$e Ja!a
1om*iler. T$e out*ut o- t$is *rocess is a -ile o- Ja!a bytecodes )it$ t$e -ile e6tension
.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 te6t editor File )it$ .Da!a e6tension
1om*ile t$e *rogram Ja!a 1om*iler File )it$ .class e6tension
4Ja!a %ytecodes9
"un t$e *rogram Ja!a Inter*reter Program &ut*ut
Table /: Summary of )hases of a 2a$a )rogram
- ?etting to %no! your Programming
En)ironment
3.1 Objectives
In t$is sectionB )e )ill %e discussing on $o) to )riteB com*ile and run Ja!a *rograms.
T$ere are t)o )ays o- doing t$isB t$e -irst one is %y using a console and a te6t editor.
T$e second one is %y using +etBeans )$ic$ is an Integrated $e)e&opment
En)ironment or I$E.
t t$e end o- t$e lessonB t$e student s$ould %e a%le to;
1reate a Ja!a *rogram using te6t editor and console in t$e =inu6 43%untu Da**er9
en!ironment
Di--erentiate %et)een synta6Ierrors and runtime errors
1reate a Ja!a *rogram using +etBeans
3.2 Introduction
n IDE is a *rogramming en!ironment integrated into a so-t)are a**lication t$at
*ro!ides a @3I %uilderB a te6t or code editorB a com*iler and8or inter*reter and a
de%ugger.
T$is tutorial uses 3%untu Da**er as t$e o*erating system. (a:e sure t$at %e-ore you do
t$is tutorialB you $a!e installed Ja!a and +etBeans in your system. For instructions on
$o) to install Ja!a and +etBeansB *lease re-er to Appendix A. For t$e .indo)s /P
!ersion o- t$is sectionB *lease re-er to Appendix 0.
Be-ore going into detailsB 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 screen
System.out.println("Hello #orld$"%
&
&
Be-ore )e try to e6*lain )$at t$e *rogram meansB letFs -irst try to )rite t$is *rogram in a
-ile and try to run it.
Introduction to Programming I 30
30
3.% :sing a +e-t 0ditor and Console
For t$is e6am*leB )e )ill %e using a te6t editor to edit t$e Ja!a source code. Eou )ill also
need to o*en t$e Terminal )indo) to com*ile and e6ecute your Ja!a *rograms.
Step +2 Start the Text Editor
To start t$e Te6t Editor in =inu6B clic: on **licationsIVccessoriesIVTe6t Editor.
Figure .1: Text Editor 3pplication in 4inux
Step .2 Open Termina&
To o*en Terminal in =inu6B clic: on **licationsIV ccessoriesIV Terminal.
Figure .2: Terminal in 4inux
Introduction to Programming I 31
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
Introduction to Programming I 32
32
Step <2 Sa)e your =a)a Program
.e )ill sa!e our *rogram on a -ile named R#ello.Da!aRB and )e )ill %e sa!ing it inside a
-older named (EJVP"&@"('.
To o*en t$e Sa)e dialog %o6B clic: on t$e File menu -ound on t$e menu%ar and t$en
clic: on 'a!e.
-ter doing t$e *rocedure descri%ed a%o!eB a dialog %o6 )ill a**ear as s$o)n in Figure
%elo).
Figure .%: Sa$e 3s 1ialog
Introduction to Programming I 33
33
1lic: on t$e %ro)se %uttonB and t$en clic: on t$e 1reate Folder %utton.
Introduction to Programming I 30
30
+ame t$e ne) -older (EJVP"&@"('. +o)B clic: on t$e (EJP"&@"(' -older in
order to get inside t$at -older. Eou )ill see a similar -igure as s$o)n %elo) a-ter you
clic:ed on (EJVP"&@"('. T$e -older s$ould %e em*ty -or no) since itFs a ne)ly
created -older and )e $a!enFt sa!ed anyt$ing in it yet.
+o)B in t$e 'election te6t%o6B ty*e in t$e -ilename o- your *rogramB )$ic$ is
R#ello.Da!aRB and t$en clic: on t$e 'VE %utton.
Introduction to Programming I 3,
3,
+o) t$at youF!e sa!ed your -ileB notice $o) t$e title o- t$e -rame c$anges -rom R3ntitled
Document 1 4modi-ied9 L geditR to R#ello.Da!a 4W8(EJVP"&@"('9 I geditR. Ta:e
note t$at i- you )ant to ma:e c$anges in your -ileB you can Dust edit itB and t$en sa!e it
again %y clic:ing on File IV 'a!e.
Figure .+: "ew 5indow 3fter Sa$ing
Introduction to Programming I 36
36
Step 42 "ompi&ing your program
+o)B t$e ne6t ste* is to com*ile your *rogram. @o to t$e Terminal )indo) )e Dust
o*ened a )$ile ago.
Ty*icallyB )$en you o*en t$e terminal )indo)B 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 -olderB ty*e &s and
t$en *ress E+TE". .$at you )ill see is a list o- -iles and -olders inside your $ome -older.
+o)B you can see $ere t$at t$ere is a -older named R(EJVP"&@"('R )$ic$ )e $a!e
created a )$ile agoB and )$ere )e sa!ed our #ello.Da!a *rogram. +o) letFs go inside
t$at directory.
To go inside a directoryB you ty*e in t$e command; cd @directory nameA, T$e RcdR
command stands -orB c$ange directory. In t$is caseB since t$e name o- our directory is
(EJVP"&@"('B you ty*e in; cd MB=A*APRO?RAMS
Figure .*: Changing the 1irectory
Introduction to Programming I 3H
3H
&nce inside t$e -older )$ere your Ja!a *rograms areB let us no) start com*iling your
Ja!a *rogram. Ta:e note t$atB 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$atB e6ecute t$e RlsR command again to see i- your -ile
is inside t$at -older.
Figure ./: 4ist of Files 6nside the "ew 1irectory
Introduction to Programming I 37
37
To com*ile a Ja!a *rogramB )e ty*e in t$e command; Ca)ac @#i&enameA. 'o in t$is
caseB ty*e in; Ca)ac e&&o,Ca)a,
Figure .0: Compiling 2a$a File
During com*ilationB Da!ac adds a -ile to t$e dis: called @#i&enameA,c&ass> or in t$is caseB
e&&o,c&assB )$ic$ is t$e actual %ytecode.
Introduction to Programming I 3<
3<
Step 82 Running the Program
+o)B assuming t$at t$ere are no *ro%lems during com*ilation 4)eFll e6*lore more o- t$e
*ro%lems encountered during com*ilation in t$e ne6t section9B )e are no) ready to run
your *rogram.
To run your Ja!a *rogramB ty*e in t$e command; Ca)a @#i&ename !ithout the
extensionAB so in t$e case o- our e6am*leB ty*e in; Ca)a e&&o
Eou can see on t$e screen t$at you $a!e Dust run your -irst Ja!a *rogram t$at *rints t$e
messageB R#ello )orldJR.
Figure .7: 8unning Class File
Introduction to Programming I 00
00
3.%.1 0rrors
.$at )eF!e s$o)n so -ar is a Ja!a *rogram )$erein )e didnFt encounter any *ro%lems in
com*iling and running. #o)e!erB t$is is not al)ays t$e case. s )$at )e $a!e discussed
in t$e -irst *art o- t$is courseB )e usually encounter errors along t$e )ay.
s discussed %e-oreB t$ere are t)o ty*es o- errors. T$e -irst one is a com*ileItime error
or also called as synta6 error. T$e second one is t$e runtime error.
-,<,+,+ Syntax Errors
'ynta6 errors are usually ty*ing errors. Eou may $a!e miss*elled a command in Ja!a or
-orgot to )rite a semiIcolon 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!erB t$e *ro%lem may not %e at t$e e6act *oint.
&t$er common mista:es are in ca*itali>ationB s*ellingB t$e use o- incorrect s*ecial
c$aractersB and omission o- correct *unctuation.
=etFs ta:e -or e6am*leB our #ello.Da!a *rogram )$erein )e intentionally omit t$e
semicolon at one statement and )e try to ty*e t$e incorrect s*elling o- a command.
Figure .1&: Source Code 5ith Errors
Introduction to Programming I 01
01
'ee t$e error messages generated a-ter com*iling t$e *rogram. T$e -irst error message
suggests t$at t$ere is an error in line 6 o- your *rogram. It *ointed to t$e ne6t )ord
a-ter t$e statictB )$ic$ s$ould %e s*elled as static.
T$e second error message suggests t$at t$ere is a missing semicolon a-ter your
statement.
Figure .11: Compiling the Source Code with Errors
s a rule o- t$um%B i- you encounter a lot o- error messagesB try to correct t$e -irst
mista:e in a long listB and try to com*ile t$e *rogram again. Doing so may reduce t$e
total num%er o- errors dramatically.
-,<,+,. Run3time Errors
"unItime errors are errors t$at )ill not dis*lay until you run or e6ecute 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.
Introduction to Programming I 02
02
3.* :sing 1etBeans
+o) t$at )eF!e tried doing our *rograms t$e com*licated )ayB letFs no) see $o) to do
all t$e *rocesses )eF!e descri%ed in t$e *re!ious sections %y using Dust one a**lication.
In t$is *art o- t$e lessonB )e )ill %e using /et0eansB )$ic$ is an Integrated
$e)e&opment En)ironment or I$E. n IDE is a *rogramming en!ironment integrated
into a so-t)are a**lication t$at *ro!ides a @3I %uilderB a te6t or code editorB a com*iler
and8or inter*reter and a de%ugger.
Step +2 Run /et0eans
T$ere are t)o )ays to run +etBeans. &ne is t$roug$ commandIline using terminalB or %y
Dst clic:ing on t$e s$ortcut %utton -ound on t$e des:to*.
To run +etBeans using commandIline. &*en terminal 4see ste*s on $o) to run terminal
in t$e *re!ious discussion9B and ty*e; netbeans
Figure .12: 8unning "et9eans with the Command:4ine
Introduction to Programming I 03
03
T$e second )ay to run +etBeansB is %y clic:ing on t$e s$ortcut icon -ound on your
Des:to*.
Figure .1: 8unning "et9eans using shortcut icon on des;top
Introduction to Programming I 00
00
-ter youF!e o*en +etBeans IDEB you )ill see a gra*$ical user inter-ace 4@3I9 similar to
)$at is s$o)n %elo).
Figure .1%: 5indow 3fter -penning "et9eans
Introduction to Programming I 0,
0,
Step .2 Ma%e a proCect
+o)B letFs -irst ma:e a *roDect. 1lic: on FileIV +e) ProDect. -ter doing t$isB a +e)
ProDect dialog )ill a**ear. +o) clic: on Ja!a **lication and clic: on t$e +E/T %utton.
Figure .1+: Choosing )ro<ect Type
Introduction to Programming I 06
06
+o)B a +e) **lication dialog )ill a**ear.
Figure .1*: Setting the )ro<ect 6nformation
Introduction to Programming I 0H
0H
+o) try to c$ange t$e **lication =ocationB %y clic:ing on t$e B"&.'E %utton.
ProDect =ocation dialog )ill t$en a**ear. Dou%leIclic: 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%leIclic: on t$e
(EJVP"&@"(' -older and clic: on t$e &PE+ %utton.
Introduction to Programming I 07
07
'ee no) t$at t$e ProDect =ocation and ProDect Folder is c$anged to
8$ome8-lorence8(EJVP"&@"('.
FinallyB on t$e 1reate (ain 1lass te6t-ieldB ty*e in #ello as t$e main classF nameB and
t$en clic: on t$e FI+I'# %utton.
Figure .10: 5indow after Setting the )ro<ect 4ocation to =>23?3)8-@83=SASetting the =ain Class of the
)ro<ect to !ello
Introduction to Programming I 0<
0<
Step -2 Type in your program
Be-ore ty*ing in your *rogramB let us -irst descri%e t$e main )indo) a-ter creating t$e
*roDect.
s s$o)n %elo)B +etBeans automatically creates t$e %asic code -or your Ja!a *rogram.
Eou can Dust add your o)n statements to t$e generated code. &n t$e le-t side o- t$e
)indo)B you can see a list o- -olders and -iles t$at +etBeans generated a-ter creating t$e
*roDect. T$is can all %e -ound in your (EJVP"&@"(' -olderB )$ere you set t$e
ProDect location.
Figure .17: ?iew of the Created )ro<ect
Introduction to Programming I ,0
,0
+o)B try to modi-y t$e code generated %y +etBeans. Ignore t$e ot$er *arts o- t$e
*rogram -or no)B as )e )ill e6*lain t$e details o- t$e code later. Insert t$e code;
System.out.println("Hello #orld$"%
a-ter t$e statementB 88T&D& code a**lication logic $ere.
Figure .2&: 6nserting the Code
Introduction to Programming I ,1
,1
Step <2 "ompi&e your program
+o)B to com*ile your *rogramB Dust clic: on Build IV Build (ain ProDect. &rB you could
also use t$e s$ortcut %utton to com*ile your code.
Introduction to Programming I ,2
,2
I- t$ere are no errors in your *rogramB you )ill see a %uild success-ul message on t$e
out*ut )indo).
Figure .21: ?iew after a Successful Compilation
Introduction to Programming I ,3
,3
Step 42 Run your program
To run your *rogramB clic: on "unIV "un (ain ProDect. &r you could also use t$e
s$ortcut %utton to run your *rogram.
Figure .22: 8unning with "et9eans
Introduction to Programming I ,0
,0
T$e out*ut o- your *rogram is dis*layed in t$e out*ut )indo).
Figure .2: ?iew after a Successful 8un
Introduction to Programming I ,,
,,
3.2 0-ercises
3.2.1 ello 'orld;
3sing +etBeansB create a class named; XEour+ameY. T$e *rogram s$ould out*ut on t$e
screen;
'elcome to (ava )rogramming [*our+ame]$$$
3.2.2 +(e +ree
3sing +etBeansB 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 pressed
/gainst t!e 0art!1s s#eet flo#ing breast.
Introduction to Programming I ,6
,6
< Programming Fundamenta&s
%.1 Objectives
In t$is sectionB )e )ill %e discussing t$e %asic *arts o- a Ja!a *rogram. .e )ill start %y
trying to e6*lain t$e %asic *arts o- t$e #ello.Da!a *rogram introduced in t$e *re!ious
section. .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 lessonB 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 literalsB *rimiti!e data ty*esB !aria%le ty*es Bidenti-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)B )eFll 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 screen
System.out.println("Hello #orld$"%
&
&
T$e -irst line o- t$e codeB
public class Hello
indicates t$e name o- t$e class )$ic$ is e&&o, In Ja!aB all code s$ould %e *laced inside
a class declaration. .e do t$is %y using t$e c&ass :ey)ord. In additionB t$e class uses an
access specifier pub&ic> )$ic$ indicates t$at our class in accessi%le to ot$er classes -rom
ot$er *ac:ages 4*ac:ages are a collection o- classes9. .e )ill %e co!ering *ac:ages and
access s*eci-iers later.
T$e ne6t line )$ic$ contains a curly %race Z indicates t$e start o- a %loc:. In t$is codeB
)e *laced t$e curly %race at t$e ne6t line a-ter t$e class declarationB $o)e!erB )e can
also *lace t$is ne6t to t$e -irst line o- our code. 'oB )e could actually )rite our code as;
public class Hello
Z
or
public class Hello {
Introduction to Programming I ,H
,H
T$e ne6t t$ree lines indicates a Ja!a comment. comment is somet$ing used to
document a *art o- a code. It is not *art o- t$e *rogram itsel-B %ut used -or
documentation *ur*oses. It is good *rogramming *ractice to add comments to your
code.
/**
* My first java program
U8
comment is indicated %y t$e delimiters P5DQ and PD5Q. nyt$ing )it$in t$ese delimiters
are ignored %y t$e Ja!a com*ilerB and are treated as comments.
T$e ne6t lineB
public static void main(String[] args {
or can also %e )ritten asB
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$od
is t$e starting *oint o- a Ja!a *rogram. ll *rograms e6ce*t **lets )ritten in Ja!a start
)it$ t$e main met$od. (a:e sure to -ollo) t$e e6act signature.
T$e ne6t line is also a Ja!a commentB
//prints t!e string "Hello #orld" on screen
+o)B )e learned t)o )ays o- creating comments. T$e -irst one is %y *lacing t$e
comment inside 8U and U8B and t$e ot$er one is %y )riting 88 at t$e start o- t$e
comment.
T$e ne6t lineB
System.out.println("Hello #orld$"%
*rints t$e te6t P#ello .orldJQ on screen. T$e command 'ystem.out.*rintln49B *rints t$e
te6t 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$od
and c&ass res*ecti!ely.
Coding
<uidelines.
1. >our 2a$a programs should always end with the .java
extension.
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.
Introduction to Programming I ,7
,7
%.3 7ava Comments
1omments are notes )ritten to a code -or documentation *ur*oses. T$ose te6t 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; 1KKIstyle single line commentsB 1Istyle
multiline comments and s*ecial Da!adoc comments.
%.3.1 C>>"St#le Comments
1KK 'tyle comments starts )it$ 88. ll t$e te6t a-ter 88 are treated as comments. For
e6am*leB
// 2!is is a 344 style or single line comments
%.3.2 C"St#le Comments
1Istyle comments or also called multiline comments starts )it$ a 8U and ends )it$ a U8.
ll te6t in %et)een t$e t)o delimeters are treated as comments. 3nli:e 1KK style
commentsB it can s*an multi*le lines. For e6am*leB
/* t!is is an e5maple of a
3 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. Eou can create Da!adoc comments %y starting t$e line )it$ 8UU and ending it
)it$ U8. =i:e 1Istyle commentsB it can also s*an lines. It can also contain certain tags to
add more in-ormation to your comments. For e6am*leB
/**
2!is is an e5ample of special java doc comments used for 6n
generating an !tml documentation. ,t uses tags li-e7
8aut!or 9lorence :alagtas
8version ;.<
*/
Introduction to Programming I ,<
,<
%.% 7ava Statements and bloc8s
statement is one or more lines o- code terminated %y a semicolon. n e6am*le o- a
single statement isB
System.out.println4P#ello )orldQ9[
b&oc% is one or more statements %ounded %y an o*ening and closing curly %races t$at
grou*s t$e statements as one unit. Bloc: statements can %e nested inde-initely. ny
amount o- )$ite s*ace is allo)ed. n e6am*le o- a %loc: isB
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 the
statementB li;e for exampleB
public static $oid main, StringCD args .E
or you can place the curly brace on the next lineB
li;eB public static $oid main, StringCD args .
E
2. >ou should indent the next statements after the start of a bloc;Bfor
exampleB public static $oid main, StringCD args .E
System.out.println,F!elloF.G
System.out.println,FworldF.G
H
Introduction to Programming I 60
60
%.* 7ava Identifiers
Identi-iers are to:ens t$at re*resent names o- !aria%lesB met$odsB classesB etc. E6am*les
o- identi-iers are; #elloB mainB 'ystemB out.
Ja!a identi-iers are c a s e I s e n s iti ! e . T$is means t$at t$e identi-ier; e&&o is not t$e same
as he&&o. Identi-iers must %egin )it$ eit$er a letterB an underscore PCQB or a dollar sign
P\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 classB *u%licB !oidB etc. .e )ill discuss more
a%out Ja!a :ey)ords later.
Coding
<uidelines.
1. For names of classesB capitaliIe the first letter of the class name. For names
of methods and $ariablesB the first letter of the word should start with a small
letter.For example:
+hisIs/n0xampleOfClass1ame
thisIs/n0xampleOfMethod1ame
2. 6n case of multi:word identifiersB use capital letters to indicate the start of the
word 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.
Introduction to Programming I 61
61
%.2 7ava ?e#!ords
Aey)ords are *rede-ined identi-iers reser!ed %y Ja!a -or a s*eci-ic *ur*ose. Eou cannot
use :ey)ords as names -or your !aria%lesB classesB met$ods ]etc. #ere is a list o- t$e
Ja!a Aey)ords.
Figure %.1: 2a$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 trueB falseB and null are not :ey)ords %ut t$ey are reser!ed )ordsB so you
cannot use t$em as names in your *rograms eit$er
Introduction to Programming I 62
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 =iteralsB FloatingIPoint =iteralsB Boolean =iteralsB 1$aracter =iterals and
'tring =iterals.
%.6.1 Integer &iterals
Integer literals come in di--erent -ormats; decima& 4%ase 109B hexadecima& 4%ase 169B
and octa& 4%ase 79. In using integer literals in our *rogramB )e $a!e to -ollo) some
s*ecial notations.
For decimal num%ersB )e $a!e no s*ecial notations. .e Dust )rite a decimal num%er as it
is. For $e6adecimal num%ersB it s$ould %e *receeded %y P06Q or P0/Q. For octalsB t$ey are
*receeded %y P0Q.
For e6am*leB consider t$e num%er +.. ItFs decimal re*resentation is +.B )$ile in
$e6adecimalB it is 9x"B and in octalB it is e?ui!alent to 9+<.
Integer literals de-ault to t$e data ty*e int. n int is a signed 32I%it !alue. In some
casesB you may )is$ to -orce integer literal to t$e data ty*e &ong %y a**ending t$e PlQ or
P=Q c$aracter. long is a signed 60I%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 e6am*le is 3.101,.
Floating *oint literals can %e e6*ressed in standard or scienti-ic notations. For e6am*leB
,73.0, is in standard notationB )$ile ,.730,e2 is in scienti-ic notation.
Floating *oint literals de-ault to t$e data ty*e doub&e )$ic$ is a 60I%it !alue. To use a
smaller *recision 432I%it9 #&oatB Dust a**end t$e P-Q or PFQ c$aracter.
%.6.3 Boolean &iterals
Boolean literals $a!e only t)o !aluesB true or #a&se.
Introduction to Programming I 63
63
%.6.% C(aracter &iterals
1$aracter =iterals re*resent single 3nicode c$aracters. 3nicode c$aracter is a 16I%it
c$aracter set t$at re*laces t$e 7I%it '1II c$aracter set. 3nicode allo)s t$e inclusion o-
sym%ols and s*ecial c$aracters -rom ot$er languages.
To use a c$aracter literalB enclose t$e c$aracter in single ?uote delimiters. For e6am*leB
t$e letter aB is re*resented as EaF.
To use s*ecial c$aracters suc$ as a ne)line c$aracterB a %ac:slas$ is used -ollo)ed %y
t$e c$aracter code. For e6am*leB ^_n` -or t$e ne)line c$aracterB ^_r` -or t$e carriage
returnB ^_%` -or %ac:s*ace.
%.6.* String &iterals
'tring literals re*resent multi*le c$aracters and are enclosed %y dou%le ?uotes. n
e6am*le o- a string literal isB Ge&&o 'or&dH,
Introduction to Programming I 60
60
%.@ $rimitive data t#pes
T$e Ja!a *rogramming language de-ines eig$t *rimiti!e data ty*es. T$e -ollo)ing areB
%oolean 4-or logical9B c$ar 4-or te6tual9B %yteB s$ortB intB long 4integral9B dou%le and -loat
4-loating *oint9.
%[email protected] &ogical " boolean
%oolean data ty*e re*resents t)o states; tru e and -a ls e . n e6am*le isB
boolean result = true%
T$e e6am*le s$o)n a%o!eB declares a !aria%le named resu&t as boo&ean ty*e and
assigns it a !alue o- true.
%[email protected] +e-tual A c(ar
c$aracter data ty*e 4c$ar9B re*resents a single 3nicode c$aracter. It must $a!e its
literal enclosed in single ?uotes4` `9. For e6am*leB
>a1 //2!e letter a
>6t1 /// tab
To re*resent s*ecial c$aracters li:e F 4single ?uotes9 or R 4dou%le ?uotes9B use t$e esca*e
c$aracter _. For e6am*leB
?\'? //for single @uotes
?\"? //for double @uotes
lt$oug$B 'tring is not a *rimiti!e data ty*e 4it is a 1lass9B )e )ill Dust introduce 'tring
in t$is section. 'tring re*resents a data ty*e t$at contains multi*le c$aracters. It is
not a primiti)e data type> it is a c&ass, It $as it`s literal enclosed in dou%le ?uotes4PQ9.
For e6am*leB
String message=AHello #orld$B
Introduction to Programming I 6,
6,
%[email protected] Integral A b#te= s(ort= int B long
Integral data ty*es in Ja!a uses t$ree -orms L decimalB octal or $e6adecimal. E6am*les
areB
< //2!e decimal value <
CDD //2!e leading C indicates an octal value
C5:/33 //2!e leading C5 indicates a !e5adecimal value
Integral ty*es $as i n t as de-ault data ty*e. Eou can de-ine its l o n g !alue %y a**ending
t$e letter l or =. Integral data ty*e $a!e t$e -ollo)ing ranges;
Integer
&engt(
1ame or +#pe 4ange
7 %its %yte I2
H
to 2
H
I1
16 %its s$ort I2
1,
to 2
1,
I1
32 %its int I2
31
to 2
31
I1
60 %its long I2
63
to 2
63
I1
Table 0: 6ntegral types and their ranges
Coding <uidelines.
6n defining a long $alueB a lowercase 4 is not recommended because it is hard to
distinguish from the digit 1.
Introduction to Programming I 66
66
%.@.% 9loating $oint A float and double
Floating *oint ty*es $as do u %l e as de-ault data ty*e. FloatingI*oint literal includes eit$er
a decimal *oint or one o- t$e -ollo)ingB
0 or e //(add e5ponential value
9 or f //(float
E or d //(double
E6am*les areB
F.;G /// simple floatingHpoint value (a double
I.C<0<F /// large floatingHpoint value
<.D;J9 /// simple float siKe value
;<F.G04FCIE /// large double value #it! redundant E
In t$e e6am*le s$o)n a%o!eB t$e 23 a-ter t$e E in t$e second e6am*le is im*licitly
*ositi!e. T$at e6am*le is e?ui!alent to 6.02EK23. FloatingI*oint data ty*es $a!e t$e
-ollo)ing ranges;
9loat &engt( 1ame or +#pe 4ange
32 %its -loat I2
31
to 2
31
I1
60 %its dou%le I2
63
to 2
63
I1
Table 7: Floating point types and their ranges
Introduction to Programming I 6H
6H
%.C Dariables
)ariab&e is an item o- data used to store state o- o%Dects.
!aria%le $as a data type and a name. T$e data type indicates t$e ty*e o- !alue t$at
t$e !aria%le can $old. T$e )ariab&e name must -ollo) rules -or identi-iers.
%.C.1 ,eclaring and InitialiEing Dariables
To declare a !aria%le is as -ollo)sB
<data type> <name> [=initial value];
/ote2 Values enclosed in aV are re?uired !aluesB )$ile t$ose !alues enclosed in XY are
o*tional.
#ere is a sam*le *rogram t$at declares and initiali>es some !aria%lesB
public class LariableSamples
{
public static void main( String[] args {
//declare a data type #it! variable name
// result and boolean data type
boolean result%
//declare a data type #it! variable name
// option and char data type
c!ar option%
option = ?3?% //assign ?3? to option
//declare a data type #it! variable name
//grade, double data type and initialiKed
//to C.C
double 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 some
random letters you choose.
. 1eclare one $ariable per line of code. For exampleB the $ariable
declarationsB double exam'&G
double #uiI'1&G
double grade ' &G
is preferred o$er the declarationB
double exam'&B #uiI'1&B grade'&G
Introduction to Programming I 67
67
%.C.2 Outputting Dariable ,ata
In order to out*ut t$e !alue o- a certain !aria%leB )e can use t$e -ollo)ing commandsB
System.out.println(
System.out.print(
#ereFs a sam*le *rogramB
public class MutputLariable
{
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 te6t on screenB
;C
2!e value of 5=/
%.C.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*utB
)$ile t$e latter doesnFt.
1onsider t$e statementsB
System.out.print("Hello "%
System.out.print("#orld$"%
T$ese statements )ill out*ut t$e -ollo)ing on t$e screenB
Hello #orld$
+o) consider t$e -ollo)ing statementsB
System.out.println("Hello "%
System.out.println("#orld$"%
T$ese statements )ill out*ut t$e -ollo)ing on t$e screenB
Hello
#orld$
Introduction to Programming I 6<
6<
%.C.% 4eference Dariables vs. $rimitive
Dariables
.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$e
actual 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 classB you are actually declaring a re-erence !aria%le to t$e o%Dect
)it$ t$at certain class.
For e6am*leB su**ose )e $a!e t)o !aria%les )it$ data ty*es int and 'tring.
int num = ;C%
String name = "Hello"
'u**oseB t$e illustration s$o)n %elo) is t$e actual memory o- your com*uterB )$erein
you $a!e t$e address o- t$e memory cellsB t$e !aria%le name and t$e data t$ey $old.
Memor#
/ddress
Dariable
1ame
,ata
1001 num 10
; ;
1,63 name ddress420009
; ;
;
;
2000 R#elloR
s you can seeB -or t$e *rimiti!e !aria%le numB t$e data is on t$e actual location o-
)$ere t$e !aria%le is. For t$e re-erence !aria%le nameB t$e !aria%le Dust $olds t$e
address o- )$ere t$e actual data is.
Introduction to Programming I H0
H0
%.15 Operators
In Ja!aB t$ere are di--erent ty*es o- o*erators. T$ere are arit$metic o*eratorsB relational
o*eratorsB 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 case
multi*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 *rogramsB
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
T o*1 T o*2
1om*utes t$e remainder o- di!iding
o*1 %y o*2
I o*1 I o*2 'u%tracts o*2 -rom o*1
Table 1&: 3rithmetic operations and their functions
Introduction to Programming I H1
H1
#ereFs 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# numbers
int 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 numbers
System.out.println("/dding..."%
System.out.println(" i 4 j = " 4 (i 4 j%
System.out.println(" 5 4 y = " 4 (5 4 y%
//subtracting numbers
System.out.println("Subtracting..."%
System.out.println(" i H j = " 4 (i H j%
System.out.println(" 5 H y = " 4 (5 H y%
//multiplying numbers
System.out.println("Multiplying..."%
System.out.println(" i * j = " 4 (i * j%
System.out.println(" 5 * y = " 4 (5 * y%
//dividing numbers
System.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 dividing
numbers
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("Mi5ing
types..."% System.out.println(" j 4 y = "
4 (j 4 y% System.out.println(" i * 5 = "
4 (i * 5%
&
&
Introduction to Programming I H2
H2
#ere is t$e out*ut o- t$e *rogramB
Lariable values...
i = FD
j = G<
5 = <D.GDN
y = D.<<
/dding...
i 4 j = DP
5 4 y = FG.IPN
Subtracting...
i H j = HN
5 H y = <C.<NN
Multiplying...
i * j = ;NNG
5 * y = ;PJ.FD
Eividing...
i / j = C
5 / y = F.JCNG
3omputing t!e remainder...
i O j = FD
5 O y = N.J;N
Mi5ing types...
j 4 y = GP.<<
i * 5 = ;C;I.NJ
/ote2 .$en an integer and a -loatingI*oint num%er are used as o*erands to a single
arit$metic o*erationB t$e result is a -loating *oint. T$e integer is im*licitly con!erted to a
-loatingI*oint num%er %e-ore t$e o*eration ta:es *lace.
Introduction to Programming I H3
H3
%.15.2 Increment and ,ecrement operators
side -rom t$e %asic arit$metic o*eratorsB Ja!a also includes a unary increment o*erator
4KK9 and unary decrement o*erator 4II9. Increment and decrement o*erators increase
and decrease a !alue stored in a num%er !aria%le %y 1.
For e6am*leB t$e e6*ressionB
count = count 4 ;% //increment t!e value of count by ;
is e?ui!alent toB
count44%
Operator :se ,escription
KK o*KK
Increments 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
II o*II
Decrements o* %y 1[ e!aluates to t$e
!alue o- o* %e-ore it )as
decremented
II IIo*
Decrements o* %y 1[ e!aluates to t$e
!alue o- o* a-ter it )as decremented
Table 11: 6ncrement and 1ecrement 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*erandB it causes t$e !aria%le to %e incremented or decremented
%y 1B and t$en t$e ne) !alue is used in t$e e6*ression in )$ic$ it a**ears. For e6am*leB
int i = ;C.
int j = F%
int - = C%
- = ++ 4 i% //#ill result to - = G4;C = ;G
Introduction to Programming I H0
H0
.$en t$e increment and decrement o*erators are *laced a-ter t$e o*erandB t$e old !alue
o- t$e !aria%le )ill %e used in t$e e6*ression )$ere it a**ears. For e6am*leB
int i = ;C.
int j = F%
int - = C%
- = j44 4 i% //#ill result to - = F4;C = ;F
Coding <uideline.
3lways ;eep expressions containing increment and decrement operators simple
and easy to understand.
Introduction to Programming I H,
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
V o*1 V o*2 o*1 is greater t$an o*2
VS o*1 VS o*2 o*1 is greater t$an or e?ual to o*2
a o*1 a o*2 o*1 is less t$an o*2
aS o*1 aS 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
JS o*1 JS o*2 o*1 and o*2 are not e?ual
Table 12: 8elational -perators
Introduction to Programming I H6
H6
#ereFs a sam*le *rogram t$at uses relational o*eratorsB
public class QelationalEemo
{
public static void main(String[] args {
//a fe# numbers
int 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!an
System.out.println("Rreater t!an..."%
System.out.println(" i S j = " 4 (i S j% //false
System.out.println(" j S i = " 4 (j S i% //true
System.out.println(" - S j = " 4 (- S j% //false
//greater t!an or e@ual to
System.out.println("Rreater t!an or e@ual to..."%
System.out.println(" i S= j = " 4 (i S= j% //false
System.out.println(" j S= i = " 4 (j S= i% //true
System.out.println(" - S= j = " 4 (- S= j% //true
//less t!an
System.out.println("Tess t!an..."%
System.out.println(" i U j = " 4 (i U j% //true
System.out.println(" j U i = " 4 (j U i% //false
System.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% //true
System.out.println(" j U= i = " 4 (j U= i% //false
System.out.println(" - U= j = " 4 (- U= j% //true
//e@ual to
System.out.println("0@ual to..."%
System.out.println(" i == j = " 4 (i == j% //false
System.out.println(" - == j = " 4 (- == j% //true
//not e@ual to
System.out.println("+ot e@ual to..."%
System.out.println(" i $= j = " 4 (i $= j% //true
System.out.println(" - $= j = " 4 (- $= j% //false
&
&
Introduction to Programming I HH
HH
#ereFs t$e out*ut -rom t$is *rogram;
Lariable values...
i = FD
j = G<
- = G<
Rreater t!an...
i S j = false
j S i = true
- S j = false
Rreater t!an or e@ual to...
i S= j = false
j S= i = true
- S= j = true
Tess t!an...
i U j = true
j U i = false
- U j = false
Tess t!an or e@ual to...
i U= j = true
j U= i = false
- U= j = true
0@ual to...
i == j = false
- == j = true
+ot e@ual to...
i $= j = true
- $= j = false
Introduction to Programming I H7
H7
%.15.% &ogical operators
=ogical o*erators $a!e one or t)o %oolean o*erands t$at yield a %oolean result. T$ere
are si6 logical o*erators; MM 4logical +D9B M 4%oolean logical +D9B NN 4logical &"9B N
4%oolean logical inclusi!e &"9B O 4%oolean logical e6clusi!e &"9B and J 4logical +&T9.
T$e %asic e6*ression -or a logical o*eration isB
5; op 5<
)$ere 61B 62 can %e %oolean e6*ressionsB !aria%les or constantsB and o* is eit$er MMB MB
NNB N or O o*erator. T$e trut$ ta%les t$at )ill %e s$o)n ne6tB summari>e t$e result o-
eac$ o*eration -or all *ossi%le com%inations o- 61 and 62.
Introduction to Programming I H<
H<
<,+9,<,+ II 6&ogica& A/$7 and I 6boo&ean &ogica& A/$7
#ere is t$e trut$ ta%le -or MM and MB
-1 -2 4esult
T"3E T"3E T"3E
T"3E F='E F='E
F='E T"3E 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 short3circuit
e)a&uations 4or *artial e!aluations9B )$ile M doesnFt. .$at does t$is meanG
@i!en an e6*ressionB
e5p; VV e5p<
MM )ill e!aluate t$e e6*ression e6*1B and immediately return a -alse !alue is e6*1 is
-alse. I- e6*1 is -alseB t$e o*erator ne!er e!aluates e6*2 %ecause t$e result o- t$e
o*erator )ill %e -alse regardless o- t$e !alue o- e6*2. In contrastB t$e M o*erator al)ays
e!aluates %ot$ e6*1 and e6*2 %e-ore returning an ans)er.
#ereFs a sam*le source code t$at uses logical and %oolean +DB
public class 2est/+E
{
public static void main( String[] args {
int i = C%
int j = ;C%
boolean test= false%
//demonstrate VV
test = (i S ;C VV (j44 S P%
System.out.println(i%
System.out.println(j%
System.out.println(test%
//demonstrate V
test = (i S ;C V (j44 S P%
System.out.println(i%
System.out.println(j%
System.out.println(test%
&
&
Introduction to Programming I 70
70
T$e out*ut o- t$e *rogram isB
C
;C
false
C
;;
false
+oteB t$at t$e DKK on t$e line containing t$e MM o*erator is not e!aluated since t$e -irst
e6*ression 4iV109 is already e?ual to -alse.
Introduction to Programming I 71
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 NB
-1 -2 4esult
T"3E T"3E T"3E
T"3E F='E T"3E
F='E T"3E T"3E
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$ortIcircuit
e!aluations 4or *artial e!aluations9B )$ile N doesnFt. .$at does t$is meanG
@i!en an e6*ressionB
e5p; WW e5p<
NN )ill e!aluate t$e e6*ression e6*1B and immediately return a true !alue is e6*1 is true.
I- e6*1 is trueB t$e o*erator ne!er e!aluates e6*2 %ecause t$e result o- t$e o*erator )ill
%e true regardless o- t$e !alue o- e6*2. In contrastB t$e N o*erator al)ays e!aluates %ot$
e6*1 and e6*2 %e-ore returning an ans)er.
#ereFs a sam*le source code t$at uses logical and %oolean &"B
public class 2estMQ
{
public static void main( String[] args {
int i = C%
int j = ;C%
boolean test= false%
//demonstrate WW
test = (i U ;C WW (j44 S P%
System.out.println(i%
System.out.println(j%
System.out.println(test%
//demonstrate W
test = (i U ;C W (j44 S P%
System.out.println(i%
System.out.println(j%
System.out.println(test%
&
&
Introduction to Programming I 72
72
T$e out*ut o- t$e *rogram isB
C
;C
true
C
;;
true
+oteB t$at t$e DKK on t$e line containing t$e NN o*erator is not e!aluated since t$e -irst
e6*ression 4ia109 is already e?ual to true.
Introduction to Programming I 73
73
<,+9,<,- K 6boo&ean &ogica& exc&usi)e OR7
#ere is t$e trut$ ta%le -or OB
-1 -2 4esult
T"3E T"3E F='E
T"3E F='E T"3E
F='E T"3E T"3E
F='E F='E F='E
Table 1+: Truth table for O
T$e result o- an e6clusi!e &" o*eration is T"3EB i- and only i- one o*erand is true and
t$e ot$er is -alse. +ote t$at %ot$ o*erands must al)ays %e e!aluated in order to
calculate t$e result o- an e6clusi!e &".
#ereFs a sam*le source code t$at uses t$e logical e6clusi!e &" o*eratorB
public class 2estXMQ
{
public static void main( String[] args {
boolean val; = true% boolean
val< = 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 isB
false
true
false
true
Introduction to Programming I 70
70
<,+9,<,< L 6&ogica& /OT7
T$e logical +&T ta:es in one argumentB )$erein t$at argument can %e an e6*ressionB
!aria%le or constant. #ere is t$e trut$ ta%le -or JB
-1 4esult
T"3E F='E
F='E T"3E
Table 1*: Truth table for P
#ereFs a sam*le source code t$at uses t$e logical +&T o*eratorB
public class 2est+M2
{
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 isB
false
true
Introduction to Programming I 7,
7,
%.15.* Conditional Operator F).G
T$e conditional o*erator M2 is a ternary o*erator. T$is means t$at it ta:es in t$ree
arguments t$at toget$er -orm a conditional e6*ression. T$e structure o- an e6*ression
using a conditional o*erator isB
e5p;Ze5p<7e5pF
)$erein e6*1 is a %oolean e6*ression )$ose result must eit$er %e true or -alse.
I- e6*1 is trueB e6*2 is t$e !alue returned. I- it is -alseB t$en e6*3 is returned.
For e6am*leB gi!en t$e codeB
public class 3onditionalMperator
{
public static void main( String[] args {
String status = ""%
int grade = JC%
//get status of t!e student
status = (grade S= IC!")assed"""9ail"%
//print status
System.out.println( status %
&
&
T$e out*ut o- t$is *rogram )ill %eB
)assed
Introduction to Programming I 76
76
#ere is t$e -lo)c$art o- $o) G; )or:sB
Figure %.2: Flowchart using the (: operator
#ere is anot$er *rogram t$at uses t$e G; o*eratorB
class 3onditionalMperator
{
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 isB
Score = ;C
Introduction to Programming I 7H
7H
%.15.2 Operator $recedence
&*erator *recedence de-ines t$e com*iler`s order o- e!aluation o- o*erators so as to
come u* )it$ an unam%iguous result.
Figure %.: -perator )recedence
@i!en a com*licated e6*ressionB
IO<*N4G/<4JJH;C
)e can reI)rite t$e e6*ression and *lace some *arent$esis %ase on o*erator *recedenceB
((IO<*N4(G/<4JJH;C%
Coding <uidelines
To a$oid confusion in e$aluating mathematical operationsB ;eep your expressions
simple and use parenthesis.
Introduction to Programming I 77
77
%.11 0-ercises
%.11.1 ,eclaring and printing variables
@i!en t$e ta%le %elo)B declare t$e -ollo)ing !aria%les )it$ t$e corres*onding data ty*es
and 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 e6*ected screen out*utB
+umber = ;C
letter = a
result = true
str = !ello
%.11.2 <etting t(e average of t(ree numbers
1reate a *rogram t$at out*uts t$e a!erage o- t$ree num%ers. =et t$e !alues o- t$e t$ree
num%ers %eB 10B 20 and 0,. T$e e6*ected screen out*ut isB
number ; = ;C
number < = <C
number F = GN
/verage is = <N
%.11.3 Output greatest value
@i!en t$ree num%ersB )rite a *rogram t$at out*uts t$e num%er )it$ t$e greatest !alue
among t$e t$ree. 3se t$e conditional G; o*erator t$at )e $a!e studied so -ar 4I/T; Eou
)ill need to use t)o sets o- M2 to sol!e t$is9. For e6am*leB gi!en t$e num%ers 10B 23 and
,B your *rogram s$ould out*utB
number ; = ;C
number < = <F
number F = N
2!e !ig!est number is = <F
%.11.% Operator precedence
@i!en t$e -ollo)ing e6*ressionsB reI)rite t$em %y )riting some *arent$esis %ased on t$e
se?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 0 O 2 O 2
3. r O s U t 8 u L ! K ) O 6 L yKK
Introduction to Programming I 7<
7<
4 ?etting Input #rom the Neyboard
*.1 Objectives
+o) t$at )eF!e studied some %asic conce*ts in Ja!a and )eF!e )ritten some sim*le
*rogramsB letFs ma:e our *rograms more interacti!e %y getting some in*ut -rom t$e
user. In t$is sectionB )eFll %e discussing t)o met$ods o- getting in*utB t$e -irst one is
t$roug$ t$e use o- t$e Bu--ered"eader class and t$e ot$er one in!ol!es a gra*$ical user
inter-ace %y using J&*tionPane.
t t$e end o- t$e lessonB t$e student s$ould %e a%le to;
1reate an interacti!e Ja!a *rogram t$at gets in*ut -rom t$e :ey%oard
3se t$e Bu--ered"eader class to get in*ut -rom t$e :ey%oard using a console
3se 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 get
input
In t$is sectionB )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 Da!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*utB and in!o:e t$e read=ine49
met$od to get in*ut -rom t$e :ey%oard. Eou $a!e to ty*e it inside a tryIcatc$ %loc:.
try{
String temp = data,n.readTine(%
&
catc!( ,M05ception e {
System.out.println(A0rror in getting inputB%
&
Introduction to Programming I <0
<0
#ere is t$e com*lete source code;
import java.io.:ufferedQeader%
import java.io.,nputStreamQeader%
import java.io.,M05ception%
public class Ret,nput9rom[eyboard
{
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) letFs try to e6*lain eac$ line o- code;
T$e statementsB
import java.io.:ufferedQeader%
import java.io.,nputStreamQeader%
import java.io.,M05ception%
indicate t$at )e )ant to use t$e classes #u$$ered%eaderB &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 in
your *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 e6am*leB t$e
ava*io *ac:age contains classes t$at allo) *rograms to in*ut and out*ut data. T$e
statements can also %e re)ritten asB
import java.io.*%
)$ic$ )ill load all t$e classes -ound in t$e *ac:ageB and t$en )e can use t$ose classes
inside our *rogram.
T$e ne6t t)o statementsB
public class Ret,nput9rom[eyboard
{
public static void main( String[] args {
)ere already discussed in t$e *re!ious lesson. T$is means )e declare a class named
Ret,nput9rom[eyboard and )e declare t$e main
met$od.
In t$e statementB
: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. DonFt
)orry a%out )$at t$e synta6 means -or no). .e )ill co!er more a%out t$is later in t$e
course.
+o)B )e are declaring a 'tring !aria%le )it$ t$e identi-ier nameB
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 an
em*ty 'tring RR. It is al)ays good to initiali>e your !aria%les as you declare t$em.
T$e ne6t line Dust out*uts a 'tring on t$e screen as:ing -or t$e userFs name.
System.out.print(")lease 0nter *our +ame7"%
+o)B t$e -ollo)ing %loc: de-ines a tryIcatc$ %loc:B
try{
name = data,n.readTine(%
&catc!( ,M05ception e
{ System.out.println("0rror$"
%
&
T$is assures t$at t$e *ossi%le e6ce*tions t$at could occur in t$e statement
name = data,n.readTine(%
)ill %e catc$ed. .e )ill co!er more a%out e6ce*tion $andling in t$e latter *art o- t$is
courseB %ut -or no)B Dust ta:e note t$at you need to add t$is code in order to use t$e
read=ine49 met$od o- Bu--ered"eader to get in*ut -rom t$e user.
+o) going %ac: to t$e statementB
name = data,n.readTine(%
t$e met$od callB data,n.readTine(B 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%leB )$ic$ )e )ill use in our -inal
statement to greet t$e userB
System.out.println("Hello " 4 name 4 "$"%
*.3 :sing 7Option$ane to get input
not$er )ay to get in*ut -rom t$e user is %y using t$e (Mption)ane class )$ic$ is
-ound in t$e java5.s#ing *ac:age. JMption)ane ma:es it easy to *o* u* a standard
dialog %o6 t$at *rom*ts users -or a !alue or in-orms t$em o- somet$ing.
@i!en t$e -ollo)ing codeB
import java5.s#ing.(Mption)ane%
public class Ret,nput9rom[eyboard
{
public static void main( String[] args {
String name = ""%
name = (option)ane.s!o#,nputEialog(")lease enter your
name"%
String msg = "Hello " 4 name 4 "$"%
(Mption)ane.s!o#MessageEialog(null. msg%
&
T$is )ill out*utB
&
Figure +.1: @etting 6nput Lsing 2-ption)ane
Figure +.2: 6nput florence on the 2-ption)ane
Figure +.: Showing =essage Lsing 2-ption)ane
T$e -irst statementB
import java5.s#ing.(Mption)ane%
indicates t$at )e )ant to im*ort t$e class (Mption)ane -rom t$e java5.s#ing
*ac:age. .e can also )rite t$is asB
import java5.s#ing.*%
T$e statementB
name = (Mption)ane.s!o#,nputEialog(")lease enter your name"%
creates a (Mption)ane in*ut dialogB )$ic$ )ill dis*lay a dialog )it$ a messageB a
te6t-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 messageB )$ic$ )e )ill store in t$e msg
!aria%leB
String msg = "Hello " 4 name 4 "$"%
T$e ne6t line dis*lays a dialog )$ic$ contains a message and an &A %utton.
(Mption)ane.s!o#MessageEialog(null. msg%
*.% 0-ercises
*.%.1 &ast 3 !ords FBuffered4eader versionG
3sing Bu--ered"eaderB as: -or t$ree )ords -rom t$e user and out*ut t$ose t$ree )ords
on t$e screen. For e6am*leB
0nter #ord;7Roodbye
0nter #ord<7and
0nter #ordF7Hello
Roodbye and Hello
*.%.2 &ast 3 !ords F7Option$ane versionG
3sing J&*tionPaneB as: -or t$ree )ords -rom t$e user and out*ut t$ose t$ree )ords on
t$e screen. For e6am*leB
Figure +.%: First 6nput
Figure +.+: Second 6nput
Figure +.*: Third 6nput
Figure +./: Show =essage
8 "ontro& Structures
2.1 Objectives
In t$e *re!ious sectionsB )e $a!e gi!en e6am*les o- se?uential *rogramsB )$erein
statements are e6ecuted one a-ter anot$er in a -i6ed order. In t$is sectionB )e )ill %e
discussing control structuresB )$ic$ allo)s us to c$ange t$e ordering o- $o) t$e
statements in our *rograms are e6ecuted.
t t$e end o- t$e lessonB t$e student s$ould %e a%le to;
3se decision control structures 4i-B elseB s)itc$9 )$ic$ allo)s selection o- s*eci-ic
sections o- code to %e e6ecuted
3se re*etition control structures 4)$ileB doI)$ileB -or9 )$ic$ allo) e6ecuting
s*eci-ic sections o- code a num%er o- times
3se %ranc$ing statements 4%rea:B continueB return9 )$ic$ allo)s redirection o-
*rogram -lo)
2.2 ,ecision Control Structures
Decision control structures are Ja!a statements t$at allo)s us to select and e6ecute
s*eci-ic %loc:s o- code )$ile s:i**ing ot$er sections.
2.2.1 if statement
T$e i-Istatement s*eci-ies t$at a statement 4or %loc: o- code9 )ill %e e6ecuted if and
only if a certain boolean statement is true.
T$e i-Istatement $as t$e -ormB
if( boolean\e5pression
statement%
or
if( boolean\e5pression {
statement;%
statement<%
. . .
&
)$ereB %ooleanCe6*ression is eit$er a %oolean e6*ression or %oolean !aria%le.
Figure *.1: Flowchart of 6f:Statement
if( grade S IC System.out.println("3ongratulations$"%
or
int grade = IJ%
if( grade S 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 true
or a false.
2. 6ndent the statements inside the if:bloc;.For
exampleB if, booleanJexpression .E
AAstatement1G
AAstatement2G
H
2.2.2 if"else statement
T$e i-Ielse statement is used )$en )e )ant to e6ecute a certain statement i- a condition
is trueB and a di--erent statement i- t$e condition is -alse.
T$e i-Ielse statement $as t$e -ormB
if( boolean\e5pression
statement%
else
statement%
or can also %e )ritten asB
if( boolean\e5pression {
statement;%
statement<%
. . .
&
else{
&
statement;%
statement<%
. . .
For e6am*leB gi!en t$e code sni**etB
int grade = IJ%
if( grade S IC System.out.println("3ongratulations$"%
else System.out.println("Sorry you failed"%
or
int grade = IJ%
if( grade S IC
{ System.out.println("3ongratulations$"
% System.out.println("*ou passed$"%
&
else{
&
System.out.println("Sorry you failed"%
Figure *.2: Flowchart of 6f:Else Statement
Coding <uidelines.
1. To a$oid confusionB always place the statement or statements of an if or if:else
bloc; inside brac;ets EH.
2. >ou can ha$e nested if:else bloc;s. This means that you can ha$e other if:else
bloc;s inside another if:else bloc;.For exampleB
if, booleanJexpression .E
if, booleanJexpression .E
. . .
H
H
elseE . . .
H
Introduction to Programming I 100
1001
2.2.3 if"else"if statement
T$e statement in t$e elseIclause o- an i-Ielse %loc: can %e anot$er i-Ielse structures.
T$is cascading o- structures allo)s us to ma:e more com*le6 selections.
T$e i-Ielse i- statement $as t$e -ormB
if( boolean\e5pression;
statement;%
else if( boolean\e5pression<
statement<%
else
statementF%
Ta:e note t$at you can $a!e many elseIi- %loc:s a-ter an i-Istatement. T$e elseI%loc: is
o*tional and can %e omitted. In t$e e6am*le s$o)n a%o!eB i- %ooleanCe6*ression1 is
trueB t$en t$e *rogram e6ecutes statement1 and s:i*s t$e ot$er statements. I-
%ooleanCe6*ression2 is trueB t$en t$e *rogram e6ecutes statement 2 and s:i*s to t$e
statements -ollo)ing statement3.
Figure *.: Flowchart of 6f:Else:6f Statement
For e6am*leB gi!en t$e code sni**etB
int grade = IJ%
if( grade S PC
{ System.out.println("Lery
good$"%
&
else if( grade S IC {
System.out.println("Lery good$"%
&
else{
&
System.out.println("Sorry you failed"%
2.2.% Common 0rrors !(en using t(e if"else statements.
1. T$e condition inside t$e i-Istatement does not e!aluate to a %oolean !alue. For
e6am*leB
//'QM+R
int number = C%
if( number {
//some statements !ere
&
T$e !aria%le num%er does not $old a Boolean !alue.
2. 3sing S instead o- SS -or com*arison. For e6am*leB
//'QM+R
int number = C%
if( number = C {
//some statements !ere
&
T$is s$ould %e )ritten asB
//3MQQ032
int number = C%
if( number == C {
//some statements !ere
&
3. .riting e&sei# instead o- e&se i#.
2.2.* 0-ample for if"else"else if
public class Rrade
{
public static void main( String[] args
{
double grade = P<.C%
if( grade S= PC {
System.out.println( "05cellent$" %
&
else if( (grade U PC VV (grade S= JC{
System.out.println("Rood job$" %
&
else if( (grade U JC VV (grade S= IC{
System.out.println("Study !arder$" %
&
else{
&
&
&
System.out.println("Sorry. you failed."%
2.2.2 s!itc( statement
not$er )ay to indicate a %ranc$ is t$roug$ t$e s!itch :ey)ord. T$e s)itc$ construct
allo)s %ranc$ing on multi*le outcomes.
T$e s)itc$ statement $as t$e -ormB
s#itc!( s#itc!\e5pression {
case case\selector;7
statement;% //
statement<% //bloc- ;
. . . //
brea-%
case case\selector<7
statement;% //
statement<% //bloc- <
. . . //
brea-%
. . .
default7
statement;% //
statement<% //bloc- n
. . . //
brea-%
&
)$ereB s)itc$Ce6*ression is an integer or character e6*ression andB caseCselector1B
caseCselector2 and so onB are uni?ue integer or c$aracter constants.
.$en a s)itc$ is encounteredB Ja!a -irst e!aluates t$e s)itc$Ce6*ressionB and Dum*s to
t$e case )$ose selector matc$es t$e !alue o- t$e e6*ression. T$e *rogram e6ecutes t$e
statements in order -rom t$at *oint on until a %rea: statement is encounteredB s:i**ing
t$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-iedB t$e de-ault %loc: is e6ecuted. Ta:e note $o)e!erB
t$at t$e de-ault *art is o*tional. s)itc$ statement can $a!e no de-ault %loc:.
/OTES2
3nli:e )it$ t$e i# statementB t$e multi*le statements are e6ecuted in t$e s)itc$
statement )it$out needing t$e curly %races.
.$en a case in a s)itc$ statement $as %een matc$edB all t$e statements associated
)it$ t$at case are e6ecuted. +ot only t$atB t$e statements associated )it$ t$e
succeeding cases are also e6ecuted.
To *re!ent t$e *rogram -rom e6ecuting statements in t$e su%se?uent casesB )e use a
brea% statement as our last statement.
Coding <uidelines.
1. 1eciding 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 single
integer or character $alue. 3lsoB the $alue pro$ided to each case statement must be
uni#ue.
Figure *.%: Flowchart of Switch Statements
2.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."%
2.3 4epetition Control Structures
"e*etition control structures are Ja!a statements t$at allo)s us to e6ecute s*eci-ic
%loc:s o- code a num%er o- times. T$ere are t$ree ty*es o- re*etition control structuresB
t$e )$ileB doI)$ile and -or loo*s.
2.3.1 !(ile loop
T$e )$ile loo* is a statement or %loc: o- statements t$at is re*eated as long as some
condition is satis-ied.
T$e )$ile statement $as t$e -ormB
#!ile( boolean\e5pression {
statement;%
statement<%
. . .
&
T$e statements inside t$e )$ile loo* are e6ecuted as long as t$e %ooleanCe6*ression
e!aluates to true.
For e6am*leB gi!en t$e code sni**etB
int i = G%
#!ile ( i S C {
System.out.print(i%
iHH%
&
T$e sam*le code s$o)n )ill *rint GF<; on t$e screen. Ta:e note t$at i- t$e line
containing t$e statement iHH% is remo!edB t$is )ill result to an in#inite &oopB or a
loo* t$at does not terminate. T$ere-oreB )$en using )$ile loo*s or any :ind o- re*etition
control structuresB ma:e sure t$at you add some statements t$at )ill allo) your loo* to
terminate at some *oint.
T$e -ollo)ing are ot$er e6am*les o- )$ile loo*sB
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%
2.3.2 do"!(ile loop
T$e doI)$ile loo* is similar to t$e )$ileIloo*. T$e statements inside a doI)$ile loo* are
e6ecuted se!eral times as long as t$e condition is satis-ied.
T$e main di--erence %et)een a )$ile and doI)$ile loo* is t$atB t$e statements inside a
doI)$ile loo* are e6ecuted at &east once,
T$e doI)$ile statement $as t$e -ormB
do{
statement;%
statement<%
. . .
&#!ile( boolean\e5pression %
T$e statements inside t$e doI)$ile loo* are -irst e6ecutedB and t$en t$e condition in t$e
%ooleanCe6*ression *art is e!aluated. I- t$is e!aluates to trueB t$e statements inside t$e
doI)$ile loo* are e6ecuted again.
#ere are a -e) e6am*les t$at uses t$e doI)$ile loo*;
Examp&e +2
int 5 = C%
do
{
System.out.println(5%
544%
&#!ile (5U;C%
T$is e6am*le )ill out*ut C;<FGNIDJP on t$e screen.
Examp&e .2
//infinite loop
do{
System.out.println(A!elloB%
& #!ile (true%
T$is e6am*le )ill result to an in-inite loo*B t$at *rints !ello on screen.
Examp&e -2
//one loop
// statement is e5ecuted once
do
System.out.println(A!elloB%
#!ile (false%
T$is e6am*le )ill out*ut !ello on t$e screen.
Coding <uidelines.
1. Common programming mista;es when using the do:while loop is forgetting to
write the semi:colon after the while expression.
doE
...
Hwhile,booleanJexpression. AA58-"@:Qforgot semicolon G
2. 2ust li;e in while loopsB ma;e sure that your do:while loops will terminate at
some point.
2.3.3 for loop
T$e -or loo*B li:e t$e *re!ious loo*sB allo)s e6ecution o- t$e same code a num%er o-
times.
T$e -or loo* $as t$e -ormB
for (,nitialiKation05pression% Toop3ondition% Step05pression{
statement;%
statement<%
. . .
&
)$ereB
InitialiEation0-pression Iinitiali>es t$e loo* !aria%le.
&oopCondition " com*ares t$e loo* !aria%le to some limit !alue.
Step0-pression I u*dates t$e loo* !aria%le.
sim*le e6am*le o- t$e -or loo* isB
int i%
for( i = C% i U ;C% i44 {
System.out.print(i%
&
In t$is e6am*leB t$e statement iS0B -irst initiali>es our !aria%le. -ter t$atB t$e condition
e6*ression ia10 is e!aluated. I- t$is e!aluates to trueB t$en t$e statement inside t$e -or
loo* is e6ecuted. +e6tB t$e e6*ression iKK is e6ecutedB and t$en t$e condition
e6*ression is again e!aluated. T$is goes on and onB until t$e condition e6*ression
e!aluates to -alse.
T$is e6am*leB is e?ui!alent to t$e )$ile loo* s$o)n %elo)B
int i = C%
#!ile( i U ;C {
System.out.print(i%
i44%
&
Introduction to Programming I 110
1101
2.% Branc(ing Statements
Branc$ing statements allo)s us to redirect t$e -lo) o- *rogram e6ecution. Ja!a o--ers
t$ree %ranc$ing statements; %rea:B continue and return.
2.%.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$ statementB and -lo) o- control
trans-ers to t$e statement immediately -ollo)ing t$e s)itc$. Eou can also use t$e
unla%eled -orm o- t$e brea- statement to terminate a -orB )$ileB or doI)$ile loo*.
For e6am*leB
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 e6am*leB i- t$e searc$ string RE>aR is -oundB t$e -or loo* )ill sto* and -lo) o-
control trans-ers to t$e statement -ollo)ing t$e -or loo*.
8,<,+,. Labe&ed brea% statement
T$e la%eled -orm o- a %rea: statement terminates an outer statementB )$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)oIdimensional array. T)o nested -or loo*s tra!erse t$e array. .$en t$e !alue is
-oundB a la%eled %rea: terminates t$e statement la%eled searc$B )$ic$ is t$e outer -or
loo*.
int[][] numbers = {{;. <. F&. {G. N. I&.
{D. J. P&&%
int searc!+um = N%
boolean found+um = false%
search.abel"
for( 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)ing
t$e la%eled 4terminated9 statement.
2.%.2 continue statement
T$e continue statement $as t)o -orms; unla%eled and la%eled. Eou can use t$e continue
statement to s:i* t$e current iteration o- a -orB )$ile or doI)$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*Fs %ody and e!aluates t$e
%oolean e6*ression t$at controls t$e loo*B %asically s:i**ing t$e remainder o- t$is
iteration o- t$e loo*.
T$e -ollo)ing e6am*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!e
list"%
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.oop"
for( 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 e6am*leB message 2 ne!er gets *rinted since )e $a!e t$e statement continue
outerloo* )$ic$ s:i*s t$e iteration.
2.%.3 return statement
T$e return statement is used to e6it -rom t$e current met$od. T$e -lo) o- control returns
to 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 doesnFt.
To return a !alueB sim*ly *ut t$e !alue 4or an e6*ression t$at calculates t$e !alue9 a-ter
t$e return :ey)ord. For e6am*leB
return 44count%
or
return "Hello"%
T$e data ty*e o- t$e !alue returned %y return must matc$ t$e ty*e o- t$e met$odFs
declared return !alue. .$en a met$od is declared !oidB use t$e -orm o- return t$at
doesnFt return a !alue. For e6am*leB
return%
.e )ill co!er more a%out return statements later )$en )e discuss a%out met$ods.
2.* 0-ercises
2.*.1 <rades
@et t$ree e6am grades -rom t$e user and com*ute t$e a!erage o- t$e grades. &ut*ut t$e
a!erage o- t$e t$ree e6ams. Toget$er )it$ t$e a!erageB also include a smiley -ace in t$e
out*ut i- t$e a!erage is greater t$an or e?ual to 60B ot$er)ise out*ut ;I4.
1. 3se Bu--ered"eader to get in*ut -rom t$e userB and 'ystem.out to out*ut t$e
result.
2. 3se J&*tionPane to get in*ut -rom t$e user and to out*ut t$e result.
2.*.2 1umber in !ords
@et a num%er as in*ut -rom t$e userB 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 1I10. I- t$e user in*uts a num%er t$at is not in
t$e rangeB out*utB RIn!alid num%erR.
1. 3se an i-Ielse statement to sol!e t$is *ro%lem
2. 3se a s)itc$ statement to sol!e t$is *ro%lem
2.*.3 undred +imes
1reate a *rogram t$at *rints your name a $undred times. Do t$ree !ersions o- t$is
*rogram using a )$ile loo*B a doI)$ile loo* and a -orIloo*.
2.*.% $o!ers
1om*ute t$e *o)er o- a num%er gi!en t$e %ase and e6*onent. Do t$ree !ersions o- t$is
*rogram using a )$ile loo*B a doI)$ile loo* and a -orIloo*.
6.1 Objectives
; =a)a Arrays
In t$is sectionB )e )ill %e discussing a%out Ja!a rrays. FirstB )e are going to de-ine
)$at arrays areB and t$en )e are going to discuss on $o) to declare and use t$em.
t t$e end o- t$e lessonB 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#s
In t$e *re!ious sectionsB )e $a!e discussed on $o) to declare di--erent !aria%les using
t$e *rimiti!e data ty*es. In declaring !aria%lesB )e o-ten use a uni?ue identi-ier or name
and a dataty*e. In order to use t$e !aria%leB )e call it %y its identi-ier name.
For e6am*leB )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 seeB it seems li:e a tedious tas: in order to Dust 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 languagesB t$ere is one ca*a%ility )$erein )e can use one !aria%le to store
a list o- data and mani*ulate t$em more e--iciently. T$is ty*e o- !aria%le is called an
array.
Figure /.1: Example of an 6nteger 3rray
n array stores multiple data items of the same datatypeB in a contiguous %loc: o-
memoryB di!ided into a num%er o- slots. T$in: o- an array as a stretc$ed !aria%le L a
location t$at still $as one identi-ier nameB %ut can $old more t$an one !alue.
6.3 ,eclaring /rra#s
rrays must %e declared li:e all !aria%les. .$en declaring an arrayB you list t$e data
ty*eB -ollo)ed %y a set o- s?uare %rac:etsXYB -ollo)ed %y t$e identi-ier name. For
e6am*leB
int []ages%
or you can *lace t$e %rac:ets a-ter t$e identi-ier. For e6am*leB
int ages[]%
-ter declaringB )e must create t$e array and s*eci-y its lengt$ )it$ a constructor
statement. T$is *rocess in Ja!a is called instantiation 4t$e Ja!a )ord -or creates9. In
order to instantiate an o%DectB )e need to use a constructor -or t$is. .e )ill co!er more
a%out instantiating o%Dects and constructors later. Ta:e noteB t$at t$e si>e o- an array
cannot %e c$anged once youF!e initiali>ed it. For e6am*leB
//declaration
int ages[]%
//instantiate object
ages = ne# int[;CC]%
orB can also %e )ritten asB
88declare and instantiate
o%Dect
int ages[] = ne#
int[;CC]%
In t$e e6am*leB t$e declaration tells t$e
Ja!a 1om*iler t$at t$e identi-ier ages )ill
%e used as t$e name o- an array containing
integersB and to create or instantiate a ne)
array containing 100 elements.
Instead o- using t$e ne) :ey)ord to
instantiate an arrayB you can also
automatically declareB construct and assign
!alues at once.
Figure /.2: 6nstantiating 3rrays
E6am*les areB
//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@A O P GMonH> GTueH> G'edH> GThuH> GFriH> GSatH> GSunHQR
6.% /ccessing an arra# element
To access an array elementB or a *art o- t$e arrayB 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 arrayB allo)ing t$e
*rogram and t$e *rogrammer to access indi!idual !alues )$en necessary. Inde6
num%ers are a&!ays integers. T$ey begin !ith Sero and progress sequentia&&y by
!ho&e numbers to the end o# the array. Ta:e note t$at t$e elements inside your
array is -rom 9 to 6siSeO#Array3+7,
For e6am*leB gi!en t$e array )e declared a )$ile agoB )e $a!e
//assigns ;C to t!e first element in t!e array
ages[C] = ;C%
//prints t!e last element in t!e array
System.out.print(ages[PP]%
Ta:e note t$at once an array is declared and constructedB t$e stored !alue o- eac$
mem%er o- t$e array )ill %e initiali>ed to >ero -or num%er data. #o)e!erB re-erence data
ty*es suc$ as 'trings are not initiali>ed to %lan:s or an em*ty string PQ. T$ere-oreB you
must *o*ulate t$e 'tring arrays e6*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*B 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 declarationB
int CDarr ' new intC1&&DG
is preferred o$erB
int CDarrG
arr ' new intC1&&DG
2. The elements of an n:element array ha$e indexes from & to n:1. "ote that there is
no array element arrCnDP This will result in an array:index:out:of:bounds exception.
. >ou cannot resiIe an array.
6.* /rra# lengt(
In order to get t$e num%er o- elements in an arrayB 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 )ritingB
array+ame.lengt!
For e6am*leB gi!en t$e *re!ious e6am*leB )e can reI)rite it asB
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 array
ob<ectRs lengt( field in the condition statement of the for loop. This will allow the
loop to ad<ust automatically for different:siIed arrays.
2. 1eclare the siIes of arrays in a 2a$a program using named constants to ma;e
them easy to change. For exampleB
final int 3883>JS6SE ' 1&&&G AAdeclare a constant
. . .
intCD ages ' new intC3883>JS6SEDG
Introduction to Programming I 120
1201
6.2 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 e6am*leB
// integer array N;< 5 ;<J elements
int[][] t#oE = ne# int[N;<][;<J]%
// c!aracter array J 5 ;I 5 <G
c!ar[][][] t!reeE = ne# c!ar[J][;I][<G]%
// String array G ro#s 5 < columns
String[][] dogs = {{ "terry". "bro#n" &.
{ "[ristin". "#!ite" &.
{ "toby". "gray"&.
{ "fido". "blac-"&
b[
To access an element in a multidimensional array is Dust t$e same as accessing t$e
elements in a one dimensional array. For e6am*leB to access t$e -irst element in t$e -irst
ro) o- t$e array dogsB )e )riteB
System.out.print( dogs[C][C] %
T$is )ill *rint t$e 'tring RterryR on t$e screen.
Introduction to Programming I 121
1211
6.6 0-ercises
6.6.1 ,a#s of t(e 'ee8
1reate an array o- 'trings )$ic$ are initiali>ed to t$e H days o- t$e )ee:. For Example,
String days[] = {AMondayB. A2uesdayB].&%
3sing a )$ileIloo*B *rint all t$e contents o- t$e array. 4do t$e same -or doI)$ile and -orI
loo*9
6.6.2 <reatest number
3sing Bu--ered"eader or J&*tionPaneB as: -or 10 num%ers -rom t$e user. 3se an array to
store t$e !alues o- t$ese 10 num%ers. &ut*ut on t$e screen t$e num%er )it$ t$e
greatest !alue.
6.6.3 /ddressboo8 0ntries
@i!en t$e -ollo)ing multidimensional array t$at contains address%oo: entries;
String entry = {{"9lorence". "DFNH;<FG". "Manila"&.
{"(oyce". "PJFHFFFF". "^ueKon 3ity"&.
{":ecca". "GNIHFF<<". "Manila"&&%
Print t$e -ollo)ing entries on screen in t$e -ollo)ing -ormat;
+ame 7 9lorence
2el. _ 7 DFNH;<FG
/ddress 7 Manila
+ame 7 (oyce
2el. _ 7 PJFHFFFF
/ddress 7 ^ueKon 3ity
+ame 7 :ecca
2el. _ 7 GNIHFF<<
/ddress 7 Manila
Introduction to Programming I 122
1221
: "ommand3&ine Arguments
@.1 Objectives
In t$is sectionB )e )ill study on $o) to *rocess in*ut -rom t$e commandIline %y using
arguments *ass onto a Ja!a *rogram.
t t$e end o- t$e lessonB t$e student s$ould %e a%le to;
Ano) and e6*lain )$at a commandIline argument is
@et in*ut -rom t$e user using commandIline 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 commandIline.
1ommandIline arguments allo) t$e user to a--ect t$e o*eration o- an a**lication -or one
in!ocation. T$e user enters commandIline arguments )$en in!o:ing t$e a**lication and
s*eci-ies t$em a-ter t$e name o- t$e class to run.
For e6am*leB su**ose you $a!e a Ja!a a**licationB called 'ortB t$at sorts -i!e num%ersB
you run it li:e t$is;
Figure 0.1: 8unning with Command:4ine 3rguments
Ta:e note t$at t$e arguments are se*arated %y s*aces.
Introduction to Programming I 123
1231
In t$e Ja!a languageB )$en you in!o:e an a**licationB t$e runtime system *asses t$e
commandIline arguments to t$e a**licationFs main met$od !ia an array o- 'trings. Eac$
'tring in t$e array contains one o- t$e commandIline arguments. "emem%er t$e
declaration -or t$e main met$odB
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 e6am*leB t$e commandIline arguments *assed to t$e 'ort a**lication is
an array t$at contains -i!e strings )$ic$ are; R,RB R0RB R3RB R2R and R1R. Eou can deri!e
t$e num%er o- commandIline arguments )it$ t$e arrayFs lengt$ attri%ute.
For e6am*leB
int numberMf/rgs = args.lengt!%
I- your *rogram needs to su**ort a numeric commandIline argumentB it must con!ert a
'tring argument t$at re*resents a num%erB suc$ as R30RB to a num%er. #ereFs a code
sni**et t$at con!erts a commandIline argument to an integerB
int first/rg = C%
if (args.lengt! S C{
first/rg = ,nteger.parse,nt(args[C]%
&
*arseInt t$ro)s a +um%erFormatE6ce*tion 4E""&"9 i- t$e -ormat o- argsX0Y isnFt !alid
4not a num%er9.
Coding <uidelines.
9efore using command:line argumentsB always chec; if the number of arguments
before accessing the array elements so that there will be no exception generated.
Introduction to Programming I 120
1201
@.3 Command"line arguments in 1etBeans
To illustrate on $o) to *ass some arguments to your *rograms in +etBeansB let us create
a Ja!a *rogram t$at )ill *rint t$e num%er o- arguments and t$e -irst argument *assed to
it.
public class 3ommandTine05ample
{
public static void main( String[] args {
System.out.println("+umber of arguments=" 4
args.lengt!%
System.out.println("9irst /rgument="4 args[C]%
&
&
+o)B run net%eans and create a ne) *roDect and name t$is 1ommand=ineE6am*le. 1o*y
t$e code s$o)n a%o!e and com*ile t$e code. +o)B -ollo) t$ese ste*s to *ass arguments
to your *rogram using +etBeans.
1lic: on ProDects 4encircled %elo)9.
Figure 0.2: -pening )ro<ect File
Introduction to Programming I 12,
12,1
"ig$tIclic: on t$e 1ommand=ineE6am*le iconB and a *o*u* menu )ill a**ear. 1lic: on
Pro*erties.
Figure 0.: -pening )roperties
T$e ProDect Pro*erties dialog )ill t$en a**ear.
Figure 0.%: )roperties 1ialog
Introduction to Programming I 126
1261
+o)B clic: on "unIV "unning ProDect.
Figure 0.+: Clic; -n 8unning )ro<ect
&n t$e rguments te6t%o6B ty*e t$e arguments you )ant to *ass to your *rogram. In
t$is case )e ty*ed in t$e arguments , 0 3 2 1. T$enB clic: on t$e &A %utton.
Figure 0.*: Set the Command:4ine 3rguments
Introduction to Programming I 12H
12H1
+o) try to "3+ your *rogram.
Figure 0./: 8unning the )rogram in with the Shortcut 9utton
s you can see $ereB t$e out*ut to your *rogram is t$e num%er o- arguments )$ic$ is ,B
and t$e -irst argument )$ic$ is ,.
Figure 0.0: )rogram -utput
Introduction to Programming I 127
1271
@.% 0-ercises
@.%.1 $rint arguments
@et in*ut -rom t$e user using commandIline arguments and *rint all t$e arguments to
t$e screen. For e6am*leB i- t$e user enteredB
java Hello #orld t!at is all
your *rogram s$ould *rint
Hello
#orld
t!at
is
all
@.%.2 /rit(metic Operations
@et t)o num%ers -rom t$e user using commandIline arguments and *rint sumB
di--erenceB *roduct and ?uotient o- t$e t)o num%ers. For e6am*leB i- t$e user enteredB
java /rit!meticMperation <C G
your *rogram s$ould *rint
sum = <G
difference = ;I
product = JC
@uotient = N
Introduction to Programming I 12<
12<1
T 'or%ing !ith the =a)a "&ass Library
C.1 Objectives
In t$is sectionB )e )ill introduce some %asic conce*ts o- o%DectIoriented *rogramming.
=ater onB )e )ill discuss t$e conce*t o- classes and o%DectsB and $o) to use t$ese
classes and t$eir mem%ers. 1om*arisonB con!ersion and casting o- o%Dects )ill also %e
co!ered. For no)B )e )ill -ocus on using classes t$at are already de-ined in t$e Ja!a
class li%raryB )e )ill discuss later on $o) to create your o)n classes.
t t$e end o- t$e lessonB t$e student s$ould %e a%le to;
E6*lain o%DectIoriented *rogramming and some o- its conce*ts
Di--erentiate %et)een classes and o%Dects
Di--erentiate %et)een instance !aria%les8met$ods and class4static9
!aria%les8met$ods
E6*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
1ast *rimiti!e data ty*es and o%Dects
1om*are o%Dects and determine t$e class o- an o%Dects
C.2 Introduction to Object"Oriented
$rogramming
&%DectI&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 )orldB )e can
-ind many o%Dects around usB suc$ as carsB lionB *eo*le and so on. T$ese o%Dects are
c$aracteri>ed %y t$eir properties 6or attributes7 and beha)iors.
For e6am*leB a car o%Dect $as t$e *ro*ertiesB type of transmissionB manufacturer and
color. Its %e$a!iors are turningB bra;ing and accelerating. 'imilarlyB )e can de-ine
di--erent *ro*erties and %e$a!ior o- a lion. Please re-er to t$e ta%le %elo) -or t$e
e6am*les.
Object $roperties Be(avior
1ar ty*e o- transmission
manu-acturer
color
turning
%ra:ing
accelerating
=ion .eig$t
1olor
$ungry or not $ungry
tamed or )ild
roaring
slee*ing
$unting
Table 1/: Example of 8eal:life -b<ects
Introduction to Programming I 130
1301
.it$ t$ese descri*tionsB t$e o%Dects in t$e *$ysical )orld can easily %e modeled as
so-t)are o%Dects using t$e properties as data and t$e beha)iors as methods. T$ese
data and met$ods could e!en %e used in *rogramming games or interacti!e so-t)are to
simulate t$e realI)orld o%DectsJ n e6am*le )ould %e a car so-t)are o%Dect in a racing
game or a lion so-t)are o%Dect in an educational interacti!e so-t)are >oo -or :ids.
C.3 Classes and Objects
C.3.1 ,ifference Bet!een Classes and
Objects
In t$e so-t)are )orldB an obCect is a so-t)are com*onent )$ose structure is similar to
o%Dects in t$e real )orld. Eac$ o%Dect 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%DectB and it also
consists o- a set o- methods 4%e$a!ior9 t$at descri%es $o) an o%Dect %e$a!es. T$usB an
o%Dect is a so-t)are %undle o- !aria%les and related met$ods. T$e !aria%les and met$ods
in a Ja!a o%Dect are -ormally :no)n as instance )ariab&es and instance methods to
distinguis$ t$em -rom class !aria%les and class met$odsB )$ic$ )ill %e discussed later.
T$e c&ass is t$e -undamental structure in o%DectIoriented *rogramming. It can %e
t$oug$t o- as a tem*lateB a *rototy*e or a %lue*rint o- an o%Dect. It consists o- t)o ty*es
o- mem%ers )$ic$ are called #ie&ds 6properties or attributes7 and met$ods. Fields
s*eci-iy t$e data ty*es de-ined %y t$e classB )$ile met$ods s*eci-y t$e o*erations. n
o%Dect is an instance o- t$e class.
To di--erentiate %et)een classes and o%DectsB let us discuss an e6am*le. .$at )e $a!e
$ere is a 1ar 1lass )$ic$ can %e used to de-ine se!eral 1ar &%Dects. In t$e ta%le s$o)n
%elo)B 1ar and 1ar B are o%Dects o- t$e 1ar class. T$e class $as fields *late num%erB
colorB manu-acturerB and current s*eed )$ic$ are -illedIu* )it$ corres*onding !alues in
o%Dects 1ar and 1ar B. T$e 1ar $as also some met$ods ccelerateB Turn and Bra:e.
"ar "&ass ObCect "ar A ObCect "ar 0
6
n
s
t
a
n
c
e
?
a
r
i
a
b
l
e
s
Plate +um%er B1 111 /Ec 123
1olor Blue "ed
(anu-acturer (itsu%is$i Toyota
1urrent '*eed ,0 :m8$ 100 :m8$
6
n
s
t
a
n
c
eccelerate (et$od
Turn (et$od
Bra:e (et$od
Table 10: Example of Car class and its ob<ects
.$en instantiatedB eac$ o%Dect gets a -res$ set o- state !aria%les. #o)e!erB t$e met$od
im*lementations are s$ared among o%Dects o- t$e same class.
1lasses *ro!ide t$e %ene-it o- reusabi&ity. 'o-t)are *rogrammers can use a class o!er
and o!er again to create many o%Dects.
Introduction to Programming I 131
1311
C.3.2 0ncapsulation
Enca*sulation is t$e met$od o- $iding certain elements o- t$e im*lementation o- a
certain class. By *lacing a %oundary around t$e *ro*erties and met$ods o- our o%DectsB
)e can *re!ent our *rograms -rom $a!ing side e--ects )$erein *rograms $a!e t$eir
!aria%les c$anged in une6*ected )ays.
.e can *re!ent access to our o%DectFs 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!a
im*lements enca*sulation as )e discuss more a%out classes.
C.3.3 Class Dariables and Met(ods
In addition to t$e instance !aria%lesB 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 -or
all t$e o%Dects in t$e same class. T$ey are also called static member )ariab&es.
To clearly descri%e class !aria%lesB letFs go %ac: to our 1ar class e6am*le. 'u**ose t$at
our 1ar class $as one class !aria%le called 1ount. I- )e c$ange t$e !alue o- 1ount to 2B
all o- t$e o%Dects o- t$e 1ar class )ill $a!e t$e !alue 2 -or t$eir 1ount !aria%le.
"ar "&ass ObCect "ar A ObCect "ar 0
6
n
s
t
a
n
c
e
?
a
r
i
a
b
l
e
s
Plate +um%er B1 111 /Ec 123
1olor Blue "ed
(anu-acturer (itsu%is$i Toyota
1urrent '*eed ,0 :m8$ 100 :m8$
C
l
a
s
s
?
a
r
i
a
b
l
e
1ount S 2
6
n
s
t
a
n
c
eccelerate (et$od
Turn (et$od
Bra:e (et$od
Table 17: Car classR methods and $ariables
Introduction to Programming I 132
1321
C.3.% Class Instantiation
To create an o%Dect or an instance o- a classB )e use t$e ne! o*erator. For e6am*leB i-
you )ant to create an instance o- t$e class 'tringB )e )rite t$e -ollo)ing codeB
String str< = ne# String(AHello #orld$B%
or also e?ui!alent toB
String str< = "Hello"%
Figure 7.1: Classs 6nstantiation
T$e ne) o*erator allocates a memory -or t$at o%Dect and returns a re#erence o- t$at
memory location to you. .$en you create an o%DectB you actually in!o:e t$e classF
constructor, T$e constructor is a met$od )$ere you *lace all t$e initiali>ationsB it $as
t$e same name as t$e class.
Introduction to Programming I 133
1331
C.% Met(ods
C.%.1 '(at are Met(ods and '(# :se Met(ods)
In t$e e6am*les )e discussed %e-oreB )e only $a!e one met$odB and t$at is t$e main49
met$od. In Ja!aB )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$er
met$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 e6ecutionB it goes %ac: to t$e met$od t$at called it.
+o)B )$y do )e need to create met$odsG .$y donFt )e Dust *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 can
do 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 smallB managea%le *ieces is critical to )riting large
*rograms.
Introduction to Programming I 130
1301
C.%.2 Calling Instance Met(ods and $assing
Dariables
+o)B to illustrate $o) to call met$odsB letFs use t$e 'tring class as an e6am*le. Eou can
use t$e Ja!a PI documentation to see all t$e a!aila%le met$ods in t$e 'tring class.
=ater onB )e )ill create our o)n met$odsB %ut -or no)B let us use )$at is a!aila%le.
To call an instance methodB )e )rite t$e -ollo)ingB
nameMfMbject.nameMfMet!od( parameters %
=etFs ta:e t)o sam*le met$ods -ound in t$e class 'tringB
Method dec&aration $e#inition
public char char4t(int inde1+
"eturns t$e c$aracter at t$e s*eci-ied inde6.
n inde6 ranges -rom 0 to lengt$49 I 1. T$e -irst
c$aracter o- t$e se?uence is at inde6 0B t$e
ne6t at inde6 1B and so onB as -or array
inde6ing.
public boolean e5uals&gnore6ase
()tring another)tring+
1om*ares t$is 'tring to anot$er 'tringB ignoring
case considerations. T)o strings are considered
e?ual ignoring case i- t$ey are o- t$e same
lengt$B and corres*onding c$aracters in t$e t)o
strings are e?ual ignoring case.
Table 2&: Sample =ethods of class String
3sing t$e met$odsB
String str; = "Hello"%
c!ar 5 = str<.c!ar/t(C% //#ill return t!e c!aracter H
//and store it to variable 5
String str< = "!ello"%
//t!is #ill return a boolean value true
boolean result = str;.e@uals,gnore3ase( str; %
Introduction to Programming I 13,
13,1
C.%.3 $assing Dariables in Met(ods
In our e6am*lesB )e already tried *assing !aria%les to met$ods. #o)e!erB )e $a!enFt
di--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$odsB t$e -irst one is *assI%yI!alue and t$enB *assI%yI
re-erence.
T,<,-,+ Pass3by3)a&ue
.$en a *assI%yI!alue occursB 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 argument
e!en i- it modi-ies t$e *arameters during calculations.
For e6am*leB
public class 2est)ass:yLalue
{
public static void main( String[] args {
int i = ;C%
//print t!e value of i
System.out.println( i %
//call met!od test
//and pass i to met!od test
test( i +;
)ass i as parameter
#!ic! is copied to j
//print t!e value of i. i not c!anged
System.out.println( i %
&
public static void test( int +,
77change value o$ parameter
= 88;
-
-
In t$e gi!en e6am*leB )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 D. 'ince D is t$e !aria%le c$anged in
t$e test met$odB it )ill not a--ect t$e !aria%le !alue i- i in main since it is a di--erent co*y
o- t$e !aria%le.
By de-aultB all *rimiti!e data ty*es )$en *assed to a met$od are *assI%yI!alue.
T,<,-,. Pass3by3re#erence
.$en a *assI%yIre-erence occursB t$e re-erence to an o%Dect is *assed to t$e calling
met$od. T$is means t$atB 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!erB unli:e in *assI%yI!alueB t$e met$od can modi-y t$e
actual o%Dect t$at t$e re-erence is *ointing toB sinceB alt$oug$ di--erent re-erences are
used in t$e met$odsB t$e location o- t$e data t$ey are *ointing to is t$e same.
For e6am*leB
class 2est)ass:yQeference
{
public static void main( String[] args {
//create an array of integers
int []ages = {;C. ;;. ;<&%
//print array values
for( int i=C% iUages.lengt!% i44 {
System.out.println( ages[i] %
&
)ass ages as parameter
#!ic! is copied to
variable arr
//call test and pass reference to array
test( ages +;
//print array values again
for( 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;
-
-
&
Figure 7.2: )ass:by:reference example
Coding
<uidelines.
3 common misconception about pass:by:reference in 2a$a is when creating a swap
method using 2a$a references. Ta;e note that 2a$a manipulates ob<ects Rby referenceBR
but it passes ob<ect references to methods Rby $alue.RF 3s a resultB you cannot write a
standard swap method to swap ob<ects.
C.%.% 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 and
not to a certain instance 4or o%Dect9 o- a class. 'tatic met$ods are distinguis$ed -rom
instance met$ods in a class de-inition %y t$e :ey)ord static.
To call a static met$odB Dust ty*eB
3lassname.staticMet!od+ame(params%
E6am*les o- static met$odsB )eF!e used so -ar in our e6am*les
areB
//prints data to screen
)ystem*out*println(AHello #orldB%
//converts t!e String ;C. to an integer
int i = &nteger*parse&nt(A;CB%
//Qeturns a String representation of t!e integer argument as an
//unsigned integer base ;I
String !e50@uivalent = &nteger*to;e1)tring( ;C %
C.%.* Scope of a variable
In addition to a !aria%leFs data ty*e and nameB a !aria%le $as sco*e. T$e scope
determines )$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 e6ist in memory. T$e sco*e is
determined %y )$ere t$e !aria%le declaration is *laced in t$e *rogram.
To sim*li-y t$ingsB Dust 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:sB and t$e inner curly %races is called
inner %loc:s.
I- you declare !aria%les in t$e outer %loc:B t$ey are !isi%le 4i.e. usa%le9 %y t$e *rogram
lines inside t$e inner %loc:s. #o)e!erB i- you declare !aria%les in t$e inner %loc:B you
cannot e6*ect t$e outer %loc: to see it.
!aria%leFs sco*e is inside t$e %loc: )$ere it is declaredB starting -rom t$e *oint )$ere it
is declaredB and in t$e inner %loc:s.
For e6am*leB gi!en t$e -ollo)ing code sni**etB
public class Scope05ample
{
public static void main( String[] args {
int i = C%
int j = C%
//... some code !ere
0
A
{
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 iBDB:Bm and nB and t$e -i!e sco*es BBB1BD
and EB )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 D is B.
T$e sco*e o- !aria%le : is 1.
T$e sco*e o- !aria%le m is D.
T$e sco*e o- !aria%le n is E.
+o)B gi!en t$e t)o met$ods main and test in our *re!ious e6am*lesB
class 2est)ass:yQeference
{
public static void main( String[] args {
//create an array of integers
int []ages = {;C. ;;. ;<&%
//print array values
for( int i=C% iUages.lengt!% i44 {
System.out.println( ages[i] %
&
A
//call test and pass reference to array
test( ages %
//print array values again
for( int i=C% iUages.lengt!% i44 {
"
System.out.println( ages[i] %
&
&
public static void test( int[] arr {
//c!ange values of array
for( int i=C% iUarr.lengt!% i44 { $
arr[i] = i 4 NC%
&
&
&
In t$e main met$odB t$e sco*e o- t$e !aria%les areB
agesXY I sco*e
i in B I sco*e B
i in 1 L sco*e 1
In t$e test met$odB t$e sco*e o-t$e !aria%les areB
arrXY I sco*e D
i in E I sco*e E
Introduction to Programming I 100
1001
.$en declaring !aria%lesB only one !aria%le )it$ a gi!en identi-ier or name can %e
declared in a sco*e. T$at means t$at i- you $a!e t$e -ollo)ing declarationB
{
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!erB you can $a!e t)o !aria%les o- t$e same nameB i- t$ey
are not declared in t$e same %loc:. For e6am*leB
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:eB it *rints t$e !alue o- t$e -irst test !aria%le
since it is t$e !aria%le seen at t$at sco*e. For t$e second 'ystem.out.*rintB t$e !alue 20
is *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$oid
confusion.
Introduction to Programming I 101
1011
C.* Casting= Converting and Comparing
Objects
In t$is sectionB )e are going to learn $o) to do typecasting. Ty*ecasting or casting is
t$e *rocess o- con!erting a data o- a certain data ty*e to anot$er data ty*e. .e )ill also
learn $o) to con!ert *rimiti!e data ty*es to o%Dects and !ice !ersa. nd -inallyB )e are
going to learn $o) to com*are o%Dects.
C.*.1 Casting $rimitive +#pes
1asting %et)een *rimiti!e ty*es ena%les you to con!ert t$e !alue o- one data -rom one
ty*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$B and t$at is t$e
boo&ean data ty*e.
n e6am*le o- ty*ecasting is )$en you )ant to store an integer data to a !aria%le o-
data ty*e dou%le. For e6am*leB
int num,nt = ;C%
double numEouble = num,nt% //implicit cast
In t$is e6am*leB since t$e destination !aria%le 4dou%le9 $olds a larger !alue t$an )$at
)e )ill *lace inside itB t$e data is im*licitly casted to data ty*e dou%le.
not$er e6am*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,B
t$e cast 4c$ar9i *roduces t$e c$aracter !alue FF. T$e numeric code associated )it$ a
ca*ital is 6,B according to t$e '1II c$aracter setB and Ja!a ado*ted t$is as *art o- its
c$aracter su**ort. For e6am*leB
c!ar val3!ar = ?/?%
int val,nt = val3!ar%
System.out.print( val&nt % //e5plicit cast7 output IN
Introduction to Programming I 102
1021
.$en )e con!ert a data t$at $as a large ty*e to a smaller ty*eB )e must use an exp&icit
cast. E6*licit casts ta:e t$e -ollo)ing -orm;
(data2ypevalue
)$ereB
dataTypeB is t$e name o- t$e data ty*e youFre con!erting to
$alueB is an e6*ression t$at results in t$e !alue o- t$e source ty*e.
For e6am*leB
double valEouble = ;C.;<%
int val,nt = (int+val<ouble; //convert valEouble to int type
double 5 = ;C.<%
int y = <%
int result = (int+(17y+% //typecast result of operation to
int
C.*.2 Casting Objects
Instances o- classes also can %e cast into instances o- ot$er classesB )it$ one
restriction; The source and destination c&asses must be re&ated by inheritanceR
one c&ass must be a subc&ass o# the other, .eFll co!er more a%out in$eritance later.
nalogous to con!erting a *rimiti!e !alue to a larger ty*eB some o%Dects mig$t not need
to %e cast e6*licitly. In *articularB %ecause a su%class contains all t$e same in-ormation
as its su*erclassB you can use an instance o- a su%class any)$ere a su*erclass is
e6*ected.
For e6am*leB consider a met$od t$at ta:es t)o argumentsB one o- ty*e &%Dect and
anot$er o- ty*e .indo). Eou can *ass an instance o- any class -or t$e &%Dect argument
%ecause all Ja!a classes are su%classes o- &%Dect. For t$e .indo) argumentB you can
*ass in its su%classesB suc$ as DialogB FileDialogB and Frame. T$is is true any)$ere in a
*rogramB not Dust inside met$od calls. I- you $ad a !aria%le de-ined as class .indo)B you
could assign o%Dects 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!erseB and you can use a su*erclass )$en a su%class is e6*ected.
T$ere is a catc$B $o)e!er; 0ecause subc&asses contain more beha)ior than their
superc&asses> thereUs a &oss in precision in)o&)ed, T$ose su*erclass o%Dects mig$t
not $a!e all t$e %e$a!ior needed to act in *lace o- a su%class o%Dect. For e6am*leB i- you
$a!e an o*eration t$at calls met$ods in o%Dects o- t$e class IntegerB using an o%Dect o-
class +um%er )onFt include many met$ods s*eci-ied in Integer. Errors occur i- you try to
call met$ods t$at t$e destination o%Dect doesnFt $a!e.
To use su*erclass o%Dects )$ere su%class o%Dects are e6*ectedB you must cast t$em
e6*licitly. Eou )onFt lose any in-ormation in t$e castB %ut you gain all t$e met$ods and
!aria%les t$at t$e su%class de-ines. To cast an o%Dect to anot$er classB you use t$e same
o*eration as -or *rimiti!e ty*es;
To castB
(classnameobject
)$ereB
classnameB is t$e name o- t$e destination class
ob<ectB is a re-erence to t$e source o%Dect.
/ote2 t$at casting creates a re-erence to t$e old o%Dect o- t$e ty*e classname[ t$e old
o%Dect continues to e6ist as it did %e-ore.
Figure 7.%: Class !ierarchy for superclass Employee
T$e -ollo)ing e6am*le casts an instance o- t$e class VicePresident to an instance o- t$e
class Em*loyee[ VicePresident is a su%class o- Em*loyee )it$ more in-ormationB )$ic$
$ere de-ines t$at t$e VicePresident $as e6ecuti!e )as$room *ri!ilegesB
0mployee emp = ne# 0mployee(%
Lice)resident veep = ne# Lice)resident(%
emp = veep% // no cast needed for up#ard use
veep = (Lice)residentemp% // must cast e5plicitly3asting
C.*.3 Converting $rimitive +#pes to Objects and Dice
Dersa
&ne t$ing you canFt do under any circumstance is cast -rom an o%Dect to a *rimiti!e data
ty*eB or !ice !ersa. Primiti!e ty*es and o%Dects are !ery di--erent t$ings in Ja!aB and you
canFt automatically cast %et)een t$e t)o or use t$em interc$angea%ly.
s an alternati!eB t$e Ca)a,&ang *ac:age includes classes t$at corres*ond to eac$
*rimiti!e data ty*e; FloatB BooleanB ByteB and so on. (ost o- t$ese classes $a!e t$e
same names as t$e data ty*esB e6ce*t t$at t$e class names %egin )it$ a ca*ital letter
4'$ort instead o- s$ortB Dou%le instead o- dou%leB and t$e li:e9. lsoB t)o classes $a!e
names t$at di--er -rom t$e corres*onding data ty*e; 1$aracter is used -or c$ar !aria%les
and 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--erentlyB and a *rogram )onFt
com*ile success-ully i- you use one )$en t$e ot$er is e6*ected.
3sing t$e classes t$at corres*ond to eac$ *rimiti!e ty*eB you can create an o%Dect 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 HS Mbject
&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 ne'6ount = data6ount*int@alue(+;
// / common translation you need in programs
// is converting a String to a numeric type. suc! as an int
// MbjectHSprimitive
)tring pennsylvania = "A:999";
int penn = &nteger*parse&nt(pennsylvania+;
"A1TIO/2 T$e Void class re*resents not$ing in Ja!aB so t$ereFs no reason it )ould %e
used )$en translating %et)een *rimiti!e !alues and o%Dects. ItFs a *lace$older -or t$e
!oid :ey)ordB )$ic$ is used in met$od de-initions to indicate t$at t$e met$od does
not return a !alue.
C.*.% Comparing Objects
In our *re!ious discussionsB )e learned a%out o*erators -or com*aring !aluesde?ualB
not e?ualB less t$anB and so on. (ost o- t$ese o*erators )or: only on *rimiti!e ty*esB not
on o%Dects. I- you try to use ot$er !alues as o*erandsB t$e Ja!a com*iler *roduces errors.
T$e e6ce*tions to t$is rule are t$e o*erators -or e?uality; SS 4e?ual9 and JS 4not e?ual9.
.$en a**lied to o%DectsB t$ese o*erators donFt do )$at you mig$t -irst e6*ect. Instead o-
c$ec:ing )$et$er one o%Dect $as t$e same !alue as t$e ot$er o%DectB t$ey determine
)$et$er %ot$ sides o- t$e o*erator re-er to t$e same o%Dect.
To com*are instances o- a class and $a!e meaning-ul resultsB you must im*lement
s*ecial met$ods in your class and call t$ose met$ods. good e6am*le o- t$is is t$e
'tring class.
It is *ossi%le to $a!e t)o di--erent 'tring o%Dects t$at contain t$e same !alues. I- you
)ere to em*loy t$e SS o*erator to com*are t$ese o%DectsB $o)e!erB t$ey )ould %e
considered une?ual. lt$oug$ t$eir contents matc$B t$ey are not t$e same o%Dect.
To see )$et$er t)o 'tring o%Dects $a!e matc$ing !aluesB a met$od o- t$e class called
e?uals49 is used. T$e met$od tests eac$ c$aracter in t$e string and returns true i- t$e
t)o strings $a!e t$e same !alues.
T$e -ollo)ing code illustrates t$isB
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 *rogramFs out*ut is as -ollo)sB
&3TP3T;
String;7 9ree t!e bound periodicals.
String<7 9ree t!e bound periodicals.
Same objectZ true
String;7 9ree t!e bound periodicals.
String<7 9ree t!e bound periodicals.
Same objectZ false
Same valueZ 2rue
+o) letFs 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 str29B assigns t$e literal
RFree t$e %ound *eriodicals.R to str1B and t$en assigns t$at !alue to str2. s you learned
earlierB str1 and str2 no) *oint to t$e same o%DectB and t$e e?uality test *ro!es t$at.
str< = ne# String(str;%
In t$e second *art o- t$is *rogramB you create a ne) 'tring o%Dect )it$ t$e same !alue
as str1 and assign str2 to t$at ne) 'tring o%Dect. +o) you $a!e t)o di--erent string
o%Dects in str1 and str2B %ot$ )it$ t$e same !alue. Testing t$em to see )$et$er t$eyFre
t$e same o%Dect %y using t$e SS o*erator returns t$e e6*ected ans)er; -alsedt$ey are
not t$e same o%Dect in memory. Testing t$em using t$e e?uals49 met$od also returns t$e
e6*ected ans)er; truedt$ey $a!e t$e same !alues.
Figure 7.*: 8eferences now point to different ob<ects
/OTE2 .$y canFt you Dust use anot$er literal )$en you c$ange str2B rat$er t$an using
ne)G 'tring literals are o*timi>ed in Ja!a[ i- you create a string using a literal and
t$en use anot$er literal )it$ t$e same c$aractersB Ja!a :no)s enoug$ to gi!e you t$e
-irst 'tring o%Dect %ac:. Bot$ strings are t$e same o%Dects[ you $a!e to go out o- your
)ay to create t)o se*arate o%Dects.
C.*.* ,etermining t(e Class of an Object
.ant to -ind out )$at an o%DectFs class isG #ereFs t$e )ay to do it -or an o%Dect assigned
to t$e !aria%le :ey;
1. T$e get"&ass67 method returns a 1lass o%Dect 4)$ere 1lass is itsel- a class9 t$at $as
a met$od called get+ame49. In turnB get+ame49 returns a string re*resenting t$e
name o- t$e class.
For E6am*leB
String name = -ey.get3lass(.get+ame(%
., The instanceO# operator
T$e instance&- $as t)o o*erands; a re-erence to an o%Dect on t$e le-t and a class
name on t$e rig$t. T$e e6*ression returns true or -alse %ased on )$et$er t$e o%Dect is
an instance o- t$e named class or any o- t$at classFs su%classes.
For E6am*leB
boolean e5; = "2e5as" instanceof String% // true
Mbject pt = ne# )oint(;C. ;C%
boolean e5< = pt instanceof String% // false
C.2 0-ercises
C.2.1 ,efining terms
In your o)n )ordsB de-ine t$e -ollo)ing terms;
1. 1lass
2. &%Dect
3. Instantiate
0. Instance Varia%le
,. Instance (et$od
6. 1lass Varia%les or static mem%er !aria%les
H. 1onstructor
C.2.2 7ava Scavenger unt
Pi*oy is a ne)%ie in t$e Ja!a *rogramming language. #e Dust $eard t$at t$ere are
already readyItoIuse PIs in Ja!a t$at one could use in t$eir *rogramsB and $eFs eager to
try t$em out. T$e *ro%lem isB Pi*oy does not $a!e a co*y o- t$e Ja!a DocumentationB
and $e also doesnFt $a!e an internet accessB so t$ereFs no )ay -or $im to !ie) t$e Ja!a
PIs.
Eour tas: is to $el* Pi*oy loo: -or t$e PIs 4**lication Programming Inter-ace9. Eou
s$ould state t$e class )$ere t$e met$od %elongsB t$e met$od declaration and a sam*le
usage o- t$e said met$od.
For e6am*leB i- Pi*oy )ants to :no) t$e met$od t$at con!erts a 'tring to integerB your
ans)er s$ould %e;
"&ass2 Integer
Method $ec&aration2 *u%lic static int *arseInt4 'tring !alue 9
Samp&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*uts
t$e correct ans)erB 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:B gi!e only one.
/o! &etUs start the searchL
1. =oo: -or a met$od t$at c$ec:s i- a certain 'tring ends )it$ a certain su--i6. For
e6am*leB i- t$e gi!en string is R#elloRB t$e met$od s$ould return true t$e su--i6 gi!en
is RloRB and -alse i- t$e gi!en su--i6 is Ral*R.
2. =oo: -or t$e met$od t$at determines t$e c$aracter re*resentation -or a s*eci-ic digit
in t$e s*eci-ied radi6. For e6am*leB i- t$e in*ut digit is 1,B and t$e radi6 is 16B t$e
met$od )ould return t$e c$aracter FB since F is t$e $e6adecimal re*resentation -or
t$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
0. =oo: -or t$e met$od t$at gets t$e -loor o- a dou%le !alue. For e6am*leB i- I in*ut a
3.13B 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 e6am*leB i- I
in*ut F3FB it returns t$e !alue true.
Introduction to Programming I 1,0
1,01
+9 "reating your o!n "&asses
15.1 Objectives
+o) t$at )eF!e studied on $o) to use e6isting classes -rom t$e Ja!a class li%raryB )e )ill
no) %e studying on $o) to )rite our o)n classes. For t$is sectionB in order to easily
understand $o) to create classesB )e )ill ma:e a sam*le class )$erein )e )ill add more
data 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 a
certain student record.
T$ings to ta:e note o- -or t$e synta6 de-ined in t$is section and -or t$e ot$er sections;
U I means t$at t$ere may %e 0 or more occurrences o- t$e line
)$ereit )as a**lied to.
adescri*tionV I 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 I indicates t$at t$is *art is o*tional
t t$e end o- t$e lessonB t$e student s$ould %e a%le to;
1reate t$eir o)n classes
Declare attri%utes and met$ods -or t$eir classes
3se t$e t$is re-erence to access instance data
1reate and call o!erloaded met$ods
Im*ort and create *ac:ages
3se access modi-iers to control access to class mem%ers
Introduction to Programming I 1,1
1,11
15.2 ,efining #our o!n classes
Be-ore )riting your classB 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 classB and list all t$e in-ormation
or *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 classB )e )riteB
UmodifierS class UnameS {
UattributeEeclarationS*
UconstructorEeclarationS*
Umet!odEeclarationS*
&
)$ere
TmodifierQ is an access modi-ierB )$ic$ may %e com%ined )it$ ot$er ty*es o- modi-ier.
Coding
<uidelines.
8emember that for a top:le$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 sectionB )e )ill %e creating a class t$at )ill contain a student record. 'ince )eF!e
already identi-ied t$e *ur*ose o- our classB )e can no) name it. n a**ro*riate name -or
our class )ould %e StudentQecord.
+o)B to de-ine our class )e )riteB
public class )tudent%ecord
{
//#e?ll add more code !ere later
&
)$ereB
*u%lic I means t$at our class is accessi%le to ot$er classes outside t$e
*ac:age
class I t$is is t$e :ey)ord used to create a class in Ja!a
'tudent"ecord I a uni?ue identi-ier t$at descri%es our class
"oding ?uide&ines2
1. Thin; of an appropriate name for your class. 1onRt <ust call your class U>S or
any 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.
Introduction to Programming I 1,2
1,21
15.3 ,eclaring /ttributes
To declare a certain attri%ute -or our classB )e )riteB
UmodifierS UtypeS UnameS [= Udefault\valueS]%
+o)B let us )rite do)n t$e list o- attri%utes t$at a student record can contain. For eac$
in-ormationB also list )$at data ty*es )ould %e a**ro*riate to use. For e6am*leB you
donFt )ant to $a!e a data ty*e int -or a studentFs nameB or a 'tring -or a studentFs
grade.
T$e -ollo)ing are some sam*le in-ormation )e )ant to add to t$e student record.
name I 'tring
address I 'tring
age I int
mat$ grade I dou%le
englis$ grade I dou%le
science grade I dou%le
a!erage grade I dou%le
Eou can add more in-ormation i- you )ant toB itFs all really u* to you. But -or t$is
e6am*leB )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 classB let us no) add
t$em to our code. 'ince )e )ant t$ese attri%utes to %e uni?ue -or eac$ o%Dect 4or -or
eac$ student9B )e s$ould declare t$em as instance !aria%les.
For e6am*leB
)$ereB
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%Dects
cannot access t$ese !aria%les directly. .e )ill co!er more a%out accessi%ility later.
"oding ?uide&ines2
1. 1eclare all your instance $ariables on the top of the class declaration.
2. 1eclare 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.
+. 1eclare instance $ariables as pri$ate so that only class methods can access
them directly.
15.3.2 Class Dariables or Static Dariables
side -rom instance !aria%lesB )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%Dects o- t$e same class. +o) su**oseB )e )ant to :no) t$e total num%er o- student
records )e $a!e -or t$e )$ole classB )e can declare one static !aria%le t$at )ill $old t$is
!alue. =et us call t$is as student1ount.
To declare a static !aria%leB
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 -arB 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(ods
Be-ore )e discuss )$at met$ods )e )ant our class to $a!eB let us -irst ta:e a loo: at t$e
general synta6 -or declaring met$ods.
To declare met$ods )e )riteB
UmodifierS Ureturn2ypeS UnameS(UparameterS* {
UstatementS*
&
)$ereB
amodi-ierV can carry a num%er o- di--erent modi-iers
areturnTy*eV can %e any data ty*e 4including !oid9
anameV can %e any !alid identi-ier
a*arameterV ;;S a*arameterCty*eV a*arameterCnameVXBY
15.%.1 /ccessor met(ods
In order to im*lement enca*sulationB t$at isB )e donFt )ant any o%Dects to Dust access
our data anytimeB )e declare t$e -ields or attri%utes o- our classes as *ri!ate. #o)e!erB
t$ere are times )$erein )e )ant ot$er o%Dects to access *ri!ate data. In order to do t$isB
)e create accessor met$ods.
Accessor methods are used to read !alues -rom class !aria%les 4instance8static9. n
accessor met$od usually starts )it$ a getV/ameO#Instance*ariab&eW, It also returns
a !alue.
For our e6am*leB )e )ant an accessor met$od t$at can read t$e nameB addressB englis$
gradeB mat$ grade and science grade o- t$e student.
+o) letFs ta:e a loo: at one im*lementation o- an accessor met$odB
public class StudentQecord
{
private String name%
7
7
public )tring getBame(+,
return name;
-
&
)$ereB
*u%lic I means t$at t$e met$od can %e called -rom o%Dects outside t$e class
'tring I 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 'tring
get+ame I t$e name o- t$e met$od
49 I t$is means t$at our met$od does not $a!e any *arameters
T$e statementB
return name%
in our *rogram signi-ies t$at it )ill return t$e !alue o- t$e instance !aria%le name to t$e
calling met$od. Ta:e note t$at t$e return ty*e o- t$e met$od s$ould $a!e t$e same data
ty*e as t$e data in t$e return statement. Eou usually encounter t$e -ollo)ing error i- t$e
t)o does not $a!e t$e same data ty*eB
StudentQecord.java7;G7 incompatible types
found 7 int
re@uired7 java.lang.String
return age%
Y
; error
not$er e6am*le o- an accessor met$od is t$e get!erage met$odB
public class StudentQecord
{
private String name%
7
7
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)B )$at i- )e )ant ot$er o%Dects to alter our dataG .$at )e do is )e *ro!ide met$ods
t$at can )rite or c$ange !alues o- our class !aria%les 4instance8static9. .e call t$ese
met$odsB mutator methods, mutator met$od is usuallyu )ritten as
setV/ameO#Instance*ariab&eW,
+o) letFs ta:e a loo: at one im*lementation o- a mutator met$odB
public class StudentQecord
{
private String name%
7
7
public void setBame( )tring temp +,
name = temp;
-
&
)$ereB
*u%lic I means t$at t$e met$od can %e called -rom o%Dects outside t$e class
!oid I imeans t$at t$e met$od does not return any !alue
set+ame I t$e name o- t$e met$od
4'tring tem*9 I *arameter t$at )ill %e used inside our met$od
T$e statementB
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 donFt return !alues. #o)e!erB it contains some *rogram
argument or arguments t$at )ill %e used inside t$e met$od.
15.%.3 Multiple 4eturn statements
Eou can $a!e multi*le return statements -or a met$od as long as t$ey are not on t$e
same %loc:. Eou can also use constants to return !alues instead o- !aria%les.
For e6am*leB consider t$e met$odB
public String get+umber,n'ords( int num {
String default+um = "Kero"%
if( num == ; {
return "one"; //return a constant
&
else if( num == <{
return "t'o"; //return a constant
&
//return a variable
return default+um%
&
15.%.% Static met(ods
For t$e static !aria%le student1ountB )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;
-
&
)$ereB
*u%lic I means t$at t$e met$od can %e called -rom o%Dects outside t$e
class
static I means t$at t$e met$od is static and s$ould %e called %y
ty*ingBX1lass+ameY.Xmet$od+ameY. For e6am*leB in t$is caseB
)e call t$e met$od StudentQecord.getStudent3ount(
int I 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 int
get'tudent1ount I t$e name o- t$e met$od
49 I t$is means t$at our met$od does not $a!e any
*arameters
For no)B get'tudent1ount )ill al)ays return t$e !alue >ero since )e $a!enFt done
anyt$ing yet in our *rogram in order to set its !alue. .e )ill try to c$ange t$e !alue o-
student1ount later on )$en )e discuss constructors.
Coding
<uidelines.
1. =ethod names should start with a S=344
letter.
2. =ethod names should be
$erbs
. 3lways pro$ide documentation before the declaration of the method. >ou can
use <a$adocs style for this. )lease see example.
15.%.* Sample Source Code for Student4ecord class
#ere is t$e code -or our 'tudent"ecord classB
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 get/verage({
double result = C%
result = ( mat!Rrade4englis!Rrade4scienceRrade /F%
return result%
&
/**
* returns t!e number of instances of StudentQecords
*/
public static int getStudent3ount({
return student3ount%
&
&
+o)B $ereFs 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 record
StudentQecord annaQecord = ne# StudentQecord(%
StudentQecord bea!Qecord = ne# StudentQecord(%
StudentQecord crisQecord = ne# StudentQecord(%
//set t!e name of t!e students
annaQecord.set+ame("/nna"%
bea!Qecord.set+ame(":ea!"%
crisQecord.set+ame("3ris"%
//print anna?s name
System.out.println( annaQecord.get+ame( %
//print number of students
System.out.println("3ount="4StudentQecord.getStudent3ount(%
&
&
T$e out*ut o- t$is *rogram isB
/nna
Student 3ount = C
15.* +(e t(is reference
T$e this re-erence is used to access t$e instance !aria%les s$ado)ed %y t$e *arameters.
To understand t$is %etterB letFs ta:e -or e6am*le t$e setge met$od. 'u**ose )e $a!e
t$e -ollo)ing declaration -or setge.
public void set/ge( int age {
age = age% //'QM+R$$$
&
T$e *arameter name in t$is declaration is ageB )$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$odB t$e !alue
o- t$e *arameter age )ill %e used. 'o in t$e statementB
age = age%
)e are Dust assigning t$e !alue o- t$e *arameter age to itsel-J T$is is not )$at )e )ant
to $a**en in our code. In order to correct t$is mista:eB )e use t$e this re-erence. To
use t$e t$is re-erenceB )e ty*eB
t!is.UnameMf2!e,nstanceLariableS
'o -or e6am*leB )e can no) re)rite our code toB
public void set/ge( 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%Dect 'tudent"ecord.
/OTE2 Bou can on&y use the this re#erence #or instance )ariab&es and /OT static
or c&ass )ariab&es,
Introduction to Programming I 160
1601
15.2 Overloading Met(ods
In our classesB )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%ility
is *ossi%le in Ja!aB 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 *arametersB to
$a!e di--erent im*lementations and return !alues o- di--erent ty*es. "at$er t$an in!ent
ne) names all t$e timeB met$od o!erloading can %e used )$en t$e same o*eration $as
di--erent im*lementations.
For e6am*leB in our 'tudent"ecord class )e )ant to $a!e a met$od t$at *rints
in-ormation a%out t$e student. #o)e!erB )e )ant t$e *rint met$od to *rint t$ings
di--erently de*ending on t$e *arameters )e *ass to it. For e6am*leB )$en )e *ass a
'tringB )e )ant t$e *rint met$od to *rint out t$e nameB address and age o- t$e student.
.$en )e *ass 3 dou%le !aluesB )e )ant t$e met$od to *rint t$e studentFs name and
grades.
.e $a!e t$e -ollo)ing o!erloaded met$ods inside our 'tudent"ecord classB
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 sCrade+
System.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%
&
Introduction to Programming I 161
1611
.$en )e try to call t$is in t$e -ollo)ing main met$odB
public static void main( String[] args
{
StudentQecord annaQecord = ne# StudentQecord(%
annaQecord.set+ame("/nna"%
annaQecord.set/ddress(")!ilippines"%
annaQecord.set/ge(;N%
annaQecord.setMat!Rrade(JC%
annaQecord.set0nglis!Rrade(PN.N%
annaQecord.setScienceRrade(;CC%
//overloaded met!ods
annaQecord.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 *rintB
+ame7/nna
/ddress7)!ilippines
/ge7;N
)e )ill $a!e t$e out*ut -or t$e second call to *rintB
+ame7/nna
Mat! Rrade7JC.C
0nglis! Rrade7PN.N
Science Rrade7;CC.C
l)ays remem%er t$at o!erloaded met$ods $a!e t$e -ollo)ing *ro*ertiesB
t$e same name
di##erent parameters
return ty*es can %e di--erent or t$e same
Introduction to Programming I 162
1621
15.6 ,eclaring Constructors
.e $a!e discussed %e-ore t$e conce*t o- constructors. 1onstructors are im*ortant in
instantiating an o%Dect. 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. 1onstructors $a!e t$e same name as the c&ass
2. constructor is Dust li:e an ordinary met$odB $o)e!er only t$e -ollo)ing in-ormation
can %e *laced in t$e $eader o- t$e constructorB
sco*e or accessi%ility identi-ier 4li:e *u%lic...9B constructorFs name and *arameters i- it
$as any.
3. 1onstructors does not ha)e any return )a&ue
0. Bou cannot ca&& a constructor direct&yB it can only %e called %y using t$e ne!
o*erator during class instantiation.
To declare a constructorB )e )riteB
UmodifierS Uclass+ameS (UparameterS* {
UstatementS*
&
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 constructorsB t$en an im*licit
de-ault constructor is created.
For e6am*leB in our 'tudent"ecord classB t$e de-ault constructor )ould loo: li:e t$isB
public StudentQecord(
{
//some code !ere
&
15.6.2 Overloading Constructors
s )e $a!e mentionedB constructors can also %e o!erloadedB -or e6am*leB )e $a!e $ere
-our o!erloaded constructorsB
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 eRrade.
double sRrade{
mat!Rrade = mRrade%
englis!Rrade = eRrade%
scienceRrade = sRrade%
&
Introduction to Programming I 163
1631
15.6.3 :sing Constructors
To use t$ese constructorsB )e $a!e t$e -ollo)ing codeB
public static void main( String[] args
{
//create t!ree objects for Student record
StudentQecord annaQecord=ne# StudentQecord("/nna"%
StudentQecord bea!Qecord=ne# StudentQecord(":ea!".
")!ilippines"%
StudentQecord crisQecord=ne#
StudentQecord(JC.PC.;CC%
//some code !ere
&
+o)B %e-ore )e mo!e onB let us go %ac: to t$e static !aria%le student1ount )e $a!e
declared a )$ile ago. T$e *ur*ose o- t$e student1ount is to count t$e num%er o- o%Dects
t$at are instantiated )it$ t$e class 'tudent"ecord. 'oB )$at )e )ant to do $ere isB
e!erytime an o%Dect o- class 'tudent"ecord is instantiatedB )e increment t$e !alue o-
student1ount. good location to modi-y and increment t$e !alue o- student1ount is in
t$e constructorsB %ecause it is al)ays called e!erytime an o%Dect is instantiated. For
e6am*leB
public StudentQecord({
//some initialiKation code !ere
student6ount++; 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 eRrade.
double sRrade{
mat!Rrade = mRrade%
englis!Rrade = eRrade%
scienceRrade = sRrade%
student6ount++; 77add a student
&
Introduction to Programming I 160
1601
15.6.% +(e t(isFG Constructor Call
1onstructor calls can %e c$ainedB meaningB you can call anot$er constructor -rom inside
anot$er constructor. .e use t$e this67 call -or t$is. For e6am*leB gi!en t$e -ollo)ing
codeB
;7 public StudentQecord({
<7 t!is("some string"%
F7
G7 &
N7
I7 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!eB )$en t$e statement at line 13 is calledB it )ill call t$e de-ault
constructor line 1. .$en statement in line 2 is e6ecutedB it )ill t$en call t$e constructor
t$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 callB 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.
Introduction to Programming I 16,
16,1
15.@ $ac8ages
Pac: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!enient
mec$anism -or managing a large grou* o- classes and inter-aces )$ile a!oiding *otential
naming con-licts.
[email protected] Importing $ac8ages
To %e a%le to use classes outside o- t$e *ac:age you are currently )or:ing inB you need
to im*ort t$e *ac:age o- t$ose classes. By de-aultB all your Ja!a *rograms im*ort t$e
Da!a.lang.U *ac:ageB t$at is )$y you can use classes li:e 'tring and Integers inside t$e
*rogram e!ent$oug$ you $a!enFt im*orted any *ac:ages.
T$e synta6 -or im*orting *ac:ages is as -ollo)sB
import UnameOfPackage>%
For e6am*leB i- you )ant to use t$e class 1olor inside *ac:age a)tB you $a!e to ty*e t$e
-ollo)ingB
import java.a#t.3olor%
import java.a#t.*%
T$e -irst statement im*orts t$e s*eci-ic class 1olor )$ile t$e ot$er im*orts all o- t$e
classes in t$e Da!a.a)t *ac:age.
not$er )ay to im*ort classes -rom ot$er *ac:ages is t$roug$ e6*licit *ac:age
re-erencing. T$is is done %y using t$e *ac:age name to declare an o%Dect o- a class.
java.a#t.3olor color%
[email protected] Creating #our o!n pac8ages
To create our o)n *ac:ageB )e )riteB
pac-age Upac-age+ameS%
'u**ose )e )ant to create a *ac:age )$ere )e )ill *lace our 'tudent"ecord classB
toget$er )it$ ot$er related classes. .e )ill call our *ac:ageB sc$ool1lasses.
T$e -irst t$ing you $a!e to do is create a -older named sc$ool1lasses. 1o*y all t$e
classes t$at you )ant to %elong to t$is *ac:age inside t$is -older. -ter co*yingB add t$e
-ollo)ing code at t$e to* o- t$e class -ile. For e6am*leB
pac3age school6lasses;
public class StudentQecord
{
private String name%
private String address%
private int age%
7
Pac:ages can also %e nested. In t$is caseB t$e Ja!a inter*reter e6*ects t$e directory
structure containing t$e e6ecuta%le classes to matc$ t$e *ac:age $ierarc$y.
Introduction to Programming I 166
1661
[email protected] Setting t(e C&/SS$/+
+o)B su**ose )e *lace t$e *ac:age sc$ool1lasses under t$e 1;_ directory. .e need to
set t$e class*at$ to *oint to t$at directory so t$at )$en )e try to run itB t$e JV( )ill %e
a%le to see )$ere our classes are stored.
Be-ore )e discuss $o) to set t$e class*at$B let us ta:e a loo: at an e6am*le on )$at )ill
$a**en i- )e donFt set t$e class*at$.
'u**ose )e com*ile and t$en run t$e 'tudent"ecord class )e )rote in t$e last sectionB
376sc!ool3lassesSjavac StudentQecord.java
376sc!ool3lassesSjava StudentQecord
05ception in t!read "main" java.lang.+o3lassEef9ound0rror7
StudentQecord (#rong name7 sc!ool3lasses/StudentQecord
at java.lang.3lassToader.define3lass;(+ative Met!od
at java.lang.3lassToader.define3lass(`n-no#n Source
at java.security.Secure3lassToader.define3lass(`n-no#n
Source
Met!od
Source
Source
at java.net.`QT3lassToader.define3lass(`n-no#n Source
at java.net.`QT3lassToader.accessa;CC(`n-no#n Source
at java.net.`QT3lassToadera;.run(`n-no#n Source
at java.security./ccess3ontroller.do)rivileged(+ative
at java.net.`QT3lassToader.find3lass(`n-no#n Source
at java.lang.3lassToader.load3lass(`n-no#n Source
at sun.misc.Taunc!era/pp3lassToader.load3lass(`n-no#n
at java.lang.3lassToader.load3lass(`n-no#n Source
at java.lang.3lassToader.load3lass,nternal(`n-no#n
.e encounter a /o"&ass$e#FoundError )$ic$ means t$at Ja!a did not :no) )$ere to
loo: -or your class. T$e reason -or t$is is t$at your class 'tudent"ecord no) %elongs to a
*ac:age named student1lasses. I- )e )ant to run our classB )e Da!e to tell Ja!a a%out
its -ull class name )$ic$ is schoo&"&asses,StudentRecord. .e also $a!e to tell JV(
)$ere to loo: -or our *ac:agesB )$ic$ in t$is case is in location 1;_. To do t$isB )e must
set t$e class*at$.
To set t$e class*at$ in .indo)sB )e ty*e t$is at t$e command *rom*tB
376sc!ool3lassesS set classpath=6"\
)$ere 1;_ is t$e directory in )$ic$ )e $a!e *laced t$e *ac:ages. -ter setting t$e
class*at$B )e can no) run our *rogram any)$ere %y ty*ingB
376sc!ool3lassesS java school6lasses*)tudent%ecord
For 3ni6 %ase systemsB su**ose )e $a!e our classes in t$e directory
8usr8local8my1lassesB )e )riteB
e5port classpat!=/usr/local/my3lasses
Ta:e note t$at you can set t$e class*at$ any)$ere. Eou can also set more t$an one
class*at$B )e Dust $a!e to se*arate t$em %y [4-or )indo)s9 and ; 4-or 3ni6 %ased
systems9. For e6am*leB
set classpat!=376my3lasses%E76%076My)rograms6(ava
and -or 3ni6 %ased systemsB
e5port classpat!=/usr/local/java7/usr/my3lasses
15.C /ccess Modifiers
.$en creating our classes and de-ining t$e *ro*erties and met$ods in our classB )e )ant
to im*lement some :ind o- restriction to access t$ese data. For e6am*leB i- you )ant a
certain attri%ute to %e c$anged only %y t$e met$ods inside t$e classB you may )ant to
$ide t$is -rom ot$er o%Dects using your class. In Ja!aB )e $a!e )$at )e call access
modi#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%licB *ri!ateB
*rotected and de-ault. T$e -irst t$ree access modi-iers are e6*licitly )ritten in t$e code to
indicate t$e access ty*eB -or t$e -ourt$ one )$ic$ is de-aultB no :ey)ord is used.
15.C.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 classF
!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 e6am*leB
public class StudentQecord
{
//default access to instance variable
int name%
//default access to met!od
String get+ame({
return name%
&
&
In t$is e6am*leB t$e instance !aria%le name and t$e met$od get+ame49 can %e accessed
-rom ot$er o%DectsB as long as t$e o%Dect %elongs to t$e same *ac:age )$ere t$e class
'tudent"ecord %elongs to.
15.C.2 public access
T$is s*eci-ies t$at class mem%ers are accessi%le to anyoneB %ot$ inside and outside t$e
class. ny o%Dect t$at interacts )it$ t$e class can $a!e access to t$e *u%lic mem%ers o-
t$e class. For e6am*leB
public class StudentQecord
{
//default access to instance variable
public int name%
//default access to met!od
public String get+ame({
return name%
&
&
In t$is e6am*leB t$e instance !aria%le name and t$e met$od get+ame49 can %e accessed
-rom ot$er o%Dects.
15.C.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 and
t$e su%classes o- t$e class. For e6am*leB
public class StudentQecord
{
//default access to instance variable
protected int name%
//default access to met!od
protected String get+ame({
return name%
&
&
In t$is e6am*leB t$e instance !aria%le name and t$e met$od get+ame49 can %e accessed
only -rom met$ods inside t$e class and -rom su%classes o- 'tudent"ecord. .e )ill
discuss a%out su%classes on t$e ne6t c$a*ter.
15.C.% 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-ined
in. For e6am*leB
public class StudentQecord
{
//default access to instance variable
private int name%
//default access to met!od
private String get+ame({
return name%
&
&
In t$is e6am*leB t$e instance !aria%le name and t$e met$od get+ame49 can %e accessed
only -rom met$ods inside t$e class.
Coding <uidelines.
The instance $ariables of a class should normally be declared pri$ateB and the class
will <ust pro$ide accessor and mutator methods to these $ariables.
Introduction to Programming I 1H0
1H01
15.15 0-ercises
15.15.1 /ddress Boo8 0ntr#
Eour tas: is to create a class t$at contains an address %oo: entry. T$e -ollo)ing ta%le
descri%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 PersonFs Email address
Table 21: 3ttributes and 3ttributes 1escriptions
For t$e met$odsB create t$e -ollo)ing;
1. Pro!ide t$e necessary accessor and mutator met$ods -or all t$e attri%utes.
2. 1onstructors
15.15.2 /ddressBoo8
1reate a class address %oo: t$at can contain 100 entries o- ddressBoo:Entry o%Dects
4use t$e class you created in t$e -irst e6ercise9. Eou s$ould *ro!ide t$e -ollo)ing
met$ods -or t$e address %oo:.
1. dd entry
2. Delete entry
3. Vie) all entries
0. 3*date an entry
Introduction to Programming I 1H1
1H11
++ Inheritance> Po&ymorphism and
Inter#aces
11.1 Objectives
In t$is sectionB )e )ill %e discussing on $o) a class can in$erit t$e *ro*erties o- an
e6isting class. class t$at does t$is is called a su%class and its *arent class is called t$e
su*erclass. .e )ill also %e discussing a s*ecial *ro*erty o- Ja!a )$erein it can
automatically a**ly t$e *ro*er met$ods to eac$ o%Dect regardless o- )$at su%class t$e
o%Dect came -rom. T$is *ro*erty is :no)n as *olymor*$ism. FinallyB )e are going to
discusss a%out inter-aces t$at $el*s reduce *rogramming e--ort.
t t$e end o- t$e lessonB t$e student s$ould %e a%le to;
De-ine su*er classes and su%classes
&!erride met$ods o- su*erclasses
1reate -inal met$ods and -inal classes
11.2 In(eritance
In Ja!aB all classesB including t$e classes t$at ma:e u* t$e Ja!a PIB are su%classed -rom
t$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$at
class.
Figure 11.1: Class !ierarchy
In$eritance is a maDor ad!antage in o%DectIoriented *rogramming since once a %e$a!ior
4met$od9 is de-ined in a su*erclassB t$at %e$a!ior is automatically in$erited %y all
su%classes. T$usB you can encode a met$od only once and t$ey can %e used %y all
su%classes. su%class only need to im*lement t$e di--erences %et)een itsel- and t$e
*arent.
Introduction to Programming I 1H2
1H21
11.2.1 ,efining Superclasses and Subclasses
To deri!e a classB )e use t$e extends :ey)ord. In order to illustrate t$isB letFs create a
sam*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 get/ddress({
return address%
&
public void set+ame( String name {
t!is.name = name%
&
public void set/ddress( String add {
t!is.address = add%
&
&
+otice t$atB t$e attri%utes name and address are declared as protected. T$e reason )e
did t$is is t$atB )e )ant t$ese attri%utes to %e accessi%le %y t$e su%classes o- t$e
su*erclass. I- )e declare t$is as *ri!ateB t$e su%classes )onFt %e a%le to use t$em. Ta:e
note t$at all t$e *ro*erties o- a su*erclass t$at are declared as pub&ic> protected and
de#au&t can %e accessed %y its su%classes.
Introduction to Programming I 1H3
1H31
+o)B )e )ant to create anot$er class named 'tudent. 'ince a student is also a *ersonB
)e decide to Dust e6tend t$e class PersonB so t$at )e can in$erit all t$e *ro*erties and
met$ods o- t$e e6isting class Person. To do t$isB )e )riteB
public class Student e5tends )erson
{
public Student({
System.out.println(A,nside Student73onstructorB%
//some code !ere
&
// some code !ere
&
.$en a 'tudent o%Dect is instantiatedB t$e de-ault constructor o- its su*erclass is in!o:ed
im*licitly to do t$e necessary initiali>ations. -ter t$atB t$e statements inside t$e
su%class are e6ecuted. To illustrate t$isB consider t$e -ollo)ing codeB
public static void main( String[] args {
Student anna = ne# Student(%
&
In t$e codeB )e create an o%Dect o- class 'tudent. T$e out*ut o- t$e *rogram isB
,nside )erson73onstructor
,nside Student73onstructor
T$e *rogram -lo) is s$o)n %elo).
Figure 11.2: )rogram Flow
Introduction to Programming I 1H0
1H01
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 e6ecution o- rele!ant constructor -rom t$e su*erclassB %ased on
t$e arguments *assed.
For e6am*leB gi!en our *re!ious e6am*le classes Person and 'tudentB )e s$o) an
e6am*le o- a su*er constructor call. @i!en t$e -ollo)ing code -or 'tudentB
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 and
e6ecutes it. not$er sam*le code s$o)n %elo)B
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 and
e6ecutes 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 (3'T &113" T#E FI"'T 'TTE(E+T I+ 1&+'T"31T&".
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 1++&T B&T# &113" I+
T#E '(E 1&+'T"31T&".
not$er use o- su*er is to re-er to mem%ers o- t$e su*erclass 4Dust li:e t$e this
re-erence 9. For e6am*leB
public Student(
{
super*name = DsomenameE;
super*address = Dsome addressE;
b
Introduction to Programming I 1H,
1H,1
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 certain
met$od -rom t$at o- t$e su*erclassB 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 Person
su*erclassB
public class )erson
Z
7
7
public String get+ame({
System.out.println(")arent7 get+ame"%
return name%
&
7
&
To o!errideB t$e get+ame met$od in t$e su%class 'tudentB )e )riteB
public class Student e5tends )erson
Z
7
7
public String get+ame({
System.out.println("Student7 get+ame"%
return name%
&
7
&
'oB )$en )e in!o:e t$e get+ame met$od o- an o%Dect o- class 'tudentB t$e o!erridden
met$od )ould %e calledB and t$e out*ut )ould %eB
Student7 get+ame
Introduction to Programming I 1H6
1H61
11.2.% 9inal Met(ods and 9inal Classes
In Ja!aB it is also *ossi%le to declare classes t$at can no longer %e su%classed. T$ese
classes are called #ina& c&asses. To declare a class to %e -inalB )e Dust add t$e -inal
:ey)ord in t$e class declaration. For e6am*leB i- )e )ant t$e class Person to %e declared
-inalB )e )riteB
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!ior
cannot %e o!erridden. E6am*les o- t$ese classes are IntegerB 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$ods
are )$at )e call #ina& methods. To declare a met$od to %e -inalB )e Dust add t$e -inal
:ey)ord in t$e met$od declaration. For e6am*leB i- )e )ant t$e get+ame met$od in
class Person to %e declared -inalB )e )riteB
public $inal String get+ame({
return name%
&
'tatic met$ods are automatically -inal. T$is means t$at you cannot o!erride t$em.
Introduction to Programming I 1HH
1HH1
11.3 $ol#morp(ism
+o)B gi!en t$e *arent class Person and t$e su%class 'tudent o- our *re!ious e6am*leB
)e add anot$er su%class o- Person )$ic$ is Em*loyee. Belo) is t$e class $ierarc$y -or
t$atB
Person
'tudent
Em*loyee
Figure 11.: !ierarchy for )erson class and itRs
classes
In Ja!aB )e can create a re-erence t$at is o- ty*e su*erclass to an o%Dect o- its su%class.
For e6am*leB
public static main( String[] args
{
)erson ref%
Student studentMbject = ne# Student(%
0mployee employeeMbject = ne# 0mployee(%
ref = studentMbject% //)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 PersonB and )e o!erride t$is
met$od in %ot$ t$e su%classes 'tudent and Em*loyeeB
public class )erson
{
public String get+ame(
{ System.out.println(A)erson +ame7B 4
name% return name%
&
&
public class Student e5tends )erson
{
public String get+ame(
{ System.out.println(AStudent +ame7B 4
name% return name%
&
&
public class 0mployee e5tends )erson
{
public String get+ame(
{ System.out.println(A0mployee +ame7B 4
name% return name%
&
&
Introduction to Programming I 1H7
1H71
@oing %ac: to our main met$odB )$en )e try to call t$e get+ame met$od o- t$e
re-erence Person re-B t$e get+ame met$od o- t$e 'tudent o%Dect )ill %e called. +o)B i-
)e assign re- to an Em*loyee o%DectB t$e get+ame met$od o- Em*loyee )ill %e called.
public static main( String[] args
{
)erson ref%
Student studentMbject = ne# Student(%
0mployee employeeMbject = ne# 0mployee(%
ref = studentMbject% //)erson reference points to a
// Student object
)tring temp = re$*getBame(+; 77getBame o$ )tudent
77class is called
)ystem*out*println( temp +;
ref = employeeMbject% //)erson reference points to an
// 0mployee object
)tring temp = re$*getBame(+; 77getBame o$ 0mployee
77class is called
)ystem*out*println( temp +;
&
T$is a%ility o- our re-erence to c$ange %e$a!ior according to )$at o%Dect it is $olding is
called po&ymorphism. Polymor*$ism allo)s multi*le o%Dects o- di--erent su%classes to
%e treated as o%Dects o- a single su*erclassB )$ile automatically selecting t$e *ro*er
met$ods to a**ly to a *articular o%Dect %ased on t$e su%class it %elongs to.
not$er e6am*le t$at e6$i%its t$e *ro*erty o- *olymor*$ism is )$en )e try to *ass a
re-erence to met$ods. 'u**ose )e $a!e a static met$od printIn#ormation t$at ta:es in
a Person o%Dect as re-erenceB )e can actually *ass a re-erence o- ty*e Em*loyee and
ty*e 'tudent to t$is met$od as long as it is a su%class o- t$e class Person.
public static main( String[] args
{
Student studentMbject = ne# Student(%
0mployee employeeMbject = ne# 0mployee(%
print&n$ormation( student/bect +;
print&n$ormation( employee/bect +;
&
public static print&n$ormation( Ferson p +{
. . . .
&
Introduction to Programming I 1H<
1H<1
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*lementationB and some met$ods )$erein )e Dust )ant to %e
o!erridden %y its su%classes.
For e6am*leB )e )ant to create a su*erclass named =i!ingT$ing. T$is class $as certain
met$ods li:e %reat$B eatB slee* and )al:. #o)e!erB t$ere are some met$ods in t$is
su*erclass )$erein )e cannot generali>e t$e %e$a!ior. Ta:e -or e6am*leB t$e )al:
met$od. +ot all li!ing t$ings )al: t$e same )ay. Ta:e t$e $umans -or instanceB )e
$umans )al: on t)o legsB )$ile ot$er li!ing t$ings li:e dogs )al: on -our legs. #o)e!erB
t$ere are many c$aracteristics t$at li!ing t$ings $a!e in commonB t$at is )$y )e )ant to
create a general su*erclass -or t$is.
Figure 11.%: 3bstract class
In order to do t$isB )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%DectIoriented *rogramming class $ierarc$yB de-ining t$e %road ty*es o- actions
*ossi%le )it$ o%Dects 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 called
abstract methods. To create an a%stract met$odB Dust )rite t$e met$od declaration
)it$out t$e %ody and use t$e a%stract :ey)ord. For e6am*leB
public abstract void someMet!od(%
Introduction to Programming I 170
1701
+o)B letFs create an e6am*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..."%
&
7HH
H abstract method 'al3
H Ie 'ant this method to be overridden by subclasses o$
H .ivingGhing
H7
public abstract void 'al3(+;
&
.$en a class e6tends t$e =i!ingT$ing a%stract classB it is re?uired to o!erride t$e
a%stract met$od )al:49B or elseB t$at su%class )ill also %ecome an a%stract classB and
t$ere-ore cannot %e instantiated. For e6am*leB
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$odB )e )ould encounter t$e -ollo)ing
error messageB
Human.java7;7 Human is not abstract and does not override
abstract met!od #al-( in Tiving2!ing
public 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<ect:oriented
programming class hierarchyB and use its subclasses to pro$ide implementation
details of the abstract class.
Introduction to Programming I 171
1711
11.* Interfaces
n 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$ey
allo) classesB regardless o- t$eir location in t$e class $ierarc$yB to im*lement common
%e$a!iors. +ote t$at inter-aces e6$i%it *olymor*$ism as )ellB since *rogram may call an
inter-ace met$od and t$e *ro*er !ersion o- t$at met$od )ill %e e6ecuted de*ending on
t$e ty*e o- o%Dect *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-acesB )e can actually ca*ture similarities among unrelated classes )it$out
arti-icially -orcing a class relations$i*.
=etFs ta:e as an e6am*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%Dect to o%Dects o- t$e same class. +o)B su**ose )e
$a!e anot$er class MyInteger )$ic$ contains met$ods t$at com*ares a MyInteger
o%Dect to o%Dects o- t$e same class. s )e can see $ereB %ot$ o- t$e classes $a!e some
similar met$ods )$ic$ com*ares t$em -rom ot$er o%Dects o- t$e same ty*eB %ut t$ey are
not related )$atsoe!er. In order to en-orce a )ay to ma:e sure t$at t$ese t)o classes
im*lement some met$ods )it$ similar signaturesB )e can use an inter-ace -or t$is. .e
can create an inter-ace classB letFs say inter-ace Re&ation )$ic$ $as some com*arison
met$od declarations. &ur inter-ace "elation can %e declared asB
public interface Qelation
{
public boolean isRreater( Mbject a. Mbject b%
public boolean isTess( Mbject a. Mbject b%
public boolean is0@ual( Mbject a. Mbject b%
&
not$er reason -or using an o%DectFs *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 section
6nterface $s. ClassesB )e can actually use an inter-ace as data ty*e.
FinallyB )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!aB %ut *resent
in ot$er o%DectIoriented languages li:e 1KK.
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 %odyB an inter-ace can only de-ine constants and an inter-ace
$a!e no direct in$erited relations$i* )it$ any *articular classB t$ey are de-ined
inde*endently.
Introduction to Programming I 172
1721
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$is
means t$at an inter-ace can %e used in *laces )$ere a class can %e used. For e6am*leB
gi!en a class Person and an inter-ace PersonInter-aceB t$e -ollo)ing declarations are
!alid;
)erson,nterface pi = ne# )erson(%
)erson pc = ne# )erson(%
#o)e!erB you cannot create an instance -rom an inter-ace. n e6am*le o- t$is
is;
)erson,nterface pi = ne# )erson,nterface(% //3MM),T0
//0QQMQ$$$
not$er common c$aracteristic is t$at %ot$ inter-ace and class can de-ine met$ods.
#o)e!erB 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-aceB )e )riteB
public interface [,nterface+ame]
{
//some met!ods #it!out t!e body
&
s an e6am*leB letFs create an inter-ace t$at de-ines relations$i*s %et)een t)o o%Dects
according to t$e Pnatural orderQ o- t$e o%Dects.
public interface Qelation
{
public boolean isRreater( Mbject a. Mbject b%
public boolean isTess( Mbject a. Mbject b%
public boolean is0@ual( Mbject a. Mbject b%
&
+o)B to use t$e inter-aceB )e use t$e imp&ements :ey)ord. For e6am*leB
/**
* 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!({
Introduction to Programming I 173
1731
double lengt! = Mat!.s@rt((5<H5;*(5<H5; 4
(y<Hy;* (y<Hy;%
return lengt!%
&
public boolean isRreater( Mbject a. Mbject b{
double aTen = ((Tinea.getTengt!(%
double bTen = ((Tineb.getTengt!(%
return (aTen S bTen%
&
public boolean isTess( Mbject a. Mbject b{
double aTen = ((Tinea.getTengt!(%
double bTen = ((Tineb.getTengt!(%
return (aTen U bTen%
&
public boolean is0@ual( Mbject a. Mbject b{
double aTen = ((Tinea.getTengt!(%
double bTen = ((Tineb.getTengt!(%
return (aTen == bTen%
&
&
.$en your class tries to im*lement an inter-aceB al)ays ma:e sure t$at you im*lement
all t$e met$ods o- t$at inter-aceB or elseB you )ould encounter t$is errorB
Tine.java7G7 Tine is not abstract and does not override
abstract met!od isRreater(java.lang.Mbject.java.lang.Mbject in
Qelation
public 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 to
manipulate all of the classes that implement the interface.
Introduction to Programming I 170
1701
11.*.* 4elations(ip of an Interface to a Class
s )e $a!e seen in t$e *re!ious sectionB 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$atB a class can
only E/TE+D &+E su*er classB %ut it can I(P=E(E+T (+E inter-aces. n e6am*le o- a
class t$at im*lements many inter-aces isB
public class )erson implements )erson,nterface.
Tiving2!ing.
'!atever,nterface {
//some code !ere
&
not$er e6am*le o- a class t$at e6tends one su*er class and im*lements an inter-ace isB
public class 3omputerScienceStudent e5tends Student
implements )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. 3nrelated
classes can im*lement t$e same inter-ace.
11.*.2 In(eritance among Interfaces
Inter-aces are not *art o- t$e class $ierarc$y. #o)e!erB inter-aces can $a!e in$eritance
relations$i* among themsel$es. For e6am*leB su**ose )e $a!e t)o inter-aces
StudentInter#ace and PersonInter#ace. I- 'tudentInter-ace e6tends PersonInter-aceB
it )ill in$erit all o- t$e met$od declarations in PersonInter-ace.
public interface )erson,nterface {
. . .
&
public interface Student,nterface e5tends )erson,nterface {
. . .
&
Introduction to Programming I 17,
17,1
11.2 0-ercises
11.2.1 0-tending Student4ecord
In t$is e6erciseB )e )ant to create a more s*eciali>ed student record t$at contains
additional in-ormation a%out a 1om*uter 'cience student. Eour tas: is to e6tend t$e
'tudent"ecord class t$at )as im*lemented in t$e *re!ious lessons. dd some attri%utes
and met$ods t$at you t$in: are needed -or a 1om*uter 'cience student record. Try to
o!erride some e6isting met$ods in t$e su*erclass 'tudent"ecordB i- you really need to.
11.2.2 +(e S(ape abstract class
Try to create an a%stract class called '$a*e )it$ a%stract met$ods getrea49 and
get+ame49. .rite t)o o- its su%classes 1ircle and '?uare. Eou can add additional
met$ods to its su%classes i- you )ant to.
Introduction to Programming I 176
1761
+. 0asic Exception and&ing
12.1 Objectives
In t$is sectionB )e are going to study a tec$ni?ue used in Ja!a to $andle unusual
conditions t$at interru*t t$e normal o*eration o- t$e *rogram. T$is tec$ni?ue is called
exception hand&ing.
t t$e end o- t$e lessonB t$e student s$ould %e a%le to;
De-ine e6ce*tions
#andle e6ce*tions using a sim*le tryIcatc$I-inally %loc:
12.2 '(at are 0-ceptions)
n e6ce*tion is an e!ent t$at interru*ts t$e normal *rocessing -lo) o- a *rogram. T$is
e!ent is usually some error o- some sort. T$is causes our *rogram to terminate
a%normally.
'ome e6am*les o- e6ce*tions t$at you mig$t $a!e encountered in our *re!ious e6ercises
are; rrayInde6&ut&-Bounds e6ce*tionsB )$ic$ occurs i- )e try to access a nonIe6istent
array elementB or may%e a +um%erFormatE6ce*tionB )$ic$ occurs )$en )e try to *ass
as a *arameter a nonInum%er in t$e Integer.*arseInt met$od.
12.3 andling 0-ceptions
To $andle e6ce*tions in Ja!aB )e use a tryIcatc$I-inally %loc:. .$at )e do in our
*rograms is t$at )e *lace t$e statements t$at can *ossi%ly generate an e6ce*tion inside
t$is %loc:.
T$e general -orm o- a tryIcatc$I-inally %loc: isB
try{
&
//#rite t!e statements t!at can generate an e5ception
//in t!is bloc-
catc!( Ue5ception2ype
;
S Uvar+ame
;
S {
&
. . .
//#rite t!e action your program #ill do if an e5ception
//of a certain type occurs
catc!( Ue5ception2ype
n
S Uvar+ame
n
S {
//#rite t!e action your program #ill do if an
//e5ception of a certain type occurs
&
finally{
//add more cleanup code !ere
&
E6ce*tions t$ro)n during e6ecution o- t$e try %loc: can %e caug$t and $andled in a
catc$ %loc:. T$e code in t$e -inally %loc: is al)ays e6ecuted.
T$e -ollo)ing are t$e :ey as*ects a%out t$e synta6 o- t$e tryIcatc$I-inally construct;
T$e %loc: notation is mandatory.
For eac$ try %loc:B t$ere can %e one or more catc$ %loc:sB %ut only one -inally %loc:.
T$e catc$ %loc:s and -inally %loc:s must al)ays a**ear in conDunction )it$ t$e try
%loc:B and in t$e a%o!e order.
try %loc: must %e -ollo)ed %y at &east one catc$ %loc: &" one -inally %loc:B or %ot$.
Eac$ catc$ %loc: de-ines an e6ce*tion $andle. T$e $eader o- t$e catc$ %loc: ta:es
e6actly one argumentB )$ic$ is t$e e6ce*tion its %loc: is )illing to $andle. T$e
e6ce*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 try:catch:finally bloc;
=etFs ta:e -or e6am*le a code t$at *rints t$e second argument )$en )e try to run t$e
code using commandIline arguments. 'u**oseB t$ere is no c$ec:ing inside your code -or
t$e num%er o- arguments and )e Dust access t$e second argument argsX1Y rig$t a)ayB
)eFll get t$e -ollo)ing e6ce*tion.
05ception in t!read "main"
java.lang./rray,nde5MutMf:ounds05ception7 ;
at 05ception05ample.main(05ception05ample.java7N
To *re!ent t$is -rom $a**eningB )e can *lace t$e code inside a tryIcatc$ %loc:. T$e
-inally %loc: is Dust o*tional. For t$is e6am*leB )e )onFt 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 argumentsB t$e out*ut )ould %eB
05ception caug!t$
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"]="4
args[i]%
&
&
&
1om*ile and run t$e TestE6ce*tions *rogram. T$e out*ut s$ould loo: li:e t$is;
javac 2est05ceptions one t#o t!ree
args[C]=one
args[;]=t#o
args[<]=t!ree
05ception in t!read "main"
java.lang./rray,nde5MutMf:ounds05ception7 F
at 2est05ceptions.main(;.java7G
(odi-y t$e TestE6ce*tions *rogram to $andle t$e e6ce*tion. T$e out*ut o- t$e *rogram
a-ter catc$ing t$e e6ce*tion s$ould loo: li:e t$is;
javac 2est05ceptions one t#o t!ree
args[C]=one
args[;]=t#o
args[<]=t!ree
05ception caug!t7
java.lang./rray,nde5MutMf:ounds05ception7 F
^uiting...
12.%.2 Catc(ing 0-ceptions 2
1$ances are !ery good t$at some *rograms youF!e )ritten %e-ore $a!e encountered
e6ce*tions. 'ince you didnFt catc$ t$e e6ce*tionsB t$ey sim*ly $alted t$e e6ecution o-
your code. @o %ac: to t$ose *rograms and im*lement e6ce*tion $andling.
Introduction to Programming I 1<0
1<01
Appendix A 2 =a)a and /et0eans Insta&&ation
In t$is sectionB )e )ill discuss on $o) to install Ja!a and +etBeans in your system
43%untu Da**er8.indo)s /P9. I- you are not *ro!ided )it$ t$e Ja!a ,.0 and +etBeans
,., installers %y your instructorB you can do)nload a co*y o- t$e installers -rom t$e 'un
(icrosystems )e%site 4$ tt * ; 8 8 Da ! 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 lo a d s8 -or +etBeans9. Be-ore starting )it$ t$e
installationB co*y t$e installers in your $ard dis: -irst.
For 1buntu $apper2
1o*y all t$e installers inside t$e 8usr -older.
For 'indo!s2
Just co*y t$e installers in any tem*orary directory.
Introduction to Programming I 1<1
1<11
Installing 7ava in :buntu ,apper
Step +2 @o to t$e -older )$ere you $a!e your installers
Step .2 Be-ore running your installerB ma:e sure it is e6ecuta%le. To do t$isB rig$t clic:
on t$e installerB clic: on t$e Permissions ta%B and t$en 1lic: on t$e e6ecute %o6. 1lose
t$e )indo).
Introduction to Programming I 1<2
1<21
Step -2 Dou%le clic: on t$e -ile Dd:I1C,C0C06Ilinu6Ii,76.%in. dialog %o6 )ill dis*layB
clic: on t$e %utton F"un In TerminalF.
-ter *ressing E+TE"B you )ill see t$e license agreement dis*layed on t$e console.
Introduction to Programming I 1<3
1<31
Just *ress enterB until you see t$e ?uestion; Do you agree to t$e a%o!e license termsG
Xyes 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.
Introduction to Programming I 1<0
1<01
Step <2 "reating symbo&ic &in%s
In order to run Da!a commands any)$ereB )e need to create sym%olic lin:s -or all t$e
commands in JDA inside t$e 8usr8local8%in directory. To do t$isB go to t$e
directory;/usr/local/bin. Ty*e; cd /usr/local/bin
Introduction to Programming I 1<,
1<,1
To ma:e t$e sym%olic lin:s to t$e commandsB ty*e;
sudo ln Hs /usr/java/jd-;.N.C\C;/bin/* .
Introduction to Programming I 1<6
1<61
Installing 7ava in 'indo!s
Step +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
J.E.D.I
Introduction to Programming I 1<H
Introduction to Programming I 1<7
1<71
J.E.D.I
Step .2 Run the insta&&er
To run t$e installerB Dust dou%leIclic: on t$e installer icon. J2'E installer dialog )ill
t$en a**ear. 1lic: 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
Introduction to Programming I 1<<
1<<1
J.E.D.I
1lic: on +E/T to continue installation.
Figure 12.%: Custom setup
1lic: on FI+I'# to com*lete installation.
Figure 12.+: Finish installation
Introduction to Programming I 200
2002
J.E.D.I
Installing 1etBeans in :buntu ,apper
Step +2 @o to t$e -older )$ere you $a!e your installers
Introduction to Programming I 201
2012
J.E.D.I
Step .2 Be-ore running your installerB ma:e sure it is e6ecuta%le.
To do t$isB rig$t clic: on t$e installerB clic: on t$e Permissions ta%B and t$en 1lic: on t$e
e6ecute %o6. 1lose t$e )indo).
Step -2 Dou%le clic: on t$e -ile net%eansI,C,I%etaIlinu6.%in. 1lic: on "un in Terminal.
Introduction to Programming I 202
2022
J.E.D.I
+et%eans ,., dialog )ill t$en a**ear. 1lic: on +E/T.
Introduction to Programming I 203
2032
J.E.D.I
1lic: on t$e radio %utton t$at says RI acce*t t$e terms in t$e license agreementR. nd
t$en clic: on +E/T.
For t$e directory nameB c$ange it to; 8usr8Da!a8net%eansI0.0B t$en clic: on +E/T.
Introduction to Programming I 200
2002
J.E.D.I
For t$e JDA directoryB c$oose 8usr8Da!a8Dd:1.,.0C01B and t$en clic: on +E/T.
T$e ne6t dialog Dust s$o)s in-ormation a%out +etBeans t$atyou )ill install. Just clic:
again on +E/T.
Introduction to Programming I 20,
20,2
J.E.D.I
+o)B Dust )ait -or +etBeans to -inis$ its installation. 1lic: on FI+I'# to com*lete t$e
installation.
J.E.D.I
Introduction to Programming I 206
Introduction to Programming I 20H
20H2
J.E.D.I
Step <2 1reating sym%olic lin:s
In order to run +etBeans any)$ereB )e need to create sym%olic lin: -or it. To do t$isB 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 e6ecuta%le %y ty*ing;
sudo ln Hs /!ome/florence/netbeans/bin/netbeans .
+o)B you can run +etBeans in any directory %y ty*ing; netbeans V
Introduction to Programming I 207
2072
J.E.D.I
Installing 1etBeans in 'indo!s
Step +2 1sing 'indo!s Exp&orer> go to the #o&der !here your /et0eans insta&&er
is &ocated
Figure 12.*: "et9eans installer file
Introduction to Programming I 20<
20<2
J.E.D.I
Step .2 Run the insta&&er
To run t$e installerB Dust dou%leIclic: on t$e installer icon. -ter clic:ing on t$e net%eansI
,C,I%etaI%inI)indo)s iconB t$e +etBeans installation )i>ard )ill a**ear. 1lic: on +E/T
to enter installation *rocess.
Figure 12./: "et9eans installation
Introduction to Programming I 210
2102
J.E.D.I
T$e agreement *age )ill t$e a**ear. 1$oose to 11EPT and clic: +E/T to continue.
Figure 12.0: 4icense 3greement
Introduction to Programming I 211
2112
J.E.D.I
T$en you )ill %e gi!en t$e c$oice on )$ic$ directory to *lace t$e +etBeans. Eou can
mo!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
Introduction to Programming I 212
2122
J.E.D.I
+e6t is c$oosing t$e 'tandard Edition JDAs -rom your mac$ine. I- you $a!e -inis$ed
installing Ja!aB t$e Dd:1.,.0C01 c$ould a**ear -rom your c$oices. 1lic: on +E/T to
continue.
Figure 12.1&: Choose 21K to use
Introduction to Programming I 213
2132
J.E.D.I
It )ill t$en in-orm you t$e location and si>e o- +etBeans )$ic$ )ill %e installed to your
mac$ine. 1lic: on +E/T to -inis$ installation.
Figure 12.11: 6nstallation Summary
Introduction to Programming I 210
2102
J.E.D.I
Eou $a!e installed +etBeans on your com*uter. 1lic: on FI+I'# to com*lete installation.
Figure 12.12: Successful installation
Introduction to Programming I 21,
21,2
J.E.D.I
Appendix 02 ?etting to %no! your Programming
En)ironment 6'indo!s (P )ersion7
In t$is sectionB )e )ill %e discussing on $o) to )riteB com*ile and run Ja!a *rograms.
T$ere are t)o )ays o- doing t$isB t$e -irst one is %y using a console and a te6t editor.
T$e second one is %y using +etBeans )$ic$ is an Integrated $e)e&opment
En)ironment or I$E.
n IDE is a *rogramming en!ironment integrated into a so-t)are a**lication t$at
*ro!ides a @3I %uilderB a te6t or code editorB a com*iler and8or inter*reter and a
de%ugger.
Be-ore going into detailsB 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 screen
System.out.println("Hello #orld$"%
&
&
Be-ore )e try to e6*lain )$at t$e *rogram meansB letFs -irst try to )rite t$is *rogram in a
-ile and try to run it.
Introduction to Programming I 216
2162
J.E.D.I
:sing a +e-t 0ditor and
Console
For t$is e6am*leB )e )ill %e using t$e te6t editor R+ote*adR4-or .indo)s9 to edit t$e
Ja!a source code. Eou can use ot$er te6t editors i- you )ant to. Eou )ill also need to
o*en t$e ('ID&' *rom*t )indo) to com*ile and e6ecute your Ja!a *rograms.
Step +2 Start /otepad
To start +ote*ad in .indo)sB clic: on startIV ll ProgramsIV ccessoriesIV +ote*ad.
Figure 12.1%: "otepad 3pplication
Figure 12.1: Clic; on start:Q 3ll )rograms:Q 3ccessories
:Q "otepad
Introduction to Programming I 21H
21H2
J.E.D.I
Step .2 Open the "ommand Prompt !indo!
To o*en t$e ('D&' command *rom*t in .indo)sB clic: on startIV ll *rogramsIV
ccessoriesIV 1ommand Prom*t.
Figure 12.1+: start:Q 3ll programs:Q 3ccessories :Q
Command )rompt
Figure 12.1*: =S1-S Command )rompt
Introduction to Programming I 217
2172
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.Da!aRB and )e )ill %e sa!ing it inside a
-older named (EJVP"&@"('.
To o*en t$e Sa)e dialog %o6B clic: on t$e File menu -ound on t$e menu%ar and t$en
clic: on 'a!e.
Introduction to Programming I 21<
21<2
J.E.D.I
-ter doing t$e *rocedure descri%ed a%o!eB a dialog %o6 )ill a**ear as s$o)n in Figure
%elo).
Figure 12.1/: This 1ialog appears after clic;ing on File :Q Sa$e
1lic: on t$e MB $O"1ME/TS %utton to o*en t$e (y Documents -older )$ere )e )ill %e
sa!ing all your Ja!a *rograms.
Introduction to Programming I 220
2202
J.E.D.I
Figure 12.10: Clic; on the button encircled. This will open your F=y 1ocumentsF
folder
+o)B )eFll create a ne) -older inside t$e (y Documents -older )$ere )e )ill sa!e your
*rograms. .e s$all name t$is -older (EJVP"&@"('. 1lic: on t$e %utton encircled in
t$e -igure %elo) to create t$e -older.
Figure 12.17: Clic;ing on the encircled button will create a "ew Folder.
Introduction to Programming I 221
2212
J.E.D.I
-ter t$e -older is createdB you can ty*e in t$e desired name -or t$is -older. In t$is caseB
ty*e in (EJVP"&@"('B and t$en *ress E+TE".
Introduction to Programming I 222
2222
J.E.D.I
+o) t$at )eF!e created t$e -older )$ere )e )ill sa!e all t$e -ilesB dou%le clic: on t$at
-older to o*en it. Eou )ill see a similar -igure as s$o)n %elo). T$e -older s$ould %e
em*ty -or no) since itFs a ne)ly created -older and )e $a!enFt sa!ed anyt$ing in it yet.
Introduction to Programming I 223
2232
J.E.D.I
+o) clic: on t$e dro* do)n list %o6 R'a!e as ty*eRB so t$at )e can c$oose )$at :ind o-
-ile )e )ant to sa!e. 1lic: on t$e Rll FilesR o*tion.
+o)B in t$e Filename te6t%o6B ty*e in t$e -ilename o- your *rogramB )$ic$ is
R#ello.Da!aRB and t$en clic: on t$e 'VE %utton.
Introduction to Programming I 220
2202
J.E.D.I
+o) t$at youF!e sa!ed your -ileB notice $o) t$e title o- t$e -rame c$anges -rom 3ntitledI
+ote*ad to #ello.Da!aI+ote*ad. Ta:e note t$at i- you )ant to ma:e c$anges in your -ileB
you can Dust edit itB and t$en sa!e it again %y clic:ing on File IV 'a!e.
Introduction to Programming I 22,
22,2
J.E.D.I
Step 42 "ompi&ing your program
+o)B t$e ne6t ste* is to com*ile your *rogram. @o to t$e ('D&' command *rom*t
)indo) )e Dust o*ened a )$ile ago.
Ty*icallyB )$en you o*en t$e command *rom*t )indo)B 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 -olderB ty*e
$IR or dir and t$en *ress E+TE". .$at you )ill see is a list o- -iles and -olders inside
your $ome -older.
Figure 12.2&: 4ist of files and folders shown after executing the command 168.
+o)B you can see $ere t$at t$ere is a -older named R(y DocumentsR )$ere )e created
your (EJVP"&@"(' -older. +o) letFs go inside t$at directory.
Introduction to Programming I 226
2262
J.E.D.I
To go inside a directoryB you ty*e in t$e command; cd @directory nameA, T$e RcdR
command stands -orB c$ange directory. In t$is caseB since t$e name o- our directory is
(y DocumentsB you ty*e in; cd My $ocuments,
Figure 12.21: 6nside the =y 1ocuments folder
+o) t$at you are inside t$e R(y DocumentsR -olderB try ty*ing in t$e RdirR command
againB and tell me )$at you see.
Figure 12.22: The contents of =y 1ocuments
+o) *er-orm t$e same ste*s descri%ed %e-ore to go inside t$e (EJVP"&@"(' -older.
Introduction to Programming I 22H
22H2
J.E.D.I
Figure 12.2: 6nside the =>23?3)8-@83=S folder
&nce inside t$e -older )$ere your Ja!a *rograms areB let us no) start com*iling your
Ja!a *rogram. Ta:e note t$atB 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$atB e6ecute t$e dir command again to see i- your -ile
is inside t$at -older.
To com*ile a Ja!a *rogramB )e ty*e in t$e command; Ca)ac @#i&enameA. 'o in t$is
caseB ty*e in; Ca)ac e&&o,Ca)a,
Figure 12.2%: Compile program by usingthe javac command
During com*ilationB Da!ac adds a -ile to t$e dis: called @#i&enameA,c&ass> or in t$is caseB
e&&o,c&assB )$ic$ is t$e actual %ytecode.
Introduction to Programming I 227
2272
J.E.D.I
Step 82 Running the Program
+o)B assuming t$at t$ere are no *ro%lems during com*ilation 4)eFll e6*lore more o- t$e
*ro%lems encountered during com*ilation in t$e ne6t section9B )e are no) ready to run
your *rogram.
To run your Ja!a *rogramB ty*e in t$e command; Ca)a @#i&ename !ithout the
extensionAB so in t$e case o- our e6am*leB ty*e in; Ca)a e&&o
Eou can see on t$e screen t$at you $a!e Dust run your -irst Ja!a *rogram t$at *rints t$e
messageB R#ello )orldJR.
Figure 12.2+: -utput of the program
Introduction to Programming I 22<
22<2
J.E.D.I
Setting t(e $at(
'ometimesB )$en you try to in!o:e t$e Da!ac or Da!a commandB you encounter t$e
message; UCa)acU is not recogniSed as an interna& or externa& command> operab&e
program or batch #i&e. T$is means t$at eit$er you $a!enFt installed Ja!a in your system
yetB or you $a!e to con-igure t$e *at$ on )$ere t$e Ja!a commands are installed so t$at
your 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 youF!e already installed Ja!a in your systemB try setting t$e PT#
!aria%le to *oint to )$ere t$e Ja!a commands are installed. To do t$isB ty*e in t$e
command; set PATO"2XC.sd%+,<,.Y9<Xbin, T$is )ill tell your system to loo: -or t$e
commands in t$e "2XC.sd%+,<,.Y9<Xbin -olderB )$ic$ is usually t$e de-ault location
)$erein your Ja!a -iles are *laced during installation. -ter doing t$isB you can no) use
t$e Ja!a commands.
Figure 12.2/: Setting the path and running <a$a
Introduction to Programming I 230
2302
J.E.D.I
:sing 1etBeans
+o) t$at )eF!e tried doing our *rograms t$e com*licated )ayB letFs no) see $o) to do
all t$e *rocesses )eF!e descri%ed in t$e *re!ious sections %y using Dust one a**lication.
In t$is *art o- t$e lessonB )e )ill %e using /et0eansB )$ic$ is an Integrated
$e)e&opment En)ironment or I$E. n IDE is a *rogramming en!ironment integrated
into a so-t)are a**lication t$at *ro!ides a @3I %uilderB a te6t or code editorB a com*iler
and8or inter*reter and a de%ugger.
Step +2 Run /et0eans
To run +etBeansB clic: on startIV ll ProgramsIV +etBeans ,., Beta IV +etBeans IDE
Introduction to Programming I 231
2312
J.E.D.I
-ter youF!e o*en +etBeans IDEB you )ill see a gra*$ical user inter-ace 4@3I9 similar to
)$at is s$o)n %elo).
Figure 12.20: "et9eans 61E
Introduction to Programming I 232
2322
J.E.D.I
Step .2 Ma%e a proCect
+o)B letFs -irst ma:e a *roDect. 1lic: on FileIV +e) ProDect.
-ter doing t$isB a +e) ProDect dialog )ill a**ear.
Introduction to Programming I 233
2332
J.E.D.I
+o) clic: on Ja!a **lication and clic: on t$e +E/T %utton.
Introduction to Programming I 230
2302
J.E.D.I
+o)B a +e) **lication dialog )ill a**ear. Edit t$e ProDect +ame *art and ty*e in
R#ello**licationR.
Figure 12.27: Change )ro<ect "ame
Introduction to Programming I 23,
23,2
J.E.D.I
+o) try to c$ange t$e **lication =ocationB %y clic:ing on t$e B"&.'E %utton. Follo)
t$e ste*s descri%ed in t$e *re!ious section to go to your (EJVP"&@"(' -older.
FinallyB on t$e 1reate (ain 1lass te6t-ieldB ty*e in #ello as t$e main classF nameB and
t$en clic: on t$e FI+I'# %utton.
Introduction to Programming I 236
2362
J.E.D.I
Step -2 Type in your program
Be-ore ty*ing in your *rogramB let us -irst descri%e t$e main )indo) a-ter creating t$e
*roDect.
s s$o)n %elo)B +etBeans automatically creates t$e %asic code -or your Ja!a *rogram.
Eou can Dust add your o)n statements to t$e generated code. &n t$e le-t side o- t$e
)indo)B you can see a list o- -olders and -iles t$at +etBeans generated a-ter creating t$e
*roDect. T$is can all %e -ound in your (EJVP"&@"(' -olderB )$ere you set t$e
ProDect location.
+o)B try to modi-y t$e code generated %y +etBeans. Ignore t$e ot$er *arts o- t$e
*rogram -or no)B as )e )ill e6*lain t$e details o- t$e code later. Insert t$e code;
System.out.println("Hello #orld$"%
a-ter t$e statementB 88T&D& code a**lication logic $ere.
Introduction to Programming I 23H
23H2
J.E.D.I
Step <2 "ompi&e your program
+o)B to com*ile your *rogramB Dust clic: on Build IV Build (ain ProDect. &rB you could
also use t$e s$ortcut %utton to com*ile your code.
Figure 12.&: Shortcut button to compile code
Introduction to Programming I 237
2372
J.E.D.I
I- t$ere are no errors in your *rogramB you )ill see a %uild success-ul message on t$e
out*ut )indo).
Figure 12.1: -utput window <ust below the window where you
type your source code
Introduction to Programming I 23<
23<2
J.E.D.I
Step 42 Run your program
To run your *rogramB clic: on "unIV "un (ain ProDect. &r you could also use t$e
s$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
Introduction to Programming I 200
2002
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:B )$erein you can add entries in t$e
*$one%oo:B de&ete entriesB )ie! a&& entries and search -or entries. In !ie)ing all
entriesB t$e user s$ould $a!e a c$oiceB )$et$er to !ie) t$e entries in a&phabetica& order
or in increasing order o- tele*$one num%ers. In searc$ing -or entriesB t$e user s$ould
also $a!e an o*tion to searc$ entries by name or by te&ephone num%ers. In searc$ing
%y nameB t$e user s$ould also $a!e an o*tion i- $e8s$e )ants to searc$ %y -irst name or
last name.
(I+ (E+3
1 I dd *$one%oo: entry
2 I Delete *$one%oo: entry
3 I Vie) all entries
a I al*$a%etical order
% I increasing order o- tele*$one num%ers
0 I 'earc$ entries
a I %y name
% I %y tele*$one num%er
, L euit
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 e6istsB )arn user a%out t$is9
Vie) all entries
Dis*lays all entries in al*$a%etical order
Dis*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
euit
close *$one%oo:
Mac(ine $roblem 2.
Mines!eeper
T$is is a one *layer game o- a sim*li-ied !ersion o- t$e *o*ular com*uter game
mines)ee*er. FirstB t$e user is as:ed i- $e or s$e )ants to *lay on a ,6, grid or 10610
grid. Eou $a!e t)o 2Idimensional arrays t$at contains in-ormation a%out your grid. n
entry in t$e array s$ould eit$er contain a 0 or 1. 1 signi-ies t$at t$ere is a %om% in
t$at locationB and a 0 i- none.
For e6am*leB gi!en t$e array;
int %om%=ist,%y,XYXYSZZ0B 0B 1B 0B 0bB
Z0B 0B 0B 0B 0bB
Z0B 1B 0B 0B 0bB
Z0B 0B 0B 1B 1bB
Z0B 1B 1B 0B 0bb[
@i!en t$e %om% listB )e $a!e 6 %om%s on our list. T$e %om%s are located in 4ro)Bcol9
cellsB 40B29B 42B19B 43B39B 43B09B 40B19 and 40B29.
I- t$e user c$ooses a cell t$at contains a %om%B t$e game ends and all t$e %om%s are
dis*layed. I- t$e user c$ooses a cell t$at does not contain a %om%B a num%er a**ears at
t$at location indicating t$e num%er o- neig$%ors t$at contain %om%s. T$e game s$ould
end )$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.
#ereFs a sam*le out*ut o- t$e gameB gi!en t$e %om%=ist,%y,.
.elcome to (ines)ee*erJ
1$oose si>e o- grid 4Press 1 -or ,6,B Press 2 -or 106109; 1
X Y X Y X Y X Y X Y
X Y X Y X Y X Y X Y
X Y X Y X Y X Y X Y
X Y X Y X Y X Y X Y
X Y X Y X Y X Y X Y
Enter ro) and column o- t$e cell you )ant to o*enXro) colY; 1 1
X Y X Y X Y X Y X Y
X Y X2Y X Y X Y X Y
X Y X Y XY X Y X Y
X Y X Y X Y X Y X Y
X Y X Y X Y X Y X Y
Enter ro) and column o- t$e cell you )ant to o*enXro) colY; 3 2
X Y X Y X Y X Y X Y
X Y X2 Y X Y XY X Y
X Y X Y X Y X Y X Y
X Y X Y X0 Y X Y X Y
X Y X Y X Y X Y X Y
Enter ro) and column o- t$e cell you )ant to o*enXro) colY; 0 2
XY X Y X Y X Y X Y
X Y X2Y X Y XY X Y
X Y X/ Y X Y X Y X Y
X Y X Y X0Y X Y X Y
X Y X Y X Y X Y X Y
&o***sJ Eou ste**ed on a %om%. 'orryB game o!erJ
Mac(ine $roblem 3. 1umber
Conversion
1reate your o)n scienti-ic calculator t$at )ill con!ert t$e in*utted num%ers to t$e -our
num%er re*resentations 4 DecimalB BinaryB &ctalB #e6adecimal 9. Eour *rogram s$ould
out*ut t$e -ollo)ing menu on screen.
(I+ (E+3;
Please ty*e t$e num%er o- your c$oice;
1 L Binary to Decimal
2 L Decimal to &ctal
3 L &ctal to #e6adecimal
0 L #e6adecimal to Binary
, L euit
T$e -ollo)ing )ill a**ear )$en one o- t$e c$oices in t$e main menu is c$osen.
1$oice 1;
Enter a %inary num%er; 11000
11000 %ase 2 S 20 %ase 10
4goes %ac: to main menu9
1$oice 2;
Enter a Decimal num%er; 20
20 %ase 10 S 30 %ase 7
4goes %ac: to main menu9
1$oice 3;
Enter an &ctal num%er; 30
30 %ase 7 S 17 %ase 16
4goes %ac: to main menu9
1$oice 0;
Enter a #e6adecimal num%er; 17
17 %ase 16 S 11000 %ase 2
1$oice 1;
Enter a %inary num%er; 110
In!alid %inary num%erJ
Enter a %inary num%er; 1
1 %ase 2 S 1 %ase 10
4goes %ac: to main menu9
4user c$ooses ,9
@ood%yeJ
Eou can %e more creati!e )it$ your user inter-ace i- you )ant toB as long as t$e *rogram
out*uts t$e correct con!ersion o- num%ers.
Re#erences
1. Programming =anguage. From .i:i*edia at
$ tt * ; 88 e n . ) i: i * ed ia . 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 ia .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
3. Programming =anguage. From ns)ers.com at
$ tt * ; 88 ))) .a n s ) er s .c o m8t o * i c 8* r og r a mm in g I la n g u a g e
0. #ig$I=e!el Programming =anguage. From .i:i*edia at
$ tt * ; 88 e n . ) i: i * ed ia . o r g8 ) i : i8 # i g $ I le ! e l C * ro g r a m mi ng Cl a n g u a g e
,. De-ining Flo)c$art 'ym%ols. !aila%le at
$ tt * ; 88 ))) .* a tt o n I
* a t ton . c o m8 % a s i c C - lo ) C c $ a rt C sy m% o ls . $t m
6. Integrated De!elo*ment En!ironment. From .e%o*edia at
$ tt * ; 88 ))) .) e%o*e d ia .c om 8 T E" ( 8 I8 in te g r a ted C de ! e l o * m e n t C e n ! ir o n m e n t .$ tm l
H. Varia%les and E6*ressions. !aila%le at
$ tt * ; 88 ))) .geo c it ie s .c o m8 'ili c o nV a ll e y 8 P a r: 8 32 3 0 8 D a!a 8 D a ! l1 0 0 2 . $ tm l
7. .riting %stract 1lasses and (et$ods. !aila%le at
$ tt * ; 8 8 Da ! a .s un . c o m 8d o c s 8 % o o : s 8t u to r ia l8 Da!a 8D a!a & &8 a % s tr ac t.$ tm l
<. De-ining an Inter-ace. !aila%le at
$ tt * ; 8 8 Da ! a .s un . c o m 8d o c s 8 % o o : s 8t u to r ia l8 Da!a 8in ter * ac: 8 in te r -a c e D e -.$ tm l
20.In$eritance and Polymor*$ism. !aila%le at
$ tt * ; 88 $ o m e. c o ge c o .ca 8 W ! e 3ll 8 D a tu to rH .$ tm
21.T$e Essence o- &&P using Ja!aB "untime Polymor*$ism t$roug$ In$eritance.
!aila%le at $ tt *; 88))).de !e lo *er.com8 te c$8ar ti cl e. *$* 8< 730 71
22.@ary B. '$ellyB T$omas J. 1as$manB Joy =. 'tar:s. Java Programming Complete Concepts
and Techniques. Course Technology Thomson Learning. 2!.
2".#tephen J. Chapman. Java $or Engineers and #cientists 2
nd
Edition. Pearson Prentice %all. 2&
2&.'eitel ( 'eitel. Java %o) to Program *
th
Edition.
2*.#un Java Programming #tudent +uide #L,2-*. #un .icrosystems. Fe/ruary 2!.
20.'oes Java pass /y re$erence or pass /y value1 2hy can3t you s)ap in Java1 4vaila/le
at h ttp 566)) ) .7a v a ) or ld .c o m 67 a v a ) or ld 67 a v a q a 62 ,* 6 " ,q a ,*2 0, pa ss. h t m l
2-.Java 8ranching #tatements. 4vaila/le at
h ttp 5667 a v a .s u n .c o m 6do cs 6/o o 9 s 6tu to ria l67 a v a 6n u ts an d /o lts 6/ ra n c h .h tm l
.
2:.Encapsulation. 4vaila/le at h ttp 566h o m e .c o g e c o .c a 6; v e" ll 67a tu to r& .h tm .