Sie sind auf Seite 1von 62

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES P"ELIM PE"I!$ C%apter &: Java !

vervie' Java is high-level, object-oriented programming language, similar to !! but simpli"ied to eliminate "eatures that cause programming errors# $he Java source code "iles %"iles &' #java e(tensions) are compiled into a "ormat called b*te code %"iles &' #class e(tensions), &'c can then be e(ecuted b* a Java +nterpreter# A (rie) *i+tor, o) Java: Java language, originall* called the A,, &as developed b* -./ 0+ R1-Y-$E02s Engr# James 3osling# $he language &as intended "or use in -un2s project research to &or4 on programming so"t&are to control consumer electronic device# +nitiall*, the !! language &as used as the brains "or the smart appliances %such as interactive $52s, omniscient ovens, hand-held devices, sel"-top bo(es, and the li4e)# 3osling &as unhapp* &ith the results he &as getting b* &riting programs &ith !!, and so he &as "orced to developed his o&n language that suit his needs# $he language he created &as small in si6e %so it could run on limited memor*), e""icient, reliable, and ver* portable so it could run in an* devices# Java language &as o""iciall* launched in 7889# +t &as modi"ied to ta4e advantage o" the :orld :ide :eb# $he :eb Runner %later named as ;ot Java) &as the ver* 7st &eb bro&ser created in Java# +n 7889, the /etscape /avigator +nternet Bro&ser &as also developed to support Java# -eature+ o) Java: 7) -imple, 1bject-oriented, and <amiliar Java can be programmed &ith out e(tensible programmer training &hile being attuned to current so"t&are practices# $he needs o" distributed, client-server based s*stems coincide &ith the encapsulated, message-passing paradigms o" object-based so"t&are#

=) Robust and -ecure +t provides e(tensive compile-time chec4ing, "ollo&ed b* a second level o" run-time chec4ing# Java technolog* is designed to operate in distributed environments, &hich means that securit* is o" paramount importance# Page =

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

<ig# 7#> Java Program ;ello :orld 10P+@ER

+/$ERPRE$ER

;E@@1 :1R@D

;E@@1 :1R@D

;E@@1 :1R@D

Note: Java applications and applets are ver* portable that the* run in an* t*pe o" operating s*stems such as D1-, :indo&s, -olaris, 0a os, ./+?, @inu(, etc# A) Architecture /eutral and Portable Java technolog* is designed to support applications that &ill be deplo*ed into heterogeneous net&or4 environments# $o accommodate the diversit* o" operating environments, the Java computer product generates b*te codes B an architecture neutral intermediate "ormat designed to transport code e""icientl* to multiple hard&are and so"t&are plat"orms# $he interpreted nature o" Java technolog* solves both the binar* distribution problem and the version problem, the same Java programming language b*te codes &ill run on an* plat"orm#

C) ;igh Per"ormance $he automatic garbage collector runs as lo&-priorit* bac4ground thread, ensuring a high probabilit* that memor* is available &hen reDuired, leading to better per"ormance#

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES 9) +nterpreted, $hreaded and D*namic $he Java interpreter can e(ecute Java b*te codes directl* on an* machine to &hich the interpreter and run-time s*stem have been ported# Java technolog* is multithreading capabilit* provides the means to build applications &ith man* concurrent threads o" activit* 0ultithreading ma* results in a high degree o" interactivit* "or the end user# :hile the Java compiler is strict in its compile-time static chec4ing, the language and run-time s*stem are d*namic in their lin4ing stages#

-rom +ource to e.ecuta/le: #%e Java Programming Proce++ m*Program#Java +/$ERPRE$ER

10P+@ER

m*Program#class

0* Program

Note: $he Java source code %#java "ile) is normall* compiled to produce the b*tecodes "ile %#class "ile) that is normall* interpreted b* the Java 5irtual 0achine#

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

Page C JA0A 1E23!"$S $he "ollo&ing are reserved b* the Java @anguage and cannot be used as identi"iers: abstract Boolean Brea4 B*te ase -&itch atch har lass onst continue de"ault do double else e(tends "inal "inall* "loat "or i" implements import instance o" int inter"ace long ne& pac4age private protected public return short static super s*nchroni6ed this thro& thro&s transient tr* void volatile &hile

JA0A $A#A #2PES +#) Primitive 4 built in data t*pes# 5 Categorie+ /umeric 4 integral and "loating point t*pes# Boolean - true ' "alse

JA0A IN#E6"AL #2PES: 7# =# A# C# 9# b*te B represents on integer e(actl* 7 b*te o" storage# short - represents on integer e(actl* = b*te o" storage# int - represents on integer e(actl* C b*te o" storage# long - represents on integer e(actl* E b*te o" storage# char B represents .nicode charactersF reDuires e(actl* = b*tes o" storage#

JA0A -L!A#IN6 #2PES: 7# "loat B represents a "loating point number reDuiring e(actl* C b*tes o" storage#

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES CSCI03: Computer Programming ( Java Application ) Page 9 $*pe Boolean Description +t is a class containing a Boolean "ield used "or &rapping a value o" the primitive t*pe Boolean in an object# +t is a class containing a char "ield used "or &rapping a value o" the primitive t*pe char in an object# ommon 0ethods - boolean value % ), getboolean % ), 5alueo" % ) - char5alue % ), compareto % ), 3ett*pe % ),isDigit% ), is@etter % ), to.ppercase % ), to@o&ercase % ) - double5alue % ), to-tring%), valueo"%), parseDouble % ), - "loat5alue % ), parse"loat % ), tostring%), valueo" %) - int5alue%),parseint%) tostring%), valueo" % ) - longvalue % ), parselong % ), tostring% ),valueo" % ) - charAt % ), compareto%),concat%) length%),starts:ith%) ends:ith%) - binar*search%),"in%) sort%), eDuals%)

haracter

Double

+t is a class containing a double "ield used "or &rapping a value o" the primitive t*pe double in an object# +t is a class containing a "loat "ield used "or &rapping a value o" the primitive t*pe "loat in an object# +t is a class containing an int "ield used "or :rapping a value o" the primitive t*pe int +n an object# +t is a class containing a long "ield used "or :rapping a value o" the primitive t*pe long +n an object# +t represents character strings# All strings +ntends in Java programs, such as GabcH, Are implemented as instances o" this class# +t contains various methods o" manipulating Arra*s%such as -orting and -earching)# +t Also contains a string "actor* that allo&s

<loat

+nteger

@ong

-tring

Arra*s

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page I $*pe 1bject Description +t is the root o" the class hierarch*# Ever* lass has object as a superclass %or parent lass)F and there"ore, all objects, including Arra*s, implement the methods o" the class# ommon 0ethods - done%), eDuals%), "inali6e%),nashcode%) noti"* % ), tostring % )

3"APPE" CLASS B &rapping primitive value to an object# 1bject B contains method "or manipulating a data such as converting a value to another t*pe o" value# E(# string to int int to string %see sample program no# =) lass +nteger @ong <loat Double 0ethod parse+nt %) parse@ong %) parse<loat %) parseDouble %) 1utput +nt long "loat double

Sample Program No &

''displa*ing ;ello Java using s*stem#out#println

lass ;elloJava J public static void main %-tring K L args) J s*stem#out#println %G;ello JavaMH)F N N

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page O Sample Program No 5 ''bu""eredreader command "or input

import java#io#PF public class ;ello Java J public static void main %Arra* K L args) thro&s E(ception J Bu""eredReader br Q ne& Bu""eredReader %ne& +nput-treamReader%s*stem#in) )F string "irstname Q G GF string lastname Q G GF s*stem#out#println %GPlease t*pe *our "irst name:H)F "irstname Q br#readline%)F s*stem#out#println %GPlease t*pe *our last name:H)F lastname Q br#readline%)F s*stem#out#println %G;elloH ! "irstname ! G G ! lastname)F s*stem#out#println %G:elcome to Java ProgrammingMH)F N N Sample program No 3 ''&rapping class program "or int

