meljun cortes manual java programming csci03

Upload: meljun-cortes-mbampa

Post on 13-Apr-2018

237 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    1/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+R1Y$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 !!, andso 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 alsodeveloped to support Java#

    -eature+ o Java:

    7) imple, 1bject-oriented, and

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    2/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    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, 0aos, ./+?, @inu(, etc#

    ) 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 computerproduct generates b*te codes an architecture neutral intermediate "ormatdesigned 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 programminglanguage 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 reuired, leading to

    better per"ormance#

    Java Program ;ello

    orld10P+@ER

    + / $ E R P R E $ E R

    ;E@@1

    1R@D

    ;E@@1

    1R@D

    ;E@@1

    1R@D

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    3/62

    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++

    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#

    m*Program#Java

    10P+@ER

    + / $ E R P R E $ E R

    m*Program#class 0* Program

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    4/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    Page C

    JAA 1E2!"$S

    $he "ollo&ing are reserved b* the Java @anguage and cannot be used asidenti"iers:

    abstract continue i" protected transientBoolean de"ault implements public tr*

    Brea4 do import return void

    B*te double instance o" short volatilease else int static &hile

    &itch e(tends inter"ace super

    atch "inal long s*nchroni6ed

    har "inall* ne& thislass "loat pac4age thro&

    onst "or private thro&s

    JAA $A#A #2PES

    +#) Primitive4built in data t*pes#

    5 Categorie+

    /umeric4 integral and "loating point t*pes#

    Boolean - true ' "alse

    JAA IN#E6"AL #2PES:

    7# b*te 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#C# long - represents on integer e(actl* b*te o" storage#

    9# char represents .nicode charactersF reuires e(actl* = b*tes o" storage#

    JAA -L!A#IN6 #2PES:

    7# "loat represents a "loating point number reuiring e(actl* C b*tes o" storage#

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    5/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page 9

    $*pe Description ommon 0ethods

    Boolean +t is a class containing a Boolean "ield used "or - boolean value % ),

    &rapping a value o" the primitive t*pe Boolean getboolean % ),in an object# 5alueo" % )

    haracter +t is a class containing a char "ield used "or - char5alue % ),&rapping a value o" the primitive t*pe char compareto % ),

    in an object# 3ett*pe % ),isDigit% ),

    is@etter % ),

    to.ppercase % ),to@o&ercase % )

    Double +t is a class containing a double "ield used "or - double5alue % ),&rapping a value o" the primitive t*pe double totring%), valueo"%),

    in an object# parseDouble % ),

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    6/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page I

    $*pe Description ommon 0ethods

    1bject +t is the root o" the class hierarch*# Ever* - done%), euals%),lass has object as a superclass %or parent "inali6e%),nashcode%)

    lass)F and there"ore, all objects, including noti"* % ), tostring % )

    Arra*s, implement the methods o" the class#

    "APPE" CLASS &rapping primitive value to an object#

    1bject contains method "or manipulating a data such as converting a value toanother t*pe o" value#

    E(# string to int

    int to string%see sample program no# =)

    lass 0ethod 1utput

    +nteger parse+nt %) +nt@ong parse@ong %) long

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    7/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page O

    Sample Program No5 ''bu""eredreader command "or input

    import java#io#Fpublic class ;ello Java

    public static void main %Arra* K L args) thro&s E(ception

    Bu""eredReader br Q ne& Bu""eredReader %ne& +nputtreamReader%s*stem#in) )Fstring "irstname Q G GF

    string lastname Q G GFs*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%)Fs*stem#out#println %G;elloH ! "irstname ! G G ! lastname)F

    s*stem#out#println %Gelcome to Java ProgrammingMH)F

    N

    N

    Sample program No3 ''&rapping class program "or int

    import java#io#

    public class um+t.o

    public static void main %tring args K L) thro&s E(ception Bu""eredReader br Q ne& Bu""eredReader %ne& +nputtreamReader%s*stem#in) )F

    int num7Q>F

    int num=Q>F

    int sumQ>Fs*stem#out#println %GEnter 7stno:H)F

    num7Q+nteger#parse+nt%br#readline%))F

    s*stem#out#println %GEnter =ndno#:H)Fnum7Q+nteger#parse+nt%br#readline%))F

    sumQnum7!num=F

    s*stem#out#println %G$he sum is:H ! sum )FN

    N

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    8/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page

    JAA !PE"A#!"S 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 9 ( ) - ( )- used to group e(pressions

    8- used to access methods and variables &'in object and

    classes# 9 used "or arra*s#

    ;; 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)

    EEN#S 4objects that are "ired &hen the user-interact &ith the 3.+s

    components and containers# %see "urther e(planation)

    -"AMES 4is the component &e use "or the &indo&s %see e(ample)

    LA2!U# MANA6E"S 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*peo" 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 4uses grid o" ro&s and columns, "ills each grid &ith component#

    CarF La,out 4uses panel li4e a dec4 o" cards#

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    11/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    6riF ag La,out 4uses grid o" ro&s and columns, components are placed across

    several grid areas#

    CSCI03: Computer Programming ( Java Application )

    Page 77

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

    1BJE$

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    12/62

    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+ +ie i+ not altereF '%en t%e container i+ re+ie+

    CSCI03: Computer Programming ( Java Application )

    Page 7=

    -ig & #%e orFer La,out maintain+ t%e location o t%e component+ #%e

    component+ +ie i+ altereF '%en t%e container i+ re+ieF

    V

    V

    Border @a*out

    /orth

    East

    :est

    outh

    enter

    V

    V

    Border @a*out

    /orth

    East

    :est

    outh

    enter

    A"ter indo& is resi6ed

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    13/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page 7

    -ig &K #%e 6riF La,out manager arrange+ component+ in a ta/le

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    14/62

    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 to &'c it might possible react# $his is represented as a

    Java class included in the java#a&t#event pac4age#

    Event Li+tener 4the 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 %e A# Event+ *ierarc%,

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    15/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    $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+:

    1bject

    Event 1bject

    A$ Event

    $e(t

    Even

    +tem

    Event

    +nvocation

    Event+nput

    0ethodEvent

    ;ierarch*

    Event

    omponent

    Event

    Adjustment

    EventAction

    event

    indo&Event

    PaintEvent

    +nputEvent

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    16/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    7# emantic Event 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 events that are "ined in response to the lo&-level input or

    graphical user inter"ace interaction such as 4e*-press or "ocus-change#

    JAA$!C

    +# ingle @ine omment ' bo* te(t '++# 0ultiple @ine omment '

    bod* te(t

    bod* te(t

    bod* te(t '

    ++# ommon Javadoc $ags

    *nta( W 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 programmer2s nameF used "or classes X inter"aces#=# W version version o" the programF used "or classes X inter"aces

    # W param description o" a "ormal parameterF used "or methods X constructors#

    C# W return description o" a return valueF used "or methods#

    9# W e(ception %or W thro&s) description o" an e(ceptionF used "or methods Xconstructors#

    I# W see re"erence to a related entit*F used "or classes X inter"aces, constructors,

    methods, X data "ields#

    Sample Program U+ing JavaFoc #ag+:

    '

    pS

    javadoc comments# Javadoc comments "or classes can be bro4en into t&o parts:

    a description part X a tags part# $his is the description part# $he parts should be separated b* one empt* comment line# 'pS, 'pS also, there should be no lines

    CSCI03: Computer Programming ( Java Application )

    Page 7I

    bet&een the end o" the Javadoc comment and the beginning o" the entit* it

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    17/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    describes# 'pS

    Wauthor @il* ;ou

    Wauthor ean Bu"ano

    Wversion 7#>

    'public class $&o+nts

    int "irstFint secondF

    '

    +nitiali6es codeS "irst 'codeS and

    codeS second 'codeS to codeS o 'codeS'

    public $&o+nts %)

    "irstQsecondQ>FN

    ' +nitiali6es codeS "irst 'codeS and codeS second 'codeS to arguments

    Wparam ( value to &'c codeS "irst 'codeS is initiali6ed Wparam * value to &'c codeS second 'codeS is initiali6ed

    '

    public $&o+nts %int (, int *)

    "irstQ(FsecondQ*F

    N

    CSCI03: Computer Programming ( Java Application )

    Page 7O

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    18/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    '

    omputes the sum o" the t&o integers

    W return the sum o" the t&o integers

    '

    public int sum %) return "irst ! secondF

    N'

    +ncrements codeS "irst 'codeS b* the argument

    W param ( the value b* &hich codeS "irst 'codeS &ill be incremented'

    public void add$o

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    19/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    a# partial i" statement

    s*nta(: i" %e(pression)

    statement%s)FN

    b# "ull-i" statements*nta(: i" %e(pression)

    statement%s)F

    Nelse

    statement%s)FN

    c# /ested i"U else i" statement*nta(: i" %e(pression7)

    statement%s)F

    Nelse i" %e(pression=)

    statement%s)F

    N#

    #

    else

    statement%s)F

    N

    CSCI03: Computer Programming ( Java Application )

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    20/62

    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#Fclass i"Elsetatement

    public static void main %string K L args) thro&s e(ception

    Bu""eredReader brQne& Bu""eredReader %ne& +nputtreamReader%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#) import java#io#F

    class i"Elseample public static void main%string K L args) thro&s e(ception

    Bu""eredReader brQne& Bu""eredreader%ne&+nputtreamReader%s*stem#in))F

    +nt ageF

    *stem#out#print%GEnter *our age:H)FBageQ+nteger#parse+nt%br#redline %))F

    +" %age SQ7)

    *stem#out#println%GYou2re allo&ed to voteMH)FElse

    *stem#out#println%Gtoo *oung to voteMH)F

    NN

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    21/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page =>

    C#) import java#io#F

    class Pass&ord public static void main %string K L args) thro&s E(ception B.""eredReader brQne& Bu""eredReader %ne& +nputtreamReader

    %s*stem#in))F

    tring input Q G GFtring pass Q GpangetHF

    *stem#out#print%GEnter a pass&ord:H)F

    +nputQbr#readline %)F+" %pass#euals%input))

    *stem#out#println%GAccess 3ranterH)F

    Else

    *stem#out#println%GAccess DeniedH)FN

    N

    9#) import java#io#F

    class 3radeRange

    public static void main%string args KL) thro&s E(ception Bu""eredReader brQne& Bu""eredReader%ne&

    +nputtreamReader%s*stem#in))F

    +nt gradeF*stem#out#print%GEnter desired 3rade:H)F

    3radeQ+nteger#parse+nt%br#readline%))F+" %grade Q7>> Xgrade SQ8>)

    *stem#out#println%G1utstandingH)FElse i" %grade Q8 X grade SQ>)

    *tem#out#println%Gatis"actor*H)F

    Else i" %grade QO8 X grade SQO9)*tem#out#println%G/eeds +mprovementH)F

    Else i" %grade QOC X grade SQ9>)

    *tem#out#println%G

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    22/62

    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*

    case const7: statement%s)F brea4F

    case const=: statement%s)F brea4Fcase const: statement%s)F brea4F

    U

    case constn: statement%s)F brea4Fde"ault: statement%s)F

    N

    $he brea4 statement causes the program "lo& to e(it "rom the bod* o" the s&itch

    construct#

    $he de"ault 4e*&ord 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 notmatch an* o" the case constants#

    E(amples:

    7#) import java#io#Fclass s&itchtatement

    public static void main%string args KL) thro&s E(ception

    Bu""eredReader brQne& Bu""eredReader%ne&+nputtreamReader%s*stem#in))F

    int nF

    s*stem#out#println%GPlease enter an integer:H)FnQinteger#parse+nt%br#readline%))Fs&itch %n)

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    23/62

    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 : s*stem#out#println%G$hreeH)F brea4Fase C: s*stem#out#println%G

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    24/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page =

    #) import java#io#Fclass &itchhar

    public static void main%string args K L) thro&s E(ception

    Bu""eredReader brQne& Bu""eredReader%ne&

    +nputtreamReader%s*stem#in))Ftring m* charF

    *stem#out#println%GEnter a letter:H)F

    0*harQcharSbr#readline&itch%m*char)

    ase ZA2 : s*stem#out#println%GAdorableH)Fbrea4Fase ZB2 : s*stem#out#println%GBeauti"ulH)Fbrea4F

    ase Z2 : s*stem#out#println%GharmingH)Fbrea4F

    ase Z.2 : s*stem#out#println%G.gl*H)Fbrea4F

    De"ault : s*stem#out#println%G/o ommentH)FN

    N

    N

    #%e %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)

    statement%s)FN

    #%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, thestatements are e(ecuted repeatedl* as long as the e(pression is true#

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    25/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page =C

    *nta(: do

    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" statementsrepeatedl* until a certain condition is reached#

    *nta(:

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    26/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page =9

    =#) import java#io#F

    public class "actorial public static void main %string KL args) thro&s E(ception

    Bu""eredReader brQne& Bu""eredReader%ne& +nputtreamReader%s*stem#in))F

    F a!!) +nt ", (, ansF

    *stem#out#println%GEnter a number:H)F

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    27/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page =I

    C#) import java#io# public class gcd

    public static void main %string KL args) thro&s E(ception

    Bu""eredReader brQne& Bu""eredReader%ne& +nputtreamReader%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%))Fhile %num=MQ>)

    num7Qnum=F num=QtempF

    N

    *stem#out#println%G$heir 3reatest ommon Divisor is:H ! num7)FN

    9#) import java#io#F public class Reverse

    public static void main %string KL args) thro&s E(ception

    Bu""eredReader brQne& Bu""eredReader%ne& +nputtreamReader%s*stem#in))F

    +nt num, rightdigitF *stem#out#println%GEnter a number:H)F

    /umQ+nteger#parse+nt%br#readline%))F

    Do

    rightdigitQnum [ 7>F

    *stem#out#println%rightdigit)F/umQnum'7>F

    N

    &hile %numMQ>)F

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    28/62

    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+ !/ect+

    lass re"ers to a group or set o" objects having the same states and behavior# +t can alsobe 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 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*#

    -ig 50

    /ote: A class usuall* represents the GblueprintH o" all objects belonging to it#

    !JEC# "ELA#I!NS*IPS:

    DA$A

    Attributes %or states)

    0E$;1D

    Behaviors %or "unctions X procedures)

    @ A / A 0 E

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    29/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    7#) Association 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 =

    -ig 5&

    Ever* tudent has a $eacher

    ample +llustration /o# =

    3ender

    AgeEmplo*ee ode

    Years o" ervice

    ubjects

    3ender

    Age3rade

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    30/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    -ig 55

    UniieF 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 53

    toc4 /o#$itle

    Rating

    5ideo +tem

    +D

    /ame5ideo Rented

    5ideo tore

    ostumer

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    31/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

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

    CSCI03: Computer Programming ( Java Application )

    Page >

    -ig 5Q

    Account

    3et Balance

    Deposit

    ithdra&

    Balance

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    32/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

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

    CSCI03: Computer Programming ( Java Application )

    Page 7

    1rder;eld

    1rder

    Bac4-order

    1rderdiscarded

    1rderlosed

    1rder

    Delivered

    1rder+tem

    Placed

    1rder

    reate

    d

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    33/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    -ig 5G

    $he lass Diagram is used to describe the attributes X behaviors o" objects in the

    s*stem#

    UML S2M!LS:

    Cla++ S,m/ol:

    Acce++ Speciier 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#

    CSCI03: Computer Programming ( Java Application )

    /A0E

    A$$R+B.$E

    1PERA$+1/ 1R

    0E$;1D

    5ideo Rented

    $itleRent Dateharge

    Due date

    5ideo Rented

    3entRent Date

    etDue Date

    lass /ame

    - Attributes

    - Attributes

    - Attributes

    ! 0ethods! 0ethods

    ! 0ethods

    Ban4 Account

    Balance

    Account no#tatus

    ! Deposit % )

    ! ithdra& % ) ! +nuire Balance % )

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    34/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    Page =

    $E-ININ6 $ESI6NIN6 CLASSES:

    Java, being a tightl* cast language, has strict rules &' regard to the process in &'cdata 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#

    $eining Cla++e+:

    A class de"inite consists several constructs "or de"ining X declaring the "":7#) Attributes 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 this method de"ines the speci"ics o" object creation#

    #) tandard 0ethods theses methods to change or access the private data in an object#

    C#) ustom 0ethods these are methods that implement the business rules#

    -ig 5H

    CSCI03: Computer Programming ( Java Application )

    /ame

    Attributes

    1perations

    or 0ethods

    Attributes declaration

    onstruction de"inition

    stand 0ethods de"initioncustom methods de"inition

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    35/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    Page

    $e+igning Cla++e+:

    7#) De"ine class name

    *nta(:access]speci"ierS class class]nameS bod*F N

    =#) +denti"* Attributes

    *nta(:

    access]speci"ierS data]t*peS attributesSF #) 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(:access]speci"ierS class /ame %argument @istsU)

    constructor bod*

    Nnote: $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" anobject#

    C#) reate tandard 0ethod

    0utator %setters) methods used to change data#

    *nta(:

    access]speci"ierS void set ??? %argument @istssU)

    ''((( is a "ield variable &'c is assigned &'a speci"ic

    value ''in the method bod*#

    Accessor %getters) methods used to access or retrieve data#

    *nta(:access]speci"ierS return$*peS get ((( %)

    ''((( is usuall* a "ield variable &hose value is returnedb* ''the method#

    /ote: $he accessor method uses the return 4e*&ord at the end o" its de"inition#

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    36/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page C

    9#) reate ustom 0ethod

    *nta(:access]speci"ierS return]t*peS method /ame %argument@istsU)

    ''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 Public static void main %string args K L)

    tudentRecord m*tudent Q ne& tudentRecord %GPearl Ruth DamiasH,GE0P-

    >7H)Fm*tudent#set3rade %8#88, 89#9)F

    s*stem#out#println%Gtudent /ame:H ! m*tudent#get/ame%))F

    s*stem#out#println%G3rade in English:H ! m*tudent#get3radeEng%))Fs*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 private tring student+dF

    private double gradeEngF A$$R+B.$Eprivate double grade0athF

    public tudentRecord %string n, string sid) name Q nF

    student+d Q sidF 1/$R.$1R

    N

    public void main set3rade %double e, double m)F gradeEng Q eFgrade0ath Q mF 0.$A$1R ' E$$ER

    N

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    37/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page 9

    Public string get/ame%) Return nameF

    N

    public string gettudent+d%) return tudent+dF

    N AE1R ' 3E$$ER

    public double get3radeEng%) return gradeEngF

    N

    public double get3rade0ath%)

    return grade0athFN

    Public double getAverage%) Double aveF

    ave Q %grade0ath ! gradeEng)'=F .$10 0E$;1D

    Return aveFN

    #*IS e,'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 variableX methods#

    ample Program /o# =

    Public class ellphone

    Private string brandF A$$R+B.$E Private string modelF

    Public cellphone %) $his#brand Q G/1+AHF 1/$R.$1R $his#model Q GII>>HF

    N

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    38/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page I

    Public void setBrand %string brand) $his#brand Q brandF

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

    public void set0odel %string model) this#model Q modelF

    N

    public tring getBrand %)

    return this#brandF

    N AE1R ' 3E$$ER

    public tring get0odel %) return this#modelF

    N

    '' public void Ring %)

    '' s*stem#out#println%G 0Y phone is ringingUH)F

    '' N .$10'' public void vibrate %) 0E$;1D

    '' s*stem#out#println%G 0Y phone is vibratingUH)F

    '' N

    public class $est public static void main %tring args K L)

    cellphone cell7F ''null value "or cell7 variablecellphone cell=Qne& ellphone%)F ''cellphone class value "or cell= variable

    cell7Qne& ellphone%)F

    cell7#setBrand %G/1+AH)Fcell7#set0odel %GOI9>H)F

    s*stem#out#println%G

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    39/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page O

    UML $iagram or Sample Program No 5

    UML $iagram or Sample Program No &

    ellphone

    - brand : string

    - model : string

    cellphone %)

    etBrand%brand :

    string) voidet0odel%model :

    string) void

    getBrand%) : stringget0odel%) : string

    $E$

    main %args : tring K L) void

    tudent Record

    - name : string

    - student +D : string

    - gradeEng : double-grade0ath : double

    ! tudentRecord%)! set3rade%e:double,m:double) void

    !get/ame%) : string! gettudent+d%) : string! get3radeEng%) : double

    ! get3rade0ath%) : double

    ! getAverage%) : double

    im le lass

    ! main %args : string K L) :

    void

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    40/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page

    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* acommon 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 data t*pe o" arra*/e& operator "or memor* allocation

    @ength si6e o" the arra*#

    E(ample:tring names K L Q ne& string K9LF

    +llustration:

    +nde( - > 7 = C

    -C inde() storing# tring values

    inside the memor* o" the computer#

    Arra, Illu+tration:

    *nta(: t*pe arra*/ame Q a, b, c, d,U##nNF

    E(amples: int ( K L Q 7, =, , C, 9, INF

    Boolean b K L Q true, true, "alseNFDouble grade K L Q , 88, 8, O9, 7>>, I#8NF

    tring names K L Q GAnnH, GBenH, GhinaHNF

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    41/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page 8

    ACCESSIN6 S#!"IN6 ALUES IN AA"A2S:

    *nta(: arra*/em Kinde(L valueF

    $he process o" storing values in an arra* is also re"erred to as GpopulatingH thearra*:

    E(ample: Representation:

    ?K>L Q OF

    ?K7L Q 8F?K=L Q CF

    ?KL Q 7=F elements

    > 7 = inde(

    ample Program /o# 7

    +mport java#io#F

    Public class Arra* mple

    public static void main %string args K L) thro&s E(ception B.""eredReader brQne& Bu""eredReader%ne& +nputtreamReader%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)FF + (#lenghtF i!!)

    *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%Gn $he numbers areH)FF + (#lenghtF i!!)

    *stem#out#println%G( K G! + !HL Q G ! ( KiL)F

    N

    7=C8O

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    42/62

    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 public static void main %string args K L)

    intK L Denver Q 79>>>>>I, 77>>>>,=>O9=77>NF

    intK L Philadelphia Q ne& int KDenver#lengthLFintK L total Q ne& int KDenver#lengthLF

    int averageF

    PhiladelphiaK>L Q 79>=>>>>F

    PhiladelphiaK7L Q 7O>>>FPhiladelphiaK=L Q =7C>>>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)'F

    *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#

    lass Rangelass

    +nt K L ma4eRange %int lo&er, int upper) +nt arr KL Q ne& int K %upper lo&er) ! 7LF

    F + arr#lengthF i!!)

    ArrKiL Q lo&er !!:N

    return arrF

    N

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    43/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    public static void main %string args K L)

    int thearra*KLFRange lass theRange Q ne& Rangelass%)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

    F + 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#FPublic class tudentRecord

    public static void main %string args K L) thro&s E(ception

    B.""eredReader brQne& Bu""eredReader%ne& +nputtreamReader%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

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    44/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    *stem#out#println%Gearch a student:H)F

    *stem#out#println%GEnter the name o" the student:H)Ftring pangalan Q br#readline%)F

    everal programming models have evolved to help programmers in carr*ing-outthe 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 techniue o" solving a problem b* brea4ing do&n a

    program into smaller pats that are arrange X e(ecuted in a logical seuence# Each o"these smaller solutions is used to per"orm a bloc4 o" codes called "unction#

    $his techniue o" programming is also 4no&n as process-oriented programming

    since it concentrates on the procedures# ;o&ever, the approach is not ideall* suited "ordeveloping 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 theprocess involved#

    !JEC#

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    45/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    1bject-oriented programming %11P) is a techniue o" solving a problem that usesobjects# $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 onthese objects# Basicall*, 11P model describes a program that uses a collection o" objects

    interacting &' each other#

    CSCI03: Computer Programming ( Java Application )

    Page C

    1ne o" the principal advantages o" using object-oriented programming techniue is that itenables 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

    techniues such as abstraction X encapsulation %or in"ormation hiding)

    Abstraction the process o" pic4ing-out %abstracting) the common

    "eatures o" objects X procedures# +t "ocuses on the essential characteristics

    o" an object#

    Encapsulation 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 inso"t&are development, &'c in their results in cost bene"its#

    +nheritance allo&s an object to e(tend its char to another object#

    #) Resilience to change &' the use o" pol*morphism#

    Pol*morphism abilit* to process objects di""erentl* depending on theirt*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

    #) Abilit* to use members o" a "amil* o" classes interchanging in methods#

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    46/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    *nta( "or implementing inheritance:Public class subclass e(tends super class

    ''attributes or data declarations

    ''constructor X method de"initionsN

    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 tode"ine di""erent circum"erence methods "or an* number o" derived classes, such ascircles, 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 t&o or more implementations o" essentiall* the same "unctionalit* touse the some name X the t*pe and order o" arguments in the parent class#

    ample Program /o# 7

    lass tudentRecord

    Private tring nameF

    Private string student+dFPrivate double gradeF

    Private string subjectF

    Public tudebtRecord %)

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    47/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    /ame Q nullF

    student+d Q null FN

    1verloaded

    public tudentRecord %string n, string sid) onstructor

    name Q nFstudent+d Q sidF

    N

    CSCI03: Computer Programming ( Java Application )

    Page C9

    Public void set3rade %double g, string s)

    3rade Q gF

    ubject Q sFN

    public void set3rade %string s, double g) grade Q gF 1verloaded

    subject Q sF 0ethods

    N#

    #

    #N

    ample Program /o# =

    lass tudentRecord= Private string nameF

    Private string student+dF

    Private double gradeF Private string subjectF

    Public tudentRecord%) /ame Q nullF

    student+d Q nullF

    N

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    48/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    :

    : public void displa*3rade%)

    s*stem#out#println%Gubject:H ! subject)F 1verridden

    s*stem#out#println%G3rade:H ! grade)F 0ethods

    N :

    :N

    class AnotherRecord e(tends tudnetRecord=

    private double grade=F

    private string subject=

    CSCI03: Computer Programming ( Java Application )

    Page CI

    Public tudentRecord %)F

    : :

    N

    public void displa*3rade%) s*stem#out#println%Gubject:H ! subject)F

    s*stem#out#println%Ggrade:H ! grade)F

    s*stem#out#println%Gubject=:H ! subject=)Fs*stem#out#println%Ggrade=:H ! grade=)F

    N

    : :

    N

    C!MPA"IS!N: !verloaFing + !verriFing

    15ER@1AD+/3 15ERR+D+/3

    1verloaded methods supplement T overriding method %largel*)

    each other replaces the method it overrides#

    1verloaded methods can e(ists, T Each method in a parent class can be

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    49/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    in an* number, in the same class# overridden at most once in an* one

    subclass#

    1verloaded methods must have T overriding methods must have argu-

    di""erent argument lists# ment lists o" identical t*pe X order

    %other&ise the* are simpl* treated asoverloaded methods)#

    $he return t*pe o" an overloaded T the return t*pe o" overriding method

    method ma* be chosen "reel*# must be identical to that o" the me-

    thod it overrides#

    CSCI03: Computer Programming ( Java Application )

    Page CO

    ample Program /o#

    Public class 0*Rectangle Protected double &idthFProtected double lengthF

    Public 0*Rectangle %double &idth, double length)

    $his#&idth Q &idthF$his#length Q lengthF

    N

    public 0*Rectangle%) this%7>#>,7>#>)F

    N

    public string totring%)

    string rec Q Gn &idth:H ! this#&idth ! Gn length:H ! this#lengthFreturn recF

    N

    Nclass 0*Bo( e(tends 0*Rectangle

    private double heightF

    public 0*Bo(%double &idth, double length, double height)

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    50/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    super%&idth, length)F

    this#height Q heightFN

    public 0*Bo( %double height)

    super%)F

    this#height QheightFN

    public 0*Bo(%) this%7>#>)F

    N

    public string totring%)

    string bo( Q super#totring%) ! Gn height:H ! this#heightFreturn bo(F

    N

    N

    CSCI03: Computer Programming ( Java Application )

    Page C

    SUPE" e,'orF

    ontains a re"erence to the parent-class %superclass) object# +t is used to accessmembers o" a class inherited b* the class in &'c it appears#

    #%e A/+tract Cla++ Interace

    Abstract class 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 ma4ethem concrete b* implementing the abstract methods#

    +nter"ace 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 &' theGimplementsH 4e*&ord#

    A/+tract Cla++:

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    51/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    An e(ample o" an abstract class 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 toe(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 class name S

    ''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

    Interace

    hape

    ;e(agonircleRectangle

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    52/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

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

    CSCI03: Computer Programming ( Java Application )

    Page 9>

    5ehicle

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    53/62

    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 oneclass#

    E.ception+ 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 techniues 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##) 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

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    54/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    1thers

    1ther

    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 reuired class in the &rong "older#hen a program cannot locate a reuired 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 )

    +nternal'ErrorE(ception

    1ut1"0emor*E(ception

    Error

    Arra*inde(1ut1"BoundsE(ception

    Arithmetic E(ception

    Runtime E(ception

    +1 E(ception

    E(ception

    $hro&able

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    55/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    Page 9=

    ample Program /o# 7

    Public class computeError Public static void main%tring argsKL)

    +nt numQ7IF

    +nt denQ>F+nt resultF

    ResultQnum'denF

    NN

    Error Cla++ represents more serious errors "rom &hich *our program usuall* cannotrecover# $hese are errors that *ou probabl* made in *our programs &hen *ou misspelled

    a class name or store a reuired class in the &rong "older# hen a program cannot locatea reuired 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 illegalarithmetic operations#

    ample Program no# 7

    Public class computeError

    Public static void main%tringargsK L) +nt numQ7IF+nt denQ>F

    +nt resultF

    ResultQnum'denFN

    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 bedi""erent i" *ou include lines at the beginning o" *our program)#

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

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    56/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page 9

    $he most o"ten used error-handling solution has been terminate the o""ending program#

    Public class 0athErrorample7 Public static void main%tring argsK L)

    +nt numQ7, denomQ>F resultF

    +" %denomQQ>)*stem e(it%7)F

    ResultQnum'denomF

    NN

    #r, Catc% anF -inall,

    *nta(: public class some0ethod thro&s someE(ception

    $r*

    ''statements that might cause an E(ceptionN

    catch%someE(ception and E(cdeption+nstance)

    ''&hat to do about itN

    "inall* ''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 programN

    ''statements here e(ecute even i" there &as no E(ceptionN

    note: +" an E(ception occurs during the e(ecution o" the tr* bloc4, then the statementsin 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 orrelease 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*&ordGthro&sH "ollo&ed b* an GE(ception t*peH in the method header#

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

    $erminates the program

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    57/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    CSCI03: Computer Programming ( Java Application )

    Page 9C

    #*"!IN6 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 onestatement, 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 seuence until match is "ound "or theE(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 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>,=>,>,C>)F

    $r*

    ResultQnum'denResultQarra*KnumL

    Ncatch%ArithmeticE(ceptionError)

    s*stem#out#println%GError 1ccurred in Arithmetic omputationH)F

    Ncatch%inde(1ut1"BoundsE(ception erro)

    s*stem#out#println%Error 1ccurred in inde(ingH)F

    N

    NN

    note: 0ultiple$r*atch class declares "our integers and an integer arra* &ith "ourelements in the main%) method, the tr* bloc4 e(ecutes and the "irst statement &ithin thetr* 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 iss4ipped#

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

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    58/62

    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#

    Public class rite@istample Public void &rite@ist%)

    printriter outQnullF

    tr* s*stem#out#println%GEntering tr* statementHF

    outQne& Printriter%ne&

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    59/62

    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#F

    lass LF

    $r*

    *stem#out#println%Gn Enter a line to be saved to dis4:H)F+nt b*tes Q s*stem#in#read%bu"")F

    "ile1utputtream "ile1ut Q ne& $1P

    7

    =

    B1$$10Element >

    Element 7

    Element =

    Element

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    60/62

    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 anelement onto the top o" the stac4#

    s#push%G1neH)Fs#push%G$&oH)F

    s#push%G$hreeH)F

    s#push%G

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    61/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    Although the stac4 class issn2t uite use"ul, it provides the "unctionalit* "or a ver*

    common and established data structure#

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

    CSCI03: Computer Programming ( Java Application )

    Page 9

    UEUES

    ^ueue is a container li4e the stac4s but ituses "irst-in-"irst-out %

  • 7/27/2019 MELJUN CORTES MANUAL JAVA Programming CSCI03

    62/62

    CSCI03: Computer Programming (Java Application)

    PREPARED BY: MELJUN P C!"#ES

    $his code places si( strings onto ueue, &ith the last string %G3rapesH) remaining

    on the top# You remove or return elements bac4 o"" the ueue b* using the deueue%)method#

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