import java#io#P public class -um+t.o J public static void main %-tring args K L) thro&s E(ception J Bu""eredReader br Q ne& Bu""eredReader %ne& +nput-treamReader%s*stem#in) )F int num7Q>F int num=Q>F int sumQ>F s*stem#out#println %GEnter 7st no:H)F num7Q+nteger#parse+nt%br#readline%))F s*stem#out#println %GEnter =nd no#:H)F num7Q+nteger#parse+nt%br#readline%))F sumQnum7!num=F s*stem#out#println %G$he sum is:H ! sum )F N N

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page E JA0A !PE"A#!"S B special s*mbols used "or mathematical "unctions, some t*pes o" assign and logical statements# Java supports several operators that are "airl* derived "rom and !!# ;o&ever, most Java operators behave di""erentl* "rom the counterparts in other languages# P"ECE$ENCE 7 *IE"A"C*2 !- !PE"A#!"S 8 - ( ) - used to group e(pressions 8 - used to access methods and variables &'in object and classes# 9 : B used "or arra*s# ;; << = in+tance o) - instance o" B returns true or "alse based on &hether the object is an instance o" the named class or an* class subclass# Ne' (t,pe) e.pre++ion < the ne& operator is used "or creating ne& instances o" classes# ( ) B "or casting a value to another t*pe# > 7 ? ;< @@ AA AAA bit&ise le"t and right shi"t, unsigned shi"t right# @ A @B AB relational operator BB =B C A/D CC 1R ?1R DD @ogical 1R E: conditional B ;B <Q PQ various ' combined operators 7B ? C!NS#AN#S B a variable &ith a value that never changes# E(# -*nta(: "inalRt*peSRvar#nameSQRvalueSF "inal "loat P7 Q A#7C798=F <inal Boolean DEB.3Q"alseF 9: ()

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page 8 JA0A 6UI $he java#a&t pac4age contains integrated set o" classes and inter"aces that provide components "or creating standard 3.+2s %graphical user inter"ace)# $he Abstract :indo&ing $ool4it %A:$) also manages user-inter"ace and te(t "iles# $he A:$ also provides the classes "or painting graphics and images# Java ontainer ontainer omponents T T T item7 item = itemA Button 7 Button = @a*out 0anagers

omponents

Event s

@istener

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES /ote: $he Abstract :indo&ing $ool4it %A:$) relates components, containers, la*out managers, events and listeners to each other#

CSCI03: Computer Programming ( Java Application ) Page 7>

C!MP!NEN#S 4 these are buttons, labels, te(t "ields, lists, menus, etc## that lie at the center o" the 3.+, b* using either a mouse or 4e*board, the user can interact &ith these components to accomplish use"ul tas4s# C!N#AINE"S 4 such as panels, "rames, and dialogs organi6e components into groups# LA2!U# MANA6E"S 4 automaticall* la*out the components o" the 3.+ &ith in the containers# %"urther e(planation at the bac4U) E0EN#S 4 objects that are "ired &hen the user-interact &ith the 3.+s components and containers# %see "urther e(planation) -"AMES 4 is the component &e use "or the &indo&s %see e(ample)

LA2!U# MANA6E"S B are special objects that determine the si6e and position o" the object in the container# Java components are arranged in containers b* de"ining the t*pe o" la*out manager object that determines the placing o" these components# $he "ollo&ing are the commonl* used la*out managers in JavaF

-lo' La,out 4 le"t-to-right, top-to-bottom component arrangement that maintains the components dimension# (orFer La,out 4 manages container area into 9 regions: north, south, east, &est and center# 6riF La,out 4 uses grid o" ro&s and columns, "ills each grid &ith component# CarF La,out 4 uses panel li4e a dec4 o" cards#

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES 6riF (ag La,out 4 uses grid o" ro&s and columns, components are placed across several grid areas#

CSCI03: Computer Programming ( Java Application ) Page 77

1BJE $

<lo& @a*out

Border @a*out

3rid @a*out

ard @a*out

3rid Bag @a*out

-ig & G #%e A3# proviFe+ cla++e+ in creating 6UI component+ anF container+

<lo&U

V V

1PE/

<lo& @a*outU

V V

@1-E

1, @1-E

1,

1PE/

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES -ig & H #%e -lo' La,out manager %onor+ t%e component+ Fimen+ion #%e component+ +iIe i+ not altereF '%en t%e container i+ re+iIe+

CSCI03: Computer Programming ( Java Application ) Page 7=

Border @a*out :est

:est

V V /orth enter

Border @a*out /orth enter

V V

East

East

-outh

-outh

A"ter :indo& is resi6ed -ig & J #%e (orFer La,out maintain+ t%e location o) t%e component+ #%e component+ +iIe i+ altereF '%en t%e container i+ re+iIeF

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page 7A

3ridU 7 A 9

V V

= C I

3rid E(ampleU 7 A 9

V V

= C I

A"ter the &indo& is resi6ed -ig & K #%e 6riF La,out manager arrange+ component+ in a ta/le<liLe manner Same a+ in a (orFer La,outM t%e component+ +iIe i+ altereF '%en t%e container i+ re+iIeF E0EN#S *AN$LIN6:

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES Event+ 4 something that occurs &'in an object that an application or other object might &ant to 4no& about Bto &'c it might possible react# $his is represented as a Java class included in the java#a&t#event pac4age# Event Li+tener 4 the inter"ace responsible "or implementing event response methods that are called in response to the speci"ic t*pe o" events#

CSCI03: Computer Programming ( Java Application ) Page 7C -ig & N #%e A3# Event+ *ierarc%,

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES


1bject

Event 1bject

A:$ Event

Action

event

Adjustment Event

omponent

;ierarch*

+nput

Event

Event

0ethod Event

+nvocation Event

+tem Event

$e(t

Event

ontainer

Event

<ocus Event

+nput
Event

Paint Event

:indo& Event

$he java#a&t#event pac4age provides inter"aces and classes "or dealing &ith di""erent t*pes o" events b* A:$ components#

CSCI03: Computer Programming ( Java Application ) Page 79 Java Event Cla++e+ are $iviFeF into 5 6roup+:

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES 7# -emantic Event B events that are "ined in response to the high-level graphical user inter"ace interaction &'in the conte(t o" a certain component# =# @o&-level Events B events that are "ined in response to the lo&-level input or graphical user inter"ace interaction such as 4e*-press or "ocus-change# JA0A$!C +# -ingle @ine omment ' PP bo* te(t PP ' ++# 0ultiple @ine omment ' PP P bod* te(t P bod* te(t P bod* te(t P' ++# ommon Javadoc $ags -*nta( RW name o" the tag S /ote: Each tag has a purpose to describe a particular attribute o" the entit* being commented# #%e )ollo'ing are commonl, u+eF JavaFoc #ag+: 7# W author B programmer2s nameF used "or classes X inter"aces# =# W version B version o" the programF used "or classes X inter"aces A# W param B description o" a "ormal parameterF used "or methods X constructors# C# W return B description o" a return valueF used "or methods# 9# W e(ception %or W thro&s) B description o" an e(ceptionF used "or methods X constructors# I# W see B re"erence to a related entit*F used "or classes X inter"aces, constructors, methods, X data "ields# Sample Program U+ing JavaFoc #ag+: 'PP RpS P javadoc comments# Javadoc comments "or classes can be bro4en into t&o parts: P a description part X a tags part# $his is the description part# $he parts should be P separated b* one empt* comment line# R'pS, R'pS also, there should be no lines

CSCI03: Computer Programming ( Java Application ) Page 7I P bet&een the end o" the Javadoc comment and the beginning o" the entit* it

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES P describes# R'pS P P Wauthor @il* ;ou P Wauthor -ean Bu"ano P Wversion 7#> P' public class $&o+nts J int "irstF int secondF 'PP P +nitiali6es RcodeS "irst R'codeS and P RcodeS second R'codeS to RcodeS o R'codeS P' public $&o+nts %) J "irstQsecondQ>F N 'PP P +nitiali6es RcodeS "irst R'codeS and P RcodeS second R'codeS to arguments P P Wparam ( value to &'c RcodeS "irst R'codeS is initiali6ed P Wparam * value to &'c RcodeS second R'codeS is initiali6ed P' public $&o+nts %int (, int *) J "irstQ(F secondQ*F N

CSCI03: Computer Programming ( Java Application ) Page 7O

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES 'PP P omputes the sum o" the t&o integers P P W return the sum o" the t&o integers P' public int sum %) J return "irst ! secondF N 'PP P +ncrements RcodeS "irst R'codeS b* the argument P P W param ( the value b* &hich RcodeS "irst R'codeS &ill be incremented P' public void add$o<irst %int () J "irst !Q(F N N $ECISI!N AN$ L!!PIN6 Java provides a choice o" t&o selection constructs the i" U else and s&itch U case mechanisms# -imple conditional code "or a choice o" t&o e(ecution paths based on the value o" a Boolean e(pression is easil* &ritten using i" U else# $he s&itchU case construct, on the other hand, is used &hen more comple( choices bet&een multiple e(ecution paths are needed# <urthermore, Java also supports the use i" iteration catered b* three st*les o" @oop: the "or, &hile and doU &hile constructions# #%e i) O el+e Con+truct $he Java i" decision construct is "ollo&ed b* a logical or relational e(pression in &'c data is compared X a decision is made based on the result o" the comparison#

CSCI03: Computer Programming ( Java Application ) Page 7E

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

a# partial i" statement s*nta(: i" %e(pression) J statement%s)F N b# "ull-i" statement s*nta(: i" %e(pression) J statement%s)F N else J statement%s)F N c# /ested i"U else i" statement -*nta(: i" %e(pression7) J statement%s)F N else i" %e(pression=) J statement%s)F N # # else J statement%s)F N

CSCI03: Computer Programming ( Java Application )

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES Page 78 E(ample: 7#) i" %(S7>>) s*stem#out#println %G $he number is greater than 7>>H )F else s*stem#out#println %G $he number is greater than 7>>H )F =#) import java#io#PF class i"Else-tatement J public static void main %string K L args) thro&s e(ception J Bu""eredReader brQne& Bu""eredReader %ne& +nput-treamReader %s*stem#in) )F +nt a,bF -*stem#out#println%GPlease enter "irst integer:H)F AQ+nteger#parse+nt%br#readline%))F -*stem#out#println%GPlease enter second integer:H)F -*stem#out#println%GaQH! a)F -*stem#out#println%GbQH! b)F +" %aSb) -*stem#out#println%Ga is greater than bH)F Else -*stem#out#println%Ga is less than bH)F N N A#) import java#io#PF class i"Else-ample J public static void main%string K L args) thro&s e(ception J Bu""eredReader brQne& Bu""eredreader%ne& +nput-treamReader%s*stem#in))F +nt ageF -*stem#out#print%GEnter *our age:H)F BageQ+nteger#parse+nt%br#redline %))F +" %age SQ7E) -*stem#out#println%GYou2re allo&ed to voteMH)F Else -*stem#out#println%Gtoo *oung to voteMH)F N N

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES CSCI03: Computer Programming ( Java Application ) Page => C#) import java#io#PF class Pass&ord J public static void main %string K L args) thro&s E(ception J B.""eredReader brQne& Bu""eredReader %ne& +nput-treamReader %s*stem#in))F -tring input Q G GF -tring pass Q GpangetHF -*stem#out#print%GEnter a pass&ord:H)F +nputQbr#readline %)F +" %pass#eDuals%input)) -*stem#out#println%GAccess 3ranterH)F Else -*stem#out#println%GAccess DeniedH)F N N 9#) import java#io#PF class 3radeRange J public static void main%string args KL) thro&s E(ception J Bu""eredReader brQne& Bu""eredReader%ne& +nput-treamReader%s*stem#in))F +nt gradeF -*stem#out#print%GEnter desired 3rade:H)F 3radeQ+nteger#parse+nt%br#readline%))F +" %grade RQ7>> Xgrade SQ8>) -*stem#out#println%G1utstandingH)F Else i" %grade RQE8 X grade SQE>) -*tem#out#println%G-atis"actor*H)F Else i" %grade RQO8 X grade SQO9) -*tem#out#println%G/eeds +mprovementH)F Else i" %grade RQOC X grade SQ9>) -*tem#out#println%G<ailedH)F Else -*stem#out#println%G+nvalid 3radeH)F N N

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES CSCI03: Computer Programming ( Java Application ) Page =7 #%e S'itc%O ca+e con+truct $his decision construct is used "or ma4ing a choice among multiple e(ecution paths, X the choice can be upon an int value# $his statement successivel* tests the value o" an e(pression on value against a list o" integer or character constants# :hen amatch is "ound, the statements-associated &' the case are e(ecuted# -*nta(: -&itch %variable/ame) S char, b*te, short, int onl* J case const7: statement%s)F brea4F case const=: statement%s)F brea4F case constA: statement%s)F brea4F U case constn: statement%s)F brea4F de"ault: statement%s)F N $he brea4 statement B causes the program "lo& to e(it "rom the bod* o" the s&itch construct# $he de"ault 4e*&ord B is comparable to the else part o" the i" statement# $he statements associated &' this 4e*&ord are e(ecuted i" the value o" the s&itch variable does not match an* o" the case constants# E(amples: 7#) import java#io#PF class s&itch-tatement J public static void main%string args KL) thro&s E(ception J Bu""eredReader brQne& Bu""eredReader%ne& +nput-treamReader%s*stem#in))F

int nF s*stem#out#println%GPlease enter an integer:H)F nQinteger#parse+nt%br#readline%))F s&itch %n) J

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page == ase 7: s*stem#out#println%G1neH)F brea4F ase =: s*stem#out#println%G$&oH)F brea4F ase A: s*stem#out#println%G$hreeH)F brea4F ase C: s*stem#out#println%G<ourH)F brea4F ase 9: s*stem#out#println%G<iveH)F brea4F ase I: s*stem#out#println%G-i(H)F brea4F ase O: s*stem#out#println%G-evenH)F brea4F ase E: s*stem#out#println%GEightH)F brea4F ase 8: s*stem#out#println%G/ineH)F brea4F ase 7>: s*stem#out#println%G$enH)F brea4F De"ault: s*stem#out#println%G1ooopss, that2s more than 7>MH)F N N N =#) import java#io#PF class -&itch-ample J public static void main%string K L args) thro&s E(ception J Bu""eredReader brQne& Bu""eredReader%ne& +nput-treamReader%s*stem#in))F +nt numF -*stem#out#print%GEnter a number:H)F /umQ+nteger#parse+nt%br#readline%))F -&itch %num) J case 7: s*stem#out#println%Gno&, thereY2sH)F brea4F case =: s*stem#out#println%Gonl* but the "e&H)F case A: s*stem#out#println%G3ood menUH)F brea4 s*stem#out#println%GitY2s trueMMMH)F brea4F de"ault: s*stem#out#println%Gno good men at allUH)F N N N

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page =A A#) import java#io#PF class -&itch har J public static void main%string args K L) thro&s E(ception J Bu""eredReader brQne& Bu""eredReader%ne& +nput-treamReader%s*stem#in))F -tring m* charF -*stem#out#println%GEnter a letter:H)F 0* harQRcharSbr#readline -&itch%m*char) J ase ZA2 : s*stem#out#println%GAdorableH)Fbrea4F ase ZB2 : s*stem#out#println%GBeauti"ulH)Fbrea4F ase Z 2 : s*stem#out#println%G harmingH)Fbrea4F ase Z.2 : s*stem#out#println%G.gl*H)Fbrea4F De"ault : s*stem#out#println%G/o ommentH)F N

N N #%e 3%ile Loop $his construct e(ecutes a given statement or bloc4 o" statements again X again as long as the value o" the e(pression is true# $he e(pression must be a Boolean e(pression X must return the variable called the loop control variable# -*nta(: &hile %e(pression) J statement%s)F N

#%e Fo '%ile loop +n the doU &hile loop, the e(pression %or condition) is evaluated at the end o" the loop to ensure that the statements are e(ecuted at least once# -imilar to the &hile loop, the statements are e(ecuted repeatedl* as long as the e(pression is true#

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page =C -*nta(: do J statement%s)F N &hile %e(pression)F #%e )or loop $his loop construct e(ecutes a given statement or bloc4 o" statements "or a de"inite number o" times# +t per"orms a set o" instructions or bloc4 o" statements repeatedl* until a certain condition is reached# -*nta(: <or%initiali6ationF conditionF update %!! ' --)) -tatement %s)F :here: +nitiali6ation B is an assignment statement that is used to set the loop-control variable# ondition B is a relational e(pression that determines &hen the loop &ill e(it b* testing the loop-control variable against same value# .pdate %!!, --) B de"ines ho& the loop-control variable &ill change each time the loop is repeated# E(amples: 7#) public class <or$est J public static void main %string K L args) J int i,jF "or%iQ>, jQ>F i!j R=>F !!+, j!Qi) s*stem#out#println%i!j)F N

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page =9 =#) import java#io#PF public class "actorial J public static void main %string KL args) thro&s E(ception J Bu""eredReader brQne& Bu""eredReader%ne& +nput-treamReader%s*stem#in))F <or % aQ7F aRQ7>F a!!) J +nt ", (, ansF -*stem#out#println%GEnter a number:H)F <Q+nteger,parse+nt%br#readline%))F AnsQ7F <or %(Q"F (SQ7F (--) AnsQ(PansF -*tem#out#println%G$he "actorial o" G ! " ! GisH ! ans)F N N A#) import java#io#PF public class e(ponential J public static void main %string KL args) thro&s E(ception J Bu""eredReader brQne& Bu""eredReader%ne& +nput-treamReader%s*stem#in))F +nt b, e, (F Double ansF -*stem#out#println%GEnter Base:H)F bQ+nteger#parse+nt%br#readline%))F -*stem#out#println%GEnter E(ponent:H)F eQ+nteger#parse+nt%br#readline%))F AnsQ7F <or %(Q7F (RQeF (!!) AnsQbPansF -*stem#out#println%G$he ans&er isH ! ans)F N N

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page =I C#) import java#io#P public class gcd J public static void main %string KL args) thro&s E(ception J Bu""eredReader brQne& Bu""eredReader%ne& +nput-treamReader%s*stem#in))F +nt num7,num=,tempF -*stem#out#println%GPlease t*pe t&o positive numbers:H)F /um7Qinteger#parse+nt%br#readline%))F /um=Qinteger#parse+nt%br#readline%))F :hile %num=MQ>) J num7Qnum=F num=QtempF N -*stem#out#println%G$heir 3reatest ommon Divisor is:H ! num7)F N 9#) import java#io#PF public class Reverse J public static void main %string KL args) thro&s E(ception J Bu""eredReader brQne& Bu""eredReader%ne& +nput-treamReader%s*stem#in))F +nt num, rightdigitF -*stem#out#println%GEnter a number:H)F /umQ+nteger#parse+nt%br#readline%))F Do J rightdigitQnum [ 7>F -*stem#out#println%rightdigit)F /umQnum'7>F N &hile %numMQ>)F

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES N N

CSCI03: Computer Programming ( Java Application ) Page =O MI$#E"M PE"I!$ C%apter 5: Cla++e+ C !/Pect+ lass B re"ers to a group or set o" objects having the same states and behavior# +t can also be de"ined as the categor* o" objects that de"ine all the common properties o" objects belonging to it# +n 11P, a class is the derived t*pe that represents a collection o" related data X collection o" methods %"unctions) that operate on the class data# 1bject B de"ines sel"-contained entities that consist o" an identit*, state X behavior %procedures) to manipulate data# An object is a representation o" something# 1bject2s re"erences are variables, &hich are o" a class t*pe that identi"ies the location in the memor*#

@A-- /A0E DA$A Attributes %or states) 0E$;1DBehaviors %or "unctions X procedures) -ig 5 0 /ote: A class usuall* represents the GblueprintH o" all objects belonging to it# !(JEC# "ELA#I!NS*IPS:

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES 7#) Association B e(ist &hen an object contains a re"erence to another object# $his is usuall* re"er to as Ghas aH relationship#

CSCI03: Computer Programming ( Java Application ) Page =E -ig 5 & $eacher 3ender Age Emplo*ee ode Years o" -ervice -ubjects Ever* -tudent has a $eacher -ample +llustration /o# = 5ideo Rented $ransaction /o# Date Rented 5ideo +tem -tudent 3ender Age 3rade <av# -ubj# $echer

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES


5ideo -tore ostumer

+D /ame 5ideo Rented

5ideo +tem -toc4 /o# $itle Rating

-ig 5 5 Uni)ieF MoFeling Language (UML) .0@ is a general-purpose notational language used "or speci"*ing X visuali6ing comple( so"t&are, usuall* large object-oriented project# .0@ uses several t*pes o" diagrams such as case diagram, class diagram X the state chart diagrams#

CSCI03: Computer Programming ( Java Application ) Page =8 -ig 5 3

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES Balance Account

:ithdra& 3et Balance Deposit

$he ase Diagram is used to describe ho& the users are using the objects in the s*stem#

CSCI03: Computer Programming ( Java Application ) Page A> -ig 5 Q

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

1rder reate d

1rder Bac4order

1rder +tem Placed

1rder ;eld

1rder Delivere d

1rder losed 1rder discarded

$he -tate chart Diagram is used to describe the li"ec*cle or stages o" objects in the s*stem#

CSCI03: Computer Programming ( Java Application ) Page A7

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES -ig 5 G /A0E A$$R+B.$E1PERA$+1/- 1R 0E$;1D5ideo Rented $itle Rent Date harge Due date 5ideo Rented 3entRent Date -etDue Date

$he lass Diagram is used to describe the attributes X behaviors o" objects in the s*stem# UML S2M(!LS: Cla++ S,m/ol: lass /ame - Attributes - Attributes - Attributes ! 0ethods ! 0ethods ! 0ethods Acce++ Speci)ier S,m/ol+: ! public Q an*&here - private Q &'in the class it is declared \ protected Q similar to private but the attribute &ill be available to sub-class# G G de"ault Q similar to public but &'in its pac4age# Ban4 Account Balance Account no# -tatus ! Deposit % ) ! :ithdra& % ) ! +nDuire Balance % )

CSCI03: Computer Programming ( Java Application )

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES Page A= $E-ININ6 C $ESI6NIN6 CLASSES: Java, being a tightl* cast language, has strict rules &' regard to the process in &'c data is stored# $he Java compiler en"orces man* o" these rules as to ho& much storage is allocated in each data X as to &here data &ill be stored# $e)ining Cla++e+: A class de"inite consists several constructs "or de"ining X declaring the "": 7#) Attributes B declared either at the start or at the end o" class de"inition, these variables identi"* the data that is stored in the object# 1bject data can be either primitives or re"erences to other objects# =#) onstructor B this method de"ines the speci"ics o" object creation# A#) -tandard 0ethods B theses methods to change or access the private data in an object# C#) ustom 0ethods B these are methods that implement the business rules# -ig 5 H /ame Attributes 1perations or 0ethods Attributes declaration onstruction de"inition stand 0ethods de"inition custom methods de"inition

CSCI03: Computer Programming ( Java Application )

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES Page AA $e+igning Cla++e+: 7#) De"ine class name -*nta(: Raccess]speci"ierS class Rclass]nameS J bod*F N =#) +denti"* Attributes -*nta(: Raccess]speci"ierS Rdata]t*peS RattributesSF A#) De"ine onstructor A constructor method has some "eatures: constructor method must have the same name as the class name# constructor method has to de"ine none, one or man* "or a class# onstructor method do not have a return value# onstructor method are e(ecuted onl* once at object creation# -*nta(: Raccess]speci"ierS class /ame %argument @istsU) J constructor bod* N note: $he constructor is ver* important method because it is used during the creation %instantiation) o" an object# $he ne& 4e*&ord is an operator used to allocate memor* "or the creation o" an object# C#) reate -tandard 0ethod 0utator %setters) B methods used to change data# -*nta(: Raccess]speci"ierS void set ??? %argument @istssU) J ''((( is a "ield variable &'c is assigned &'a speci"ic value ''in the method bod*# Accessor %getters) B methods used to access or retrieve data# -*nta(: Raccess]speci"ierS Rreturn$*peS get ((( %) J ''((( is usuall* a "ield variable &hose value is returned b* ''the method# /ote: $he accessor method uses the return 4e*&ord at the end o" its de"inition#

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES CSCI03: Computer Programming ( Java Application ) Page AC 9#) reate ustom 0ethod -*nta(: Raccess]speci"ierS Rreturn]t*peS method /ame %argument@istsU) J ''method bod* N custom methods are methods that implement the business rules "or &'c the application is being developed are part o" the class de"inition# Sample Program No &: Public class -imple lass J Public static void main %string args K L) J -tudentRecord m*-tudent Q ne& -tudentRecord %GPearl Ruth DamiasH,GE0P>7H)F m*-tudent#set3rade %8E#88, 89#9)F s*stem#out#println%G-tudent /ame:H ! m*-tudent#get/ame%))F s*stem#out#println%G3rade in English:H ! m*-tudent#get3radeEng%))F s*stem#out#println%G3rade in 0ath:H ! m*-tudent#get3rade0ath%))F s*stem#out#println%GAverage 3rade:H ! m*-tudent#getAverage%))F N N class -tudentRecord J private -tring student+dF private double gradeEngF A$$R+B.$Eprivate double grade0athF public -tudentRecord %string n, string sid) J name Q nF student+d Q sidF N

1/-$R. $1R

public void main set3rade %double e, double m)F J gradeEng Q eF grade0ath Q mF 0.$A$1R ' -E$$ER N

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES CSCI03: Computer Programming ( Java Application ) Page A9 Public string get/ame%) J Return nameF N public string get-tudent+d%) J return -tudent+dF N public double get3radeEng%) J return gradeEngF N public double get3rade0ath%) J return grade0athF N Public double getAverage%) J Double aveF ave Q %grade0ath ! gradeEng)'=F Return aveF N #*IS Le,'orF #%i+ 4 contains re"erence as the current object being constructed# $his 4e*&ord represents an instance o" the class in &'c it appears# +t can be used to access class variable X methods# -ample Program /o# = Public class ellphone J Private string brandF Private string modelF Public cellphone %) J $his#brand Q G/1,+AHF $his#model Q GII>>HF N A$$R+B.$E-

E--1R ' 3E$$ER-

.-$10 0E$;1D

1/-$R. $1R

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page AI Public void setBrand %string brand) J $his#brand Q brandF N public void set0odel %string model) J this#model Q modelF N public -tring getBrand %) J return this#brandF N public -tring get0odel %) J return this#modelF N '' public void Ring %) J '' s*stem#out#println%G 0Y phone is ringingUH)F '' N '' public void vibrate %) J '' s*stem#out#println%G 0Y phone is vibratingUH)F '' N public class $est J public static void main %-tring args K L) J cellphone cell7F cellphone cell=Qne& ellphone%)F cell7Qne& ellphone%)F cell7#setBrand %G/1,+AH)F cell7#set0odel %GOI9>H)F

0.$A$1R- ' -E$$ER-

E--1R- ' 3E$$ER-

.-$10 0E$;1D-

''null value "or cell7 variable ''cellphone class value "or cell= variable

s*stem#out#println%G <irst choice:H ! cell=#getBrand%) ! cell=#get0odel%))F N

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page AO UML $iagram )or Sample Program No 5 ellphone - brand : string - model : string P cellphone %) P -etBrand%brand : string) void P-et0odel%model : string) void PgetBrand%) : string Pget0odel%) : string $E-$ Pmain %args : -tring K L) void

UML $iagram )or Sample Program No & -tudent Record - name : string - student +D : string - gradeEng : double -grade0ath : double ! -tudentRecord%) ! set3rade%e:double,m:double) void !get/ame%) : string ! get-tudent+d%) : string ! get3radeEng%) : double ! get3rade0ath%) : double ! getAverage%) : double -imple lass ! main %args : string K L) : void

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page AE A""A2S Arra*s are used to represent "i(ed number o" elements o" the same t*pe# $he entire arra* is stored contiguousl* &ithin the computer2s memor* X is re"erence b* a common name# each element o" the arra* is distinguished b* the inde( %or subscript)# $he elements o" the arra* are e(plicitl* initiali6ed to de"ault values based on the arra* t*pe %> "or-integral t*pes, >#> "or "loat ' double, "alse, "or Boolean X null "or object t*pes)# -*nta(: $*pe arra*/ame K L Q ne& t*pe KlengthL :here: $*pe B data t*pe o" arra* /e& B operator "or memor* allocation @ength B si6e o" the arra*# E(ample: -tring names K L Q ne& string K9LF +llustration:

+nde( -

>

<ig# =#E An arra* o" names has the si6e o" 9 %>-C inde() storing# -tring values inside the memor* o" the computer# Arra, Illu+tration: -*nta(: t*pe arra*/ame Q Ja, b, c, d,U##nNF E(amples: int ( K L Q J7, =, A, C, 9, INF Boolean b K L Q Jtrue, true, "alseNF Double grade K L Q J EE, 88, 8E, O9, 7>>, EI#8NF -tring names K L Q JGAnnH, GBenH, G hinaHNF

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page A8 ACCESSIN6 C S#!"IN6 0ALUES IN AA"A2S: -*nta(: arra*/em Kinde(L B valueF $he process o" storing values in an arra* is also re"erred to as GpopulatingH the arra*: E(ample: ?K>L Q OEF ?K7L Q E8F ?K=L Q ACF ?KAL Q 7=F -ample Program /o# 7 +mport java#io#PF Public class Arra* -mple J public static void main %string args K L) thro&s E(ception J B.""eredReader brQne& Bu""eredReader%ne& +nput-treamReader%s*stem#in))F -tring sQ G GF +nt ( K L Q ne& int K9LF -*stem#out#println%G$his program &ill accept 9 integer:H)F <or %int iQ>F + R(#lenghtF i!!) J -*stem#out#println%GPlease enter number: ( K G! + ! G L:H)F -Qbr#readline%)F ?KiL Q integer#parse+nt%9)F N -*stem#out#println%GYn $he numbers areH)F <or %int iQ>F + R(#lenghtF i!!) J -*stem#out#println%G( K G! + !HL Q G ! ( KiL)F N Representation:

OE >

E8 7

AC =

7= A

elements inde(

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES N N

CSCI03: Computer Programming ( Java Application ) Page C> -ample Program /o#= lass ;al"Dollars J public static void main %string args K L) J intK L Denver Q J 79>>>>>I, 7EE7>>>>,=>O9=77>NF intK L Philadelphia Q ne& int KDenver#lengthLF intK L total Q ne& int KDenver#lengthLF int averageF PhiladelphiaK>L Q 79>=>>>>F PhiladelphiaK7L Q 7EOE>>>F PhiladelphiaK=L Q =7ACE>>>F $otal K>L QDenver ! Philadelphia K>LF $otal K7L QDenver ! Philadelphia K7LF $otal K=L QDenver ! Philadelphia K=LF Average Q %totalK>L ! totalK7L ! totalK=L)'AF -*stem#out#println%G=>>> production:H !total K>L)F -*stem#out#println%G=>>7 production:H !total K7L)F -*stem#out#println%G=>>= production:H !total K=L)F -*stem#out#println%GAverage production:H ! average)F N -ample Program /o# A lass Range lass J +nt K L ma4eRange %int lo&er, int upper) J +nt arr KL Q ne& int K %upper B lo&er) ! 7LF <or %int iQ>F + R arr#lengthF i!!) J ArrKiL Q lo&er !!: N return arrF N

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES public static void main %string args K L) J int thearra*KLF Range lass theRange Q ne& Range lass%)F N

CSCI03: Computer Programming ( Java Application ) Page C7 theArra* Q theRange#ma4eRange%7,7>)F -*stem#out#print%G$he arra* is: +H)F <or %int iQ>F + R theArra*#lengthF i!!)F -*stem#out#print%theArra*KiL! G G)F N -*stem#out#println%G+H)F N -ample Program /o# C +mport java#io#PF Public class -tudentRecord J public static void main %string args K L) thro&s E(ception J B.""eredReader brQne& Bu""eredReader%ne& +nput-treamReader%s*stem#in))F -*stem#out#print%GEnter the number o" record *ou &ant:H)F +nt number1"Record Q +nteger#parse+nt%br#readline%))F ''declaration o" arra* string namesKL Q ne& -tring Knumber1"RecordLF doubleKL grades Q ne& double Knumber1"RecordLF -*stem#out#println%G<ill up the "ollo&ing:H ! number1"Record ! GrecordsUH)F <or %int iQ>F + R names#lengthF i!!) J -*stem#out#print%GEnter the student2s name:H)F /ames KiL Q br#readlin%)F -*stem#out#print%GEnter the student2s grade:H)F 3rades KiL Q Double#parseDouble%br#readline%))F N -*stem#out#println%GYou have entered the "ollo&ingU:H)F <or %int iQ>F + R names#lenghtF i!!) -*stem#out#println%%i!7) ! G#H ! namesKiL ! G:H ! gradesKiL)F

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES -*stem#out#println%G-earch a student:H)F -*stem#out#println%GEnter the name o" the student:H)F -tring pangalan Q br#readline%)F <or %int iQoF + R names#lengthF i!!) J

CSCI03: Computer Programming ( Java Application ) Page C= +"%pangalan#eDuals %namesKiL)) J -*stem#out#println%GRecord "oundMH)F -*stem#out#println%%i!7) ! G#H ! names KiL ! G:H ! grades KiL)F N else -*stem#out#println%GRecord not "oundMH)F N N P"!CE$U"AL 0S !(JEC#<!"IEN#E$ P"!6"AMMIN6 -everal programming models have evolved to help programmers in carr*ing-out the process o" problem solving using a computer# $he = o" the most popular models are: the procedural programming X the object-oriented programming# P"!CE$U"AL P"!6"AMMIN6 Procedural programming is a techniDue o" solving a problem b* brea4ing do&n a program into smaller pats that are arrange X e(ecuted in a logical seDuence# Each o" these smaller solutions is used to per"orm a bloc4 o" codes called "unction# $his techniDue o" programming is also 4no&n as process-oriented programming since it concentrates on the procedures# ;o&ever, the approach is not ideall* suited "or developing comple( so"t&are since the modules are tightl* inter&oven X interdependent that it is di""icult to separate "rom one module to another# +n addition to this, the reusabilit* o" the so"t&are becomes ver* di""icult as comple(it* increases &'in the process involved# !(JEC#<!"IEN#E$ P"!6"AMMIN6

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES 1bject-oriented programming %11P) is a techniDue o" solving a problem that uses objects# $hese objects are created X stored in the computer memor* &'c contains data X "unctions %instructions ' operations) that per"orms a speci"ic tas4s# +n addition to this, 11P describes the relationships that can be created bet&een these objects# -o &hen the program is e(ecuted, the computer s*stem loads these objects X per"orms operations on these objects# Basicall*, 11P model describes a program that uses a collection o" objects interacting &' each other#

CSCI03: Computer Programming ( Java Application ) Page CA 1ne o" the principal advantages o" using object-oriented programming techniDue is that it enables programmers to create modules that need not to be changed &hen a ne& t*pe o" object is added# $his ma4es 11P so"t&are easier to modi"*# (ENE-I#S !- !!P 7#) Reduced so"t&are comple(ities X realistic modeling through the use o" various techniDues such as abstraction X encapsulation %or in"ormation hiding) Abstraction B the process o" pic4ing-out %abstracting) the common "eatures o" objects X procedures# +t "ocuses on the essential characteristics o" an object# Encapsulation B the process o" hiding the implementation details o" an object# +t is also used to combine elements to produce a ne& entit*# =#) -o"t&are reusabilit* b* implementing inheritance# Programs are built that can be used b* several other applications# -o"t&are reusabilit* translates to a saving time X e""ort in so"t&are development, &'c in their results in cost bene"its# +nheritance B allo&s an object to e(tend its char to another object# A#) Resilience to change &' the use o" pol*morphism# Pol*morphism B abilit* to process objects di""erentl* depending on their t*pe o" class# (ENE-I#S !- USIN6 IN *E"I#ANCE: 7#) Reuse o" prede"ined X &ell-tested classes# =#) -tandardi6ation o" behaviors across a group o" classes A#) Abilit* to use members o" a "amil* o" classes interchanging in methods#

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES -*nta( "or implementing inheritance: Public class subclass e(tends super class J ''attributes or data declarations ''constructor X method de"initions N

CSCI03: Computer Programming ( Java Application ) Page CC P!L2M!"P*ISM Abilit* to process objects di""erentl* depending on the data t*pe or class# Abilit* to rede"ined methods "or derived classes#

E(ample: 3iven a base class or superclass shape, pol*morphism enables the programmer to de"ine di""erent circum"erence methods "or an* number o" derived classes, such as circles, rectangles X triangles# /o matter &hat shape an object is, appl*ing the circum"erence method to it &ill return the correct results# IMPLEMEN#IN6 P!L2M!"P*ISM: 7#) 1verloading B t&o or more implementations o" essentiall* the same "unctionalit* to use the some name X the t*pe and order o" arguments in the parent class# -ample Program /o# 7 lass -tudentRecord J Private -tring nameF Private string student+dF Private double gradeF Private string subjectF Public -tudebtRecord %) J

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES /ame Q nullF student+d Q null F N public -tudentRecord %string n, string sid) J name Q nF student+d Q sidF N 1verloaded onstructor

CSCI03: Computer Programming ( Java Application ) Page C9 Public void set3rade %double g, string s) J 3rade Q gF -ubject Q sF N public void set3rade %string s, double g) J grade Q gF subject Q sF N # # # N -ample Program /o# = lass -tudentRecord= J Private string nameF Private string student+dF Private double gradeF Private string subjectF Public -tudentRecord%) J /ame Q nullF student+d Q nullF N 1verloaded 0ethods

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES : : public void displa*3rade%) J s*stem#out#println%G-ubject:H ! subject)F s*stem#out#println%G3rade:H ! grade)F N : : N class AnotherRecord e(tends -tudnetRecord= J private double grade=F private string subject=

1verridden 0ethods

CSCI03: Computer Programming ( Java Application ) Page CI Public -tudentRecord %)F : : N public void displa*3rade%) J s*stem#out#println%G-ubject:H ! subject)F s*stem#out#println%Ggrade:H ! grade)F s*stem#out#println%G-ubject=:H ! subject=)F s*stem#out#println%Ggrade=:H ! grade=)F N : : N C!MPA"IS!N: !verloaFing 0+ !verriFing 15ER@1AD+/3 1verloaded methods supplement each other 1verloaded methods can e(ists, 15ERR+D+/3 T overriding method %largel*) replaces the method it overrides# T Each method in a parent class can be

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES in an* number, in the same class# 1verloaded methods must have di""erent argument lists# overridden at most once in an* one subclass# T overriding methods must have argument lists o" identical t*pe X order %other&ise the* are simpl* treated as overloaded methods)# T the return t*pe o" overriding method must be identical to that o" the method it overrides#

$he return t*pe o" an overloaded method ma* be chosen "reel*#

CSCI03: Computer Programming ( Java Application ) Page CO -ample Program /o# A Public class 0*Rectangle J Protected double &idthF Protected double lengthF Public 0*Rectangle %double &idth, double length) J $his#&idth Q &idthF $his#length Q lengthF N public 0*Rectangle%) J this%7>#>,7>#>)F N public string to-tring%) J string rec Q GYn &idth:H ! this#&idth ! GYn length:H ! this#lengthF return recF N N class 0*Bo( e(tends 0*Rectangle J private double heightF public 0*Bo(%double &idth, double length, double height) J

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES super%&idth, length)F this#height Q heightF N public 0*Bo( %double height) J super%)F this#height QheightF N public 0*Bo(%) J this%7>#>)F N public string to-tring%) J string bo( Q super#to-tring%) ! GYn height:H ! this#heightF return bo(F N N

CSCI03: Computer Programming ( Java Application ) Page CE SUPE" Le,'orF ontains a re"erence to the parent-class %superclass) object# +t is used to access members o" a class inherited b* the class in &'c it appears# #%e A/+tract Cla++ C Inter)ace Abstract class B a class contains one or more abstract methods, X there"ore can never be instantiated# Abstract classes are de"ined so that other classes can e(tend then X ma4e them concrete b* implementing the abstract methods# +nter"ace B an abstract class that represents a collection o" method de"initions X constant values# +t can later be implemented b* classes that de"ine this inter"ace &' the GimplementsH 4e*&ord# A/+tract Cla++:

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES -hape

Rectangle

ircle

;e(agon

An e(ample o" an abstract class B the shape class# -ince not all the objects in the &orld can be modeled in the same manner, most real-&orld objects are too abstract to e(ist b* themselves# An abstract class de"ines the common properties X behaviors o" classes derived X belonging to same 4ind# -*nta( "or Abstract lass: Abstract class R class name S J ''abstract method declarations public abstract return$*pe method/ame%Args@ist)F N note: All abstract classes are public b* de"ault X cannot be instantiated# onstructors X static methods cannot be declared as abstract# ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] CSCI03: Computer Programming ( Java Application ) Page C8 -INALS Inter)ace

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES 5ehicle

ar

Boat

Airplane

Animal

<l*ing object K"l* %) methodL

Dog

<ish

Bird

]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] CSCI03: Computer Programming ( Java Application ) Page 9>

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES -*nta( "or +nter"ace: Abstract inter"ace inter"ace/ame N ''constant declarations public "inal $*pe variable/ame Q valueF ''abstract method declarations public abstract return$*pe method/ame %Args@ist)F note: $he di""erence bet&een an abstract class and an inter"ace is that all methods in inter"ace are onl* declared, and not all implemented# Also, an inter"ace ma* not have an* private member "ields unli4e an* abstract classes# All inter"ace "ield variables are "inal b* de"ault# An* class can implement more than one inter"ace, but can onl* e(tend "rom one class# E.ception+M Stream+ anF -ile+: E.ception is de"ined as an une(pected error or error condition# $he* are called e(emptions presumabl* because the* are not usual occurrences the* are Ge(ceptionalH# $he object-oriented techniDues to manage such errors comprise the group o" methods 4no&n as e(ception handling# Potential E.ception+: 7#) +ssues a command to read a "ile "rom a dis4, but the "ile do not e(ist there# =#) You &rite date to a dis4, but the dis4 is "ull or un"ormatted# A#) Your program as4s "or user input, but the user enters invalid data# C#) $he program attempts to divide a value b* 6ero, access an arra* &' a subscript that is too large, or calculate a value that is too large "or the ans&er2s t*pe# +n java, there are t&o basic classes o" errors, error and E(emption# $he ascendants o" both o" these classes came "rom the thro&able class sho&n in the "igure belo&#

]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] CSCI03: Computer Programming ( Java Application ) Page 97

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES $hro&able

E(ception

Error

+1 E(ception

1ut1"0emor*E(ception

+nternal'ErrorE(ception Runtime E(ception 1thers Arithmetic E(ception 1ther

Arra*inde(1ut1"BoundsE(ception

Error Cla++ represents more serious errors "rom &hich *our program usuall* cannot recover# $hese are errors that *ou probabl* made in *our programs &hen *ou misspelled a class name or store a reDuired class in the &rong "older# :hen a program cannot locate a reDuired class an Error condition occurs or runs out o" memor*# E.ception Cla++ it is a less serious error that represents unusual conditions that arise &hile a program is running and "rom &hich the program can recover# -ome o" these errors in E(ception class include using an invalid arra* subscript or per"orming illegal arithmetic operations#

]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] CSCI03: Computer Programming ( Java Application )

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES Page 9= -ample Program /o# 7 Public class computeError J Public static void main%-tring argsKL) J +nt numQ7IF +nt denQ>F +nt resultF ResultQnum'denF N N Error Cla++ represents more serious errors "rom &hich *our program usuall* cannot recover# $hese are errors that *ou probabl* made in *our programs &hen *ou misspelled a class name or store a reDuired class in the &rong "older# :hen a program cannot locate a reDuired class an Error condition occurs or runs out o" memor*# E.ception Cla++ it is a less serious error that represents unusual conditions that arise &hile a program is running and "rom &hich the program can recover# -ome o" these errors in E(ception class include using an invalid arra* subscript or per"orming illegal arithmetic operations# -ample Program no# 7 Public class computeError J Public static void main%-tringargsK L) J +nt numQ7IF +nt denQ>F +nt resultF ResultQnum'denF N N note: You can see that the E(ception is a java#lang#ArithmeticE(ception, &hich is a subclass o" E(ception# You also get some in"ormation as to the nature o" the error %G' 6eroH), the method that generates the error % omputerError#main), and the "ile and the line number "or the error % omputerError#java, line 8, *our line number might be di""erent i" *ou include lines at the beginning o" *our program)# ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES CSCI03: Computer Programming ( Java Application ) Page 9A $he most o"ten used error-handling solution has been terminate the o""ending program# Public class 0athError-ample7 J Public static void main%-tring argsK L) J +nt numQ7A, denomQ>F resultF +" %denomQQ>) -*stem e(it%7)F ResultQnum'denomF N N #r,M Catc%M anF -inall, -*nta(: public class some0ethod thro&s someE(ception J $r* J ''statements that might cause an E(ception N catch%someE(ception and E(cdeption+nstance) J ''&hat to do about it N "inall* J ''statements "or cleaning up the state o" the method be"ore %possibl*) allo&ing control to be passed to a di""erent part o" the program N ''statements here e(ecute even i" there &as no E(ception N note: +" an E(ception occurs during the e(ecution o" the tr* bloc4, then the statements in the catch bloc4 &ill e(ecute# +" no E(ception occurs &ithin the tr* bloc4, then the catch bloc4 &ill not e(ecute# $he "inall* bloc4 allo&s *our method to clean up a"ter itsel" regardless o" &hat happens &ithin the tr* bloc4# .se "inall* bloc4s to close "iles or release other s*stem resources# Either &a*, the statements "ollo&ing the "inall* bloc4 e(ecute normall*# +" a method thro&s an E(ception that &ill be caught, *ou must use the 4e*&ord Gthro&sH "ollo&ed b* an GE(ception t*peH in the method header#

$erminates the program

]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page 9C #*"!3IN6 AN$ CA#C*IN6 MUL#IPLE ERCEP#I!NS +n thro&ing and catching multiple e(ceptions *ou can place man* statements as *ou &ant &ithin the tr* bloc4 as &ell as catching E(ceptions# +" *ou tr* more than one statement, onl* the "irst error generating statement thro&s E(ceptions# As soon as the E(ception occurs, the logic trans"ers to the catch bloc4, &hich leaves the rest o" the statements in the tr* bloc4 une(ecuted# 0ultiple catch bloc4 is e(amined in seDuence until match is "ound "or the E(ception that occurred, and the matching catch bloc4 e(ecutes and each remaining catch bloc4 is b*passed# -ample Program /o# = Public class 0ultiple$r* atch J Public static void main%-tring args KL) thro&s ArithmeticE(ceptionF +nde(Q1ut1"BoundsE(ception +nt numQ=>F +nt denQ>F +nt resultF +nt K L arra*Q%7>,=>,A>,C>)F $r* J ResultQnum'den ResultQarra*KnumL N catch%ArithmeticE(ceptionError) J s*stem#out#println%GError 1ccurred in Arithmetic omputationH)F N catch%inde(1ut1"BoundsE(ception erro) J s*stem#out#println%Error 1ccurred in inde(ingH)F N N N note: 0ultiple$r* atch class declares "our integers and an integer arra* &ith "our elements in the main%) method, the tr* bloc4 e(ecutes and the "irst statement &ithin the tr* bloc4, an E(ception occurs because the denominator%den) in the divisionproblem is 6ero%>)# $he tr* bloc4 is abandoned and the logic trans"ers to the "irst catchbloc4# Divisionb* 6ero causes an Arithmetic omputationH# $he second catch bloc4ed is s4ipped# ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page 99 An +nde(1ut1"BoundE(ception occurs &hen an arra* subscript is not &ithin the allo&ed range# -ample Program /o#A Public class :rite@ist-ample J Public void &rite@ist%) J print:riter outQnullF tr* J s*stem#out#println%GEntering tr* statementHF outQne& Print:riter%ne& <ile:riter %G1ut<ile#t(tH))F "or %int aQ>F a R si6eF a!!) out orintln%G5alue at G ! a ! GQH ! victor#elementAt%a))F N catch%Arra*+nde(1ut1"BoundsE(ception e) J s*stem#out#prinln%G aught Arra*+nde(1ut1"BoundsE(ception G ! e#get0essage%))F N catch%+1E(ception e) J s*stem#err#println%G aught +1E(ceptionG ! e#get0essage%))F N "inall* J i" %out MQ null) J s*stem#out#println%G losing Print:riterH)F 1ut#close%)F N else J s*stem#out#println%GPrin:riter not openH)F A "ile output stream can be created &ith the <ile1utput-tream%-tring) constructor# $he usage is the same as the <ile+nput-tream%-tring) constructor so *ou can speci"* a path along &ith a "ilename# You have to be care"ul &hen speci"*ing the "ile to &hich to &rite an output stream# +" it2s the same as an e(isting "ile, the original &ill be &iped out &hen *ou start &riting data to the stream# ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

CSCI03: Computer Programming ( Java Application ) Page 9I -ample Program /o# C +mport java#io#PF lass <ile1peration= J Public static void main%-tring argsKL) NJ B*te bu""KL Q ne& b*teKE>LF $r* J -*stem#out#println%GYn Enter a line to be saved to dis4:H)F +nt b*tes Q s*stem#in#read%bu"")F "ile1utput-tream "ile1ut Q ne& <ile1utput-tream%G-ample#t(tH)F "ile1ut#&rite%bu""#>#b*tes)F N catch%E(ception e) J -tring error Q e#to-tring%)F -*tem#out#println%error)F N N N S#AC1S -tac4s are a classic data structure used to model in"ormation that is accessed in a speci"ic order# $he -tac4 class in Java is implemented as a last-in-"irst-out %@+<1) stac4, &hich means that the last item added to the stac4 is the "irst one to be removed# -ig & 0 Logical !rganiIation o) a +tacL Fata +tructure Position "rom the top > 7 = A Element A Element = Element 7 Element > B1$$10 $1P

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES

]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] CSCI03: Computer Programming ( Java Application ) Page 9O $he stac4 class de"ines onl* one constructor, &hich is a de"ault constructor that creates an empt* stac4# You use this constructor to create a stac4 li4e this# -tac4 s Q ne& -tac4%)F You add ne& elements to a stac4 b* using the push%) method, &hich pushes an element onto the top o" the stac4# s#push%G1neH)F s#push%G$&oH)F s#push%G$hreeH)F s#push%G<ourH)F s#push%G<iveH)F s#push%G-i(H)F this code pushes si( string on to the stac4, &ith the last string %Gsi(H) remaining on the top# You pop elements bac4 o"" the stac4 b* using the pop%) method# -tring s7 Q %-tring) s#pop%)F -tring s= Q %-tring) s#pop%)F $his code pops the last t&o strings o"" the stac4, leaving the "irst "our strings# $his code results in the s7 variable containing the G-i(H string and the s= variable containing the G<iveH string# +" *ou &ant to ge the top element on the stac4 &ithout actuall* poppong it o"" the stac4, *ou can use the pee4%) method# -tring sA Q %-tring) s#pee4%)F $his call to pee4%) returns the G<ourH string but leaves the string on the stac4# $he onl* other nethod de"ined in the -tac4 class is empt*, &hich determines &hether a stac4 is empt*# Boolean isempt* Q s empt*%)F

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES Although the stac4 class issn2t Duite use"ul, it provides the "unctionalit* "or a ver* common and established data structure#

]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] CSCI03: Computer Programming ( Java Application ) Page 9E SUEUES ^ueue is a container li4e the stac4s but ituses "irst-in-"irst-out %<+<1) protocol, &hich means that the "irst item added to the Dueue is the "irst one to be removed# -ig & 0 #%e Logical !rganiIation o) a StacL $ata Structure

> 7 = A

Element A Element = Element 7 Element >

;EAD

$A+@

$he ^ueue class de"ines onl* constructor, &hich is a de"ault constructor that creates an empt* Dueue# You use this constructor to vreate a Dueue li4e this# ^ueue D Q ne& ^ueue%)F You add ne& elements to a Dueue b* using the enDueue%) method, &hich places an element onto the tail o" the Dueue# ^ enDueue%GAppleH)F ^ enDueue%GBananaH)F ^ enDueue%G hicoH)F ^ enDueue%G0angoH)F ^ enDueue%G:atermelonH)F ^ enDueue%G3rapesH)F

CSCI03: Computer Programming (Java Application) PREPARED BY: MELJUN P C!"#ES $his code places si( strings onto Dueue, &ith the last string %G3rapesH) remaining on the top# You remove or return elements bac4 o"" the Dueue b* using the deDueue%) method# ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]