core java part2

Upload: martinsdebo

Post on 04-Jun-2018

259 views

Category:

Documents


2 download

TRANSCRIPT

  • 8/13/2019 Core Java Part2

    1/74

  • 8/13/2019 Core Java Part2

    2/74

  • 8/13/2019 Core Java Part2

    3/74

    0

    OBJECT ORIENTED

    PROGRAMMING

    Encapsulation (Data hiding & Method abstraction) Inheritance (IS-A Relationship) Polymorphism

    Method Signature !erloading !erriding

    "onstructors this or super #inal & static Abstract class Inter$ace

    Encapsulation

    Data hiding&ne of the sound ob'ect-oriented programming techni1ues is hiding the data%ithin the class by

    declaring them

    %ith private accessibility modifier. Making such 2ariables a2ailable outside the class through publicmethods. 3ata hiding says 4restrict access and modification of internal data items through the useof getter and setter methods5.Example:

    public class User6//Data hidingprivate (tring username7private (tring pass%ord7

    public 2oid setUsername!(tring name#6if!!name 89 null# ** name8955 #6

    username 9 name7

    else6

    (op!4Username cannot be null or empty5#7

    public (tring getUsername!#6return username7

    Method Abstraction&ne of the sound ob'ect-oriented programming techni1ues is 4Hiding method implementation complexity

    from

    outside users5 is called as method abstraction.

    Encapsulation % Data hiding Method Abstraction'

  • 8/13/2019 Core Java Part2

    4/74

    Encapsulation combines !or bundles# data members %ith method members together !or the facility thatbundles data %ith the operations that perform on that data is called as encapsulation#.Example:

    public class /uthentication6//Data hidingprivate (tring username7

    private (tring pass%ord7

    public 2oid setUsername!(tring name#6if!!name 89 null# ** name8955 #6

    username 9 name7

    public 2oid set;ass%ord!(tring p%d#6if!!p%d 89 null# ** p%d8955 #6

    ;ass%ord 9 p%d7

    //Method abstractionpublic boolean is

  • 8/13/2019 Core Java Part2

    5/74

    nheritance3efine common methods in base class and specific methods in subclass.

    Example:class Figure6 ==;arent

    class pri2ate int %idth7pri2ate int height7public Figure!int %@ int

    h#6%idth 9 %7

    height 9

    h7

    public int getidth!# 6

    return %idth7

    public int getHeight!# 6

    return height7

    public void move()!

    "#stem$out$println(%Move method$$$%);

    &public void resi'e()!

    "#stem$out$println(%esi'e method$$$$%);

    &public void hide()!

    "#stem$out$println(%ide method$$$%);

    &public void sho*()!

    "#stem$out$println(%sho* method$$$%);&

    class Gectangle extends Figure6 ==childclass public Gectangle!int %@ int h#6

    super(*+h);//nvo,es immediate superclass matching constructor

    ==subclass specific method.double area()!

    return getHeight!# getidth!#7

    class $riangle extends Figure6public $riangle!int %@ int

    h#6

    super!%@h#

    7

    ==subclass specific method.

  • 8/13/2019 Core Java Part2

    6/74

    Double area()!

  • 8/13/2019 Core Java Part2

    7/74

    Geturn . getHeight!# getidth!#7

    - .igure

    -%idth-height

    JFigure!#Jgetidth!#JgetHeight!#move()resi'e()hide()sho*()

    -

    ectangle

    JGectangle!#Jgetidth!#JgetHeight!

    #

    Jmo2e!#Jresi"e!#

    Jhide!#Jsho%!#

    area()

    - 0riangle

    J$riangle!#Jgetidth!#JgetHeight!#Jmo2e!#Jresi"e!#

    Jhide!#Jsho%!#area()

    1ote:

    2ccessibilit# UM4 s#mbol

    ;ri2ate -

    3efault K

    ;rotected L

    ;ublic J

    In the abo2e example@ Gectangle "52 Figure. (imilarly@ $riangle "52 Figure. (o@ inheritance is alsocalled as "52relationship.$he base class common methods mo2e!#@ resi"e!#@ hide!#@ and sho%!# are reused in the subclassesGectangle and$riangle. Hence the main ad2antage %ith inheritance is Code EU"26407$$he base class is also called as superclass@ supertype@ or parent class. $he deri2ed class is alsocalled as subclass@ subtype@ or child class.In 'a2a@ extends key%ord is used to inherit a superclass.

    Example:class Gectangle extends Figure6

    In 'a2a@ a class can inherit at most one superclass. $his is called single le2el inheritance.Example:

    class C extends /@ )6 ==Compilation error.Conclusion: +a2a does not support multiple inheritance %ith classes but supports %ith interfaces.

    $he inheritance relationship is represented as ierarchical classi3ication$

    .igur

    e

  • 8/13/2019 Core Java Part2

    8/74

  • 8/13/2019 Core Java Part2

    9/74

  • 8/13/2019 Core Java Part2

    10/74

    Example:class /ddition6

  • 8/13/2019 Core Java Part2

    11/74

    public int add!int x@ int y#6public int add!int x@ int y@ int "#6

    public float add!float x@ float y#6

    public double add!double x@ double y#6

    public float add!int x@ float y#6public float add!float x@ int y#6

    /ll abo2e methods are o2erloaded %ith each other./ddition ob' 9 ne% /ddition!#7ob'.add!,@0#7==compiler maps %ith add!int@ int#ob'.add!,@0@#7 ==compiler maps %ith add!int@ int@int#

    0he overloaded methods are resolved b# the compiler at compilation time$ ence overloadingis also

    ,no*n as

  • 8/13/2019 Core Java Part2

    12/74

    Figure 6 Gectangle!int%@ int h# 6

    super!%@ h#7

    //overriding method

  • 8/13/2019 Core Java Part2

    13/74

    Criteria &2erriding &2erloading

    Method signature Must be same Must be different.

    Geturn type Must be same. e2er considered.

    /ccessibility modifier Must be same or Dess restricti2e. e2er considered.

    ;ublic double area!# 6

    Geturn %idth height7

    public class &2erriding3emo 6public static 2oid main!(tringAB args# 6

    ==superclass ob'ect assigned to superclass reference 2ariableFigure fGef 9 ne% Figure!#7

    (op!fGef.area!##7 ==. ==area!# from Figure class

    ==subclass ob'ect assigned to subclass reference 2ariableFigure fGef, 9 ne% Gectangle!,@0#7(op!fGef,.area!##7 ==0. //area() 3rom ectangle class$

    $he method o2erriding is resol2ed at runtime based on actual ob'ect type but not Geference type. Henc

    method o2erriding is also kno%n as Date )inding or dynamic polymorphism.

    D#namic Method Dispatch (DMD):Method o2erriding is also kno%n as 3ynamic Method 3ispatching.

    Example:class Figure6

    2oid area!#6

    class Gectangle extends Figure6

    2oid area!#6

    class $riangle extends Figure6

    2oid area!#

    6

    Figure fGef 9 ne% Gectangle!#7fGef.area!#7 ==area!# method from Gectangle ob'ect is in2oked.

    fGef 9 ne% $riangle!,@0#7

    fGef.area!#7 ==area!# method from $riangle ob'ect is in2oked.

    $he method o2erriding is also called as 3ynamin Method 3ispatching@ 3ynamic ;olymorphism@ or Date

    )inding.

    Di33erence bet*een overloading and overriding:

  • 8/13/2019 Core Java Part2

    14/74

    $hro%s clause Must not thro% ne% checked

    exceptions.

    e2er considered.

    3eclaration context / method must only be

    o2erridden

    / method can be o2erloaded in

    the

    Method call resolution Method o2erriding resol2edat

    runtime based on actualob'ect type. It is also called

    Method o2erloading resol2ed atcompile time based onGeference type. It is alsocalled as static polymorphism

    Constructor$he purpose of the constructor is initiali'ation follo%ed by instantiation.

    Constructor ules:a# $he name of constructor must be same as classname. b# $he only applicable modifiers for the

    constructors are:i# ;ublic ii# protected iii# no accessibility i2#pri2ate c# $he constructor must not return any type not e2en 2oid.

    Example:;ublic class )ox6

    Int %idth7Intheight7Int depth7public 6ox(int *+ int h+ int d)!

    *idth >*; height> h;depth >d;

    &

    )ox b 9 ne* 6ox(8+9+); //nstantiation

    Constructors are either 3efault constructors or ;arameteri"ed constructors:

    Constructor

    s

    3efault constructors ;arameteri"ed

    construcotrs

  • 8/13/2019 Core Java Part2

    15/74

    Implicit default constructor Explicit default constructors ;rimiti2e type

    Geference type

    De3ault constructorConstructor %ithout parameters is called as 3efault constructor.

  • 8/13/2019 Core Java Part2

    16/74

  • 8/13/2019 Core Java Part2

    17/74

    9 height7 depth 97

    =)ox!int %idth@ int height@ int depth#6this.%idth 9 %idth7this.height 9

    height7 this.depth9 depth7

    =

  • 8/13/2019 Core Java Part2

    18/74

  • 8/13/2019 Core Java Part2

    19/74

    args# 6 $hree ob' 9 ne%$hree!#7

    ?/:,

    0

  • 8/13/2019 Core Java Part2

    20/74

    super or this$here are t%o forms of OsuperP or OthisP: i# %ithout parantheses ii# %ith parantheses

  • 8/13/2019 Core Java Part2

    21/74

    3in a l * $r $t c l a sses

  • 8/13/2019 Core Java Part2

    22/74

    If all methods in class are completely implemented@ then instead of declaring e2ery method asfinal@ better declare class itself as final.)y default@ all methods in a final class are final.

    Example:final ;ublic class

    &ne6 2oid

    meth,!#62oid meth0!#6

    Final classes cannot be extended.Example:

    final class &ne6class $%o extends &ne6=/C$E

    1ote:,# Final %ith 2ariables pre2ents re-initiali"ation.

    0# Final %ith methods pre2ents method o2erriding.# Final %ith classes pre2ents inheritance.

    "tatic(tatic is a modifier used %ith:

    a#

  • 8/13/2019 Core Java Part2

    23/74

    0# (tatic 2ariables are associated %ith Method area.# Docal 2ariables are associated %ith "tac, area.R# Final 2ariables are associated %ith Constant ool area.

  • 8/13/2019 Core Java Part2

    24/74

    "tatic methodsRules

    ,# / static method cannot access instance 2ariables.0# / static method cannot access instance methods.# Cannot use this or super from static context.

    e can use static members from non-static context@ but not 2ice 2ersa.It is al%ays recommended to use class name to access static members rather than ob'ect name.

    2bstract class&2 e rr id e

    ublic double area()!eturn *idth A height;

    &

    Class $riangle extends Figure6$riangle!int %@ int h#6super!%@ h#7

    mailto:@Overridemailto:@Override
  • 8/13/2019 Core Java Part2

    25/74

    ublic double area()!eturn B$ A *idth A height;

  • 8/13/2019 Core Java Part2

    26/74

    &

    Class /bstract3emo6;ublic static 2oid main!(tringAB args#6

    ==Figure fGef 9 ne% Figure!,@0#7 ==C$E since abstract classes cannot be instantiated.

    Figure fGef 9 ne% Gectangle!,@0#7==(ubclass ob'ect is assigned to superclass ref2ariable(&;!fGef.area!##7 == area!# method from Gectangle isin2oked. fGef 9 ne% $riangle!,@0#7

    (&;!fGef.area!##7 == area!# method from $riangle is in2oked.

    2d v an ta g es * ith 2 b st r a c t cla s s e s:,# Forces the subclass to pro2ide method implementation

    0# /chie2es 3ynamic ;olymorphism.

    nter3acesInterface pro2ides ser2ice details but not its implementation details.

    For example@ the stack interface says its operations push!# and pop!# but not its actualimplementation details such as array or linked list. e !ser2ice pro2ider# can change stackimplementation from array to linked list %ithout affecting to client applications !ser2ice users#.

    "ervice User

    nter3ace ("erice Details)

    "ervice rovider

    "#ntax:

    W modifierX interface Winterface nameX Aextends interface8 interfacen6

    Wfield declarationsX

    Wmethod declarationsX

    . i e ld s * $r $t n te r3 a ce)y default@ all interface fields are public static 3inal.

    /ll of the follo%ing field declarations are e1ual:a# ublic static 3inal int (IQE 9 ,7 ==3eclaring public static final explicitly is redundant butnot error. b# static final int (IQE 9 ,7

  • 8/13/2019 Core Java Part2

    27/74

    c# final int (IQE 9 ,7

  • 8/13/2019 Core Java Part2

    28/74

    ;ublic interface &ne6

    ;ublic class $%oimplements &ne6

    ;ublic interface &ne6

    ;ublic interface $%oextends &ne6

    ;ublic interface &ne6

    ;ublic interface $%o6;ublic class $hreeimplements &ne@

    ;ublic interface

    &ne6

    ;ublic interface$%o6 ;ublic

    d# int (IQE 9 ,7

    /ll interface 2ariables must be initiali"ed in the declaration section.Example:

    ;ublic static final int (IQE 9 8B7 ==declaration cum initiali"ation;ublic static final int (IQE7==C.E saying Missing Initiali"ation

    Methods *$r$t nter3ace)y default@ all interface methods are public abstract. Hence@ interface is a pure abstract class.

    /ll of the follo%ing methods declarations are e1ual:a# public abstract 2oid meth!#7b# abstract 2oid meth!#7c# 2oid meth!#7

    /ll methods in an interface are abstract@ hence@ interfaces cannot be instantiated. Ho%e2er@interfaces can be used as reference 2ariables.Example:public interface (tack6

    public 2oid push!int x#7

    public int pop!#7

    public class (tackImpl implements(tack6

    pri2ate final int (IQE 9 ,7public 2oid push!int x#6

    ==impl using arrays

    public int pop!#6

    ==impl using arrays

    "tac, se3 9 ne% (tackImpl!#7

    Constructors *$r$t inter3ace/ll 2ariables in an interface are final constants@ %hich must be initiali"ed in the declaration section itself.

    /lso@ all methods in an interface are abstract@ such an interfaces cannot be instantiated.Hence@ Interface does not need constructors at all i.e.@ interfaces ne2er ha2e constructors at all.

    nheritance *$r$t nter3ace/ class inherits an interface using implements key%ord. )ut an interface inherits another interface usin

    extends key%ord. Either class or an interface can inherit any number of interfaces.Example:

  • 8/13/2019 Core Java Part2

    29/74

    2bstract class nter3ace

    Can contain concrete methods. /ll methods are abstract.

    Can contains non final * non static /ll 2ariables must be static and final.

    Can contains any number of constructors. e2er contains constructors at all.

    3oes not support multiple inheritance. (upports multiple inheritance.

    +a2a supports multiple inheritance by inheriting multiple interfaces.

    $he subclass of an interface either implement all abstract methods or declare subclass as an abstractclass. $he accessibility modifier of the subclass method must be public.Example:

    Interface &ne6

    ;ublic 2oidmeth,!#7 ;ublic2oid meth0!#7

    Class $%o implements&ne6ublic 2oid meth,!#6ublic 2oid meth0!#6

    abstract Class $%o implements&ne6 ;ublic 2oid meth,!#6

    Mar,er nter3aceIf our class gets special pri2ilege by inheriting an interface@ such an interface is called as marker

    interface.

    Example:+a2a.io.(eriali"able+a2a.lang.Gunnable

    If an interface does not ha2e any methods@ it is al%ays called as Marker interface.Example:

    +a2a.io.(eriali"able

    E2en though an interface contains methods %hich gi2es special pri2ilege to our class@ then such aninterface is also called as Marker Interface.Example:

    +a2a.lang.Gunnable - run!# method.

    uestion: $hough interface is a pure abstract class@ %hy do %e need an interfaceY0o support multiple inheritance and if a subclass already implements another class@ then subclasscannot inherit our abstract class. $his restriction is not applicable for an interface@ since a class caninherit any number of interfaces.

    Di33erence bet*een abstract class and nter3ace:

  • 8/13/2019 Core Java Part2

    30/74

    Exceptio Error

    Exceptions are caused b# ourprogram and hence recovarable. /fterreco2ering !handling# exception@ theprogram %ill continue as if there is no

    Errros are not caused by our application andrather they are caused due to lac, o3 s#stemresources suchas memory@ etc. Hence@ errors are not recoverable.

    ntroduction Exception ierarch# Di33erence bet*een Exception Error

    Methods to displa# errorin3ormation$

    EXCEPTIONS

    Exception handling using : tr#5catch53inall# Chec,ed and Unchec,ed exceptions Multiple catch bloc,s 1ested tr# bloc,s User de3ined exceptions (Customi'ed Exceptions) 0hro* and 0hro*s

    ntroduction

    De3inition: /n unexpected problem occurs %hile running our application at runtime is called as anexception.

    For example: /rithmeticExcetion@ /rrayIndex&ut&f)oundsException@ FileotFoundException@ etc.Example:public class Exception3emo 6

    public static 2oid main!(tringABargs# 6

    int a 9Integer.parseInt!argsAB#7 int b9 Integer.parseInt!argsA,B#7int c 9 a=b7(ystem.out.println!NEnd of main

    methodN#7

    o/p:

    Exception in thread NmainN 'a2a.lang./rithmeticException: = by"ero at Exception3emo.main!Exception3emo.'a2a:#

    F2bnormal 0erminationG

    Exception ierarch#$he root class for all exceptions isHava$lang$0hro*able.

    $he t%o main subclasses of $hro%able are Exception and Error.

    Di33erence bet*een Exception and Error:

  • 8/13/2019 Core Java Part2

    31/74

    ,V

  • 8/13/2019 Core Java Part2

    32/74

    Throwable

    Exception Error

    InterruptedExceupted RunTimeException IOException AssertionError VirtualMachineError

    FileNotFoundException EOFException OutOfMemoryError tac!O"erFlowErro

    ArithmeticExcepton IndexOutOf#oudsException $lass$astException Null%ointerException

    ArrayIndexOutOf#oundsException trin&IndexOutOf#oudsException

    0

  • 8/13/2019 Core Java Part2

    33/74

  • 8/13/2019 Core Java Part2

    34/74

  • 8/13/2019 Core Java Part2

    35/74

    0

    execution of

    all statements inside try.

  • 8/13/2019 Core Java Part2

    36/74

    0R

    It is not recommended to place cleanup statements inside catch block because it %onZt executed if thereis noExceptione re1uired one place to maintain cleanup code %hich should be executed al%ays irrespecti2e of

    %hether exception is raised or not and exception is handle or not. (uch type of block is called asfinally block.

    Hence the main ob'ecti2e of finally block is to maintain cleanupcode. &nly one finally block can be associated %ith try block.

    Example:public class ExceptionHandling3emo 6

    public static 2oid main!(tringABargs# 6 int a 9Integer.parseInt!argsAB#7 int b9 Integer.parseInt!argsA,B#7try6

    int c 9 a=b7catch!/rithmeticException ae#6

    (ystem.out.println!N3enominator should not beN#7 /e.print(tack$race!#7

    (ystem.out.println!NEnd of main method.N#7

    Iava ExceptionandlingDemo 8B B?/:3enominator should not be

    'a 2 a.la ng ./ rithm e t ic E xc e p tion : = by"ero

    at ExceptionHandling3emo.main!ExceptionHandling3emo.'a2a:S#

    End o3 mainmethod$ (1ormal0ermination)

    Chec,ed and Unchec,ed exceptions:If an exception!or error# is directly or indirectly inherited from untimeException(or Error) is called as

    Unchecked exception i.e.@ in the exception hierarchy@ if GuntimeException !or Error# presents then it is aUnchecked exception@ other%ise@ it is a checked exception.

    Example:

    Unchec,ed exception Chec,ed exception

    'a 2 a.la ng .& b 'e c t'a 2 a.la ng .$ h ro %ab le

    'a 2 a.la ng .Exc e p tio nH a v a $la n g$u n timeE x c ep ti o n

    'a2 a.la ng .& b 'e c t'a 2 a.la ng .$ h ro %ab le

    'a 2 a.la ng .Exc e p tio n'a2a.lang.ClassotFoundExcep

    Checked exception must be handled@ other%ise the program %ill not be compiled.Example:

    http://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Object.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Object.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Throwable.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Throwable.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Throwable.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Throwable.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Exception.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Exception.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/RuntimeException.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/RuntimeException.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/RuntimeException.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/RuntimeException.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Object.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Object.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Throwable.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Throwable.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Throwable.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Exception.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Exception.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Object.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Throwable.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Throwable.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Throwable.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Exception.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/RuntimeException.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Object.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Throwable.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Throwable.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/lang/Exception.html
  • 8/13/2019 Core Java Part2

    37/74

    0

    $ry6

    $hread.sleep!,#7

  • 8/13/2019 Core Java Part2

    38/74

    0S

    catch!InterruptedException ie#6

    Unchecked exception may or may not be handled. $he compiler %ill ignore unchecked exceptions.Example:

  • 8/13/2019 Core Java Part2

    39/74

    0T

    catch!#6If an exception is raised inside inner try block@ initially it %ill look for inner catch block@ if it is notmatched@ then it %ill look for outer catch block.If an exception is raised in outer try block@ then directly it %ill look for outer catch block.

  • 8/13/2019 Core Java Part2

    40/74

    User de3ined (or Customi'ed) exceptionsDike built-in exceptions@ user can define application !pro'ect # specific exceptions is called as user

    defined

    exceptions.Dike built-in exceptions@ there are t%o types of user defined exceptions as %ell:

    Un-checked Exceptions Checked Exceptions.

    Un5chec,ed Exceptions Chec,ed Exceptions

    ;ublic class 3i2)y&neException extendsuntimeException6;ublic 3i2)y&neException ! #6;ublic 3i2)y&neException !(tring

    message#6 (uper!message#7

    ;ublic class 3i2)y&neException extendsException6;ublic 3i2)y&neException ! #6;ublic 3i2)y&neException !(tring

    message#6 (uper!message#7

    0hro*$he Othro*P key%ord is used to propagate !or delegate# an exception to its caller inorder to let the callin

    method to handle an exception rather than implementation method. $he Othro%Pkey%ord is al%ays usedatbloc, level but not at method signature le2el./ll built-in exceptions are automatically thro%n by the +

  • 8/13/2019 Core Java Part2

    41/74

    6 u i lt5 in e x c ep ti on s * $r$t t h r o * , e #* o r d

  • 8/13/2019 Core Java Part2

    42/74

    Using thro% ke%ord %ith built-in exceptions is optional. Hence the result of the follo%ing t%oprograms is exactly same.class $est6

    public static 2oid main!(tringABargs#6

    "#stem$out$println(8B/

    B);

    //$E : 2$E

    Class $est6

    public static 2oid main!(tringAB args#6thro* ne* 2rithmeticException(J/ b# LeroK);

    //$E : 2$E

    User d e 3ine d e x c ep ti on s * $r $t th r o * ,e # * o r dUser defined exceptions must be thro%n explicitly using thro% key%ord. Hence the result of the thefollo%ing t%o programs is not same.class $est6public static 2oid main!(tringAB args#6

    "#stem$out$println(8B/

    8);

    ?/: Compiles and uns *ithout

    exception$

    Class $est6public static 2oid main!(tringAB args#6

    thro* ne* Div6#?neException(J/ b# ?neK)

    // $E : Div6#?neException : / b# ?ne

    0hro*s$hro%s key%ord is used at method signature level to specify the type of exception a method thro%s.

    "#ntax:Wmethod modifiersX Wreturn typeX method\name!Wformal parameter listX#

    thro*sN WException$ype8X W@Exception$ypeOX6

    WstatementX

    Chec,ed exceptions *$r$t thro*s ,e#*ord:If the thro% propagates checked exceptions inside method block@ then such checked exceptions must b

    specified at method signature using Othro*sP key%ord.

    Example:

    class $est6p.s.2 main!(tringAB args#thro%s I.E6

    do(tuff!#7;ublic static 2oid do(tuff!# thro%s IE6

    doMore(tuff!#7;ublic static 2oid doMore(tuff!#thro*sE6thro* ne* nterruptedException();

    //$E: nterruptedException

    class $est6p.s.2 main!(tringAB args#6

    do(tuff!#7public static 2oid do(tuff!#6

    doMore(tuff!#7public static 2oid doMore(tuff!#6thro* ne* nterruptedException();

    //C$E: Unhandled exceptiont#pe : nterruptedException$

  • 8/13/2019 Core Java Part2

    43/74

  • 8/13/2019 Core Java Part2

    44/74

    class &ne6public 2oid meth!#thro%sIndex&ut&f)oundsExceptions6

    class $%o extends &ne6 public2oid meth!#thro%s/rrayIndex&ut&f)oundsException//1o compilation error$

  • 8/13/2019 Core Java Part2

    45/74

    Chec,edException UnChec,edException

    Except for GuntimeException@ Error@ and their

    subclasses@ all other exceptions arecalled checked exceptions.

    Exceptions inherited from Error or

    GuntimeException class and theirsubclasses are kno%n as unchecked

    /ll checked exceptions must be handled@other%ise the program %ill not be compiled.

    $he compiler %ill not force uncheckedexceptions

    to be handled i.e.@ unchecked exceptions

    If a method thro% checked exceptions@ they

    must

    be specified in the thro%s clause. )ut@ morechecked exceptions must not be specified in

    (pecifying unchecked exceptions in thro%s

    clause

    is optional.

    D i33 e r e n ce b e t * ee n C h e c,ed a n d Un c h e c,ed e x c e p t i o n s :

  • 8/13/2019 Core Java Part2

    46/74

    ierarch# ?bHectclass

    "tring

    JAVA.LANG PACKAGE

    "tring6u33er "tring6uider (Id,8$) Prapper classes 2utoboxing and Unboxing (Id,8$)

    $his package is automatically imported into e2ery source file at compile time. $his packagecontains most common classes in 'a2a.

  • 8/13/2019 Core Java Part2

    47/74

    &b'ect

    tring (tring)uffe

    r

    (tring)uilder Math umber Character

    )oolean

  • 8/13/2019 Core Java Part2

    48/74

    ,

  • 8/13/2019 Core Java Part2

    49/74

    ?bHect classE2ery class in 'a2a@ %hether it is built-in or user defined must be implicitly inherited from &b'ect class@

    i.e.@ the

    &b'ect is the root class for all classes in 'a2a.

    ?bHect class de3ines 3ollo*ing methods:,. public (tring to(tring!#

    0. public boolean e1uals!#. public int hashCode!#R. protected &b'ect clone!#. public Class getClass!#S. public 2oid %ait!#T. public 2oid notify!#7

    . public 2oid notify/ll!#V. protected 2oid finali"e!#

    public "tring to"tring()It is al%ays recommended to o2erride to(tring!# method to pro2ide ob'ect state information.

    Example:class )ox6

    int %idth7int height7int depth7)ox!int %@ int h@ int

    d#6 idth 9%7 Height 9h7 3epth 9 d7

    Int 2olume!#6

    Geturn %idth height depth7

    public "tring to"tring()!

    return JPidth>K*idth K eight>Kheight K Depth>Kdepth;

    &

    )ox b, 9 ne% )ox!,@ 0@#7 )oxb0 9 ne% )ox!R@@S#7

    (ystem.out.println!b,.to(tring!##7(ystem.out.println!b0#7==to(tring!# method %ill be automatically in2oked.?/:idth9, height 9 0 depth 9

    idth9R height 9 depth 9 S

    0

  • 8/13/2019 Core Java Part2

    50/74

    ublic boolean eQuals()/ctually@ e1uals!# method is used to compare t%o ob'ect states !content comparision#.

    $he >> operator is used to compare reference 2alues but not ob'ect states !Geference comparision#.Example:

    )ox b, 9 ne%)ox!,@0@#7 )ox b0 9

    ne% )ox!,@0@#7 )oxb 9 b,7

    (&; !b, 99 b0#7==false (&; !b, 99b#7 ==true (&; !b099 b#7 ==false

    It is al%ays recommended to o2erride e1uals!# method to compare t%o ob'ect states.>&2 e rr id epublic boolean e1uals!&b'ect o# 6

    ==Comparing %ith null reference al%ays returnsnull. if !o 99 null#

    return false7==Comparing incompatible types al%ays thro%s

    ClassCastException.

    if !8!o instanceof)ox##

    thro% ne% ClassCastException!#7==aliascomparision. if!this 99 o#

    return true7

    )ox b 9 !6ox#o7==contentcomparisonif !!this.%idth 99 b.%idth# ** !this.height 99b.height#

    ** !this.depth 99 b.depth## 6

    return true7

    else 6

    return false7

    )ox b, 9 ne*)ox!,@0@#7 )ox b0 9ne* )ox!,@0@#7 )oxb 9 ne* )ox!R@@S#7)ox bR 9 b,7)ox b 9 null7(ystem.out.println!b, 99 b0#7==false(ystem.out.println!b,.e1uals!b0##7==true (ystem.out.println!b, 99 b#7==false(ystem.out.println!b,.e1uals!b##7 ==false (ystem.out.println!b,99bR#7==true

    mailto:@Overridemailto:@Override
  • 8/13/2019 Core Java Part2

    51/74

  • 8/13/2019 Core Java Part2

    52/74

    >> operator eQuals() method

    Used to compare reference 2alues but notactual ob'ect states i.e.@ used for e3erence

    Used to compare actual ob'ect states!Content comparision#.

    Di33erence bet*een >> operator and eQuals() method

    public int hashCode()$he hashcode is associated %ith ob'ect. More than one ob'ect may ha2e same hashcode 2alue. $he

    hashcode is

    different from reference 2alue. $he reference 2alue is returned to reference 2ariable@ but hashcode isassociated %ith ob'ect.$he hashing mechanism is used to achie2e better search results.$he hashcode take us to the appropriate bucket. $he e1uals!# method is used to choose one of the

    ob'ect among

    many ob'ects %ithin the bucket.>&2 e rr id epublic int hashCode() !

    final int prime 9,7int result 9,7result 9 prime result Jdepth7 result 9 prime resultJ height7 result 9 prime result J %idth7 return result7

    )ox b, 9 ne%)ox!,@0@#7 )ox b0 9

    ne% )ox!R@@S#7

    )ox b 9 ne%)ox!,@0@#7 )ox bR 9ne% )ox!R@@S#7

    Contract bet*een eQuals() and hashCode() methods:,# If t%o ob'ects are e1ual by e1uals!# method@ then their hashcodes must be same.

    0# If t%o ob'ects are not e1ual by e1uals!# method@ then their hashcodes may or may not be same# If t%o ob'ects hashcodes are e1ual by hashCode!# method@ then their e1uals!# method may or

    may not

    return true.R# If t%o ob'ects hashcodes are not e1ual by hashCode!# method@ then their e1uals!# method

    must return false.

    Iava$lang$"tringIn 'a2a@ (tring is a se1uence of characters but not array of characters. &nce string ob'ect is created@ %e

    are not

    allo%ed to change existing ob'ect. If %e are trying to perform any change@ %ith those changes a ne%ob'ect is created. $his beha2ior is called as mmutabilit#." trin g s are cr ea ted i n R * a # s:

    ,# (tring DiteralsExample:

    (tring str 9 4aspire57

    mailto:@Overridemailto:@Override
  • 8/13/2019 Core Java Part2

    53/74

    0# (tring ob'ects

  • 8/13/2019 Core Java Part2

    54/74

    Example:(tring str 9 ne% (tring!4aspire5#7

    # (tring constant expressions.Example:

    (tring str 9 4aspire 5 J 4 technoloiges5P7R# (tring concatenation operation.

    Example:(tring str, 9 4aspire5P7(tring str0 95 technologies57(tring str 9 str, J str07

    Example:(tring str, 9 ne% (tring!4aspire5#7(tr,.concat!4technology5#7 ==ne% string ob'ect iscreated.

    ea p M e m o r #

    str

    aspire

    /spire technology

    (tring)uffer sb 9 ne%(tring)uffer!4/spire5#7(b.append!4technology5#7

    eap Memor#

    /spire

    technology sb

    (tring class does not support append() method. &nce %e create (tring)uffer ob'ect@ %e can performchanges. Hence it is a mutable ob'ect.

    Case 8: "tring 4iterals(tring str, 9 4hello57 ==string literal(tring str0 9 4hello57 ==string literal

    eap Memor# " trin g C on st an t oo l ( " C )

    (tr,

    (tr0

    hello

    !str, 99 str0# ==true(tr,.e1uals!str0# ==true.

    String literals are alays created in String "onstant Pool (S"P)% Initially@ string literal %ill check in the(C;@ if it does not exists@ then string literal is added to (C; and returns the reference. If it is alreadyexists@ then reference 2alue of the existing string literal is returned. ence+ "tring Constant ool("C) never allo*s duplicate string literals$

  • 8/13/2019 Core Java Part2

    55/74

    Case 9: "tring obHects(tring str, 9 ne* (tring!4hello5#7 ==string ob'ect(tring str0 9 ne* (tring!4hello5#7 ==string ob'ect

    ea p M e m o r # " trin g C on st an t oo l ( " C )

    (tr,

    hello

    (tr0 hello

    !str, 99 str0# ==false(tr,.e1uals!str0# ==true.

    String ob'ects are created in eap Memory% E2ery time a ne% ob'ect is created in heap memory.Hence string ob'ects are al%ays duplicated.

    Case : "tring Constant expression(tring str, 9 4hel5 J 4lo57 ==string constant expression(tring str0 9 4hello57 ==string literal23ter compilation

    (tring str, 9 4hello57==Gesol2ed at compile time into string literal.

    ea p M e m o r # "tring Constant ool ("C)

    !str, 99 str0# ==true

    (tr,.e1uals!str0# =

    =true.

    (tr0

    (tr,

    hello

    (tring constant expressions are computed at compile time@ henced they are string literals@ %hich isstored in (C;.

    Case R: "tring concatenation operation$(tring concatenation operations are resol2ed using (tring)uffer and its append!# method instead of(tring and its concat!# method.Example S8:

    (tring str, 9 4hel57 ==string literal(tring str0 9 str, J 4lo57 ==(tring ob'ect23ter Compilation:

    (tring str0 9 ne* "tring6u33er(str8)$append(JloK)$to(tring!#7

    ea p M e m o r # " trin g C on st an t oo l ( " C )

    (tr0

    hello(tr,

    hel

  • 8/13/2019 Core Java Part2

    56/74

    !str, 99 str0# ==false(tr,.e1uals!str0# ==true.

    Example S9:6e3ore compilation:

    (tring str, 9N$his is N7

    (tring str0 9Ntesting theN7 (tringstr9Ndifference N7(tring strR9 Nbet%een N7(tring str 9N(tring N7(tring strS9Nand N7(tring strT 9 N(tring)ufferN7"tring result > str8 str9 str strR str strTstr;

    23ter compilation: ne%(tring)uffer!str,#.append!str0#.append!str#.append!strR#.append!str#.append!strS#.append!strT#.to(tring!#7

    //Method chaining$

    Conclusion: In 'a2a@ (tring concatenation operation is e2aluated using (tring)uffer and its append!#method@ but not (tring and its concat!# method.$he ad2antage of using (tring)uffer and its append!# method is to minimi"e memory o2erhead.(tring concatenation operation is resol2ed at runtime@ hence ne% string ob'ect is created in heapmemory.

    "tring Constructors,# ;ublic

    (tring!#

    Creates an empty string %hose length is "ero.0# ;ublic (tring!(tring str#Example:

    (tring str 9 ne% (tring!4hello5#7 ==string ob'ect

    # ;ublic (tring!charAB 2alue#Example:

    charA/value > +

  • 8/13/2019 Core Java Part2

    57/74

    "tring Methods8$ ublic char char2t(int index)

    Geturns the char 2alue at the specified index.Example:

    (tring str 9 4aspire57(&;!str.char/t!0##7 == p

    9$ ublic "tring concat("tring str)/ppends at the end of the in2oking string. /l%ays returns ne% ob'ect.Example:

    (tring str, 9 OPaspire 57 ==string literal(tring str0 9 str,.concat!4technologies5#7 ==string ob'ect(op!str,#7 == 4aspire 5(op!str0#7== 4aspire technologies5

    $ ublic "tring substring(int beginndex+ int endndex)Geturns a ne% string that is a substribg of this string. beginIndex is inclusive@ but@ endIndex is

    exclusive.Example:

    (tring str, 9 4aspire technologies5(tring str0 9 str,.substring!@ S#7 ==5aspire5

    R$ ublic "tring substring(int beginndex)If the endIndex is not specified@ it returns till end of the string.Example:

    (tring str, 9 4aspire technologies57

    (tring str0 9 str,.substring!T#7==5technologies5

    $ 0he 3ollo*ing lastndex?3() methods are overloaded$

    ;ublic int lastIndex&f!charch# ;ublic intlastIndex&f!(tring str#Example:

    (tring name 9 4'a2a.lang.nteger57(tring came 9 name.substring!name.lastIndex&f!O.P#J,#7 ==5Integer5 (tring pame [email protected]&f!O.P##7 == 4'a2a.lang5

    T$ 0he 3ollo*ing index?3() methods are overloaded$;ublic int index&f!int ch#;ublic int index&f!(tring

    str# Example:(tring pack 9 4Hava.lang.(tring57

    pack.substring!pack.index&f!O.P##7 =='a2a

    $ public int length()Geturns the number of characters in the string ob'ect.Example:

    (tring str 9 4hello57

  • 8/13/2019 Core Java Part2

    58/74

    (&;!str.length!##7 ==

    $ public "tring to4o*erCase()Geturns string in lo%ercaseformat. Example:

    (tring name95G/ME(H57

    (tring after 9 name.toDo%erCase!#7 ==ramesh

    W$ public "tring toUpperCase()Geturns string in uppercaseformat. Example:

    (tring name95ramesh57(tring after 9 name.toUpperCase!#7 ==G/ME(H

    8B$ public "tring trim()Gemo2es leading and trailing spaces@ if any.Example:

    (tring str 9 4 ramesh 5

    (op!str.trim!##7==5ramesh5

    88$ ublic "tring replace(char oldChar+ char ne*Char)Geplaces all occurrences of old characters %ith ne%

    character.Example:

    (tring str 9 4ababab57(tring result 9str.replace!ObP@PaP#7 ==aaaaaa

    89$ ublic int compare0o(?bHect obH)Geturns ]2e then place ob'ect, before ob'ect0

    Geturns J2e@ then place ob'ect, after ob'ect07Geturn @ then both ob'ect, and ob'ect0 aree1ual. Example:

    (op!4a5.compare$o!4b5##7==-,

    (op!4b5.compare$o!4a5##7==J,

    (op!4a5.compare$o!4a5##7==

    Iava$lang$"tring6u33er

    For e2ery change in string ob'ect@ a ne% string ob'ect is created@ because string is immutable ob'ect@%hich

    causes memory o2erhead. $o a2oid this@ use (tring)uffer@ the changes are applied on the existingob'ect rather than creating ne% ob'ect e2ery time. Hence (tring)uffer is muttable ob'ect.

    "tring6u33er Constructors,# ;ublic (tring)uffer!#

    Constructs an empty string buffer %ith default initial capacity is 8T$

    0# ;ublic (tring)uffer!(tring str#Constructs a string buffer initiali"ed to the contents of the specifiedstring. $he initial capacity of the string buffer is : 8T str$length()

  • 8/13/2019 Core Java Part2

    59/74

    Example:(tring)uffer sb 9 ne%(tring)uffer!4hello5#7(&;!sb.capacity!##7 ==0,(&;!sb.length!##7 ==

    # ;ublic (tring)uffer!int initialCapacity#

    Creates an empty string buffer %ith specified initial capacity.

    "tring6u33erMethods

    ,. ;ublic int capacity!# //1ot available in "tring class

    Geturns the current capacity of the (tring)uffer. It means@ the maximum number ofcharacters in can hold. &nce it reaches it capacity@ it automatically increases.

    0. ;ublic int length!#Geturns the actual number of characters contained in the (tring)uffer.

    . ;ublic char char/t!int index#R. $he follo%ing are append!# o2erloaded methods in (tring)uffer class

    ;ublic (tring)uffer append!(tring

    s# ;ublic (tring)ufferappend!)oolean b# ;ublic(tring)uffer append!char s# ;ublic(tring)uffer append!int s#;ublic (tring)uffer append!longs# ;ublic (tring)ufferappend!double s# ;ublic(tring)uffer append!float s#;ublic (tring)uffer append!&b'ects#

    1ote: (uch methods are not a2ailable in (tring class.. $he follo%ing are o2erloaded insert!# methods in (tring)uffer class

    ;ublic (tring)uffer insert!int pos@ (trings# ;ublic (tring)uffer insert !int pos@)oolean b# ;ublic (tring)uffer insert !intpos@ char c# ;ublic (tring)uffer insert!intpos@ int i#;ublic (tring)uffer insert !int pos@ longl# ;ublic (tring)uffer insert !int pos@float f# ;ublic (tring)uffer insert!intpos@ double f#

    1ote: (tring does not ha2e this method.Example:

    (tring)uffer sb 9 ne% (tring)uffer!4,00,5#7

    (b.insert!0@55#7 ==,00,S. ;ublic (tring)uffer delete!int start@ int end# ==ot in string class

    (tart is inclusive@ but end is exclusive.Example:

    (tring)uffer sb 9 ne% (tring)uffer!4,00,5#7(b.delete!0@R#7 ==,00,

    T. ;ublic (tring)uffer deleteChar/t!int index#. ;ublic (tring)uffer re2erse!# ==not in string class

    Example:(tring)uffer sb 9 ne*(tring)uffer!NsatyamN#7(ystem.out.println!sb.re2erse!##7 == &=;:

    ma#tas

  • 8/13/2019 Core Java Part2

    60/74

    V. ;ublic 2oid trim$o(i"e!#

  • 8/13/2019 Core Java Part2

    61/74

    "tring6u33er "tring6uilder

    (ynchroni"ed class !i.e.@ thread-safe# on-(ynchroni"ed class !i.e.@ non thread-safe#

    ;erformance is lo% ;erformance is highDegacy class Introduced in +dk,.

    If the capacity is larger than length@ then extra space %ill be remo2ed.Example:

    (tring)uffer sb 9 ne% (tring)uffer!4hello5#7

    (&;!sb.capacity!##7 ==0,

    (&;!sb.length!##7 ==

    "b$trim0o"i'e();

    (&;!sb.capacity!##7 ==

    (&;!sb.length!##7 ==

    Iava$lang$"tring6uilder (Hd,8$)(tring)uffer is a synchroni"ed class. It cannot be accessed by more than one thread at a time. Hence

    performance is not good.(tring)uilder is non-synchroni"ed 2ersion of (tring)uffer class. Hence@ it can be accessed bymore than one thread at a time. (o@ ;erformance is good %ith (tring)uilder.3ifferences bet%een (tring)uffer and (tring)uilder:

  • 8/13/2019 Core Java Part2

    62/74

  • 8/13/2019 Core Java Part2

    63/74

  • 8/13/2019 Core Java Part2

    64/74

    )oolean bGef 9 ne%)oolean!4aspire5#7

    Iava$lang$Void/lthough the

  • 8/13/2019 Core Java Part2

    65/74

    RR

  • 8/13/2019 Core Java Part2

    66/74

    Prapper class parse0#pe("tring) Example

    +a2a.lang.)yte parse)yte!(tring# byte b 9 )yte.parse)yte!4,5#7byte b 9 )yte.parse)yte!4one5#7 ==FE

    +a2a.lang.(hort parse(hort!(tring# short s 9 (hort.parse(hort!4,5#7+a2a.lang.Integer paseInt!(tring# Int I 9 Integer.parseInt!4,P#7

    +a2a.lang.Dong paseDong!(tring# Dong l 9 Dong.parseDong!4,5#7

    +a2a.lang.Float paseFloat!(tring# Float f 9 Float.parseFloat!4,.F5#7

    +a2a.lang.3ouble pase3ouble!(tring# 3ouble d 9 3ouble.parse3ouble!4,.5#7

    +a2a.lang.)oolean pase)oolean!(tring# )oolean b 9 )oolean.parse)oolean!4no5#7

    public long long

  • 8/13/2019 Core Java Part2

    67/74

    Integer iGef 9 ne% Integer!,#7(tring str 9 iGef.to(tring!#7 == 4,5

    /lso@ the Integer@ Float@ 3ouble classes contains the follo%ing xxx(tring!# methods for con2ertingprimiti2e to

    )inary@ &ctal@ and Hexa format.

    to)inary(tring!int# to&ctal(tring!int# toHex(tring!int = float= double#

    Integer Float or 3ouble

    Example:

    (tring s 9 Integer.to)inary(tring!,#7 ==,,(tring s 9 Integer.toHex(tring!,#7 ==a

    2utoboxing and Unboxing$he /uto * Un boxing first time introduced in +3[,..

    2utoboxing$he 'a2a compiler automatically con2erts ;rimiti2e data to rapper ob'ect is called as autoboxing.Example:

    6e3ore compilation:Integer iGef 9 ,.

    23ter compilation:Integer iGef 9 ne* nteger(8B)7 == /utoboxing

    Unboxing$he 'a2a compiler automatically con2erts rapper ob'ect to primiti2e data is called as unboxing.

    Example:6e3ore compilation:

    Int I 9 ne% Integer!,#723ter compilation:

    Int I 9 ne* nteger(8B)$intValue()7 ==unboxing.

  • 8/13/2019 Core Java Part2

    68/74

    RT

    e3lection MechanismGeflection is the process of obtaining information about any 'a2a class i.e.@ getting information about

    fields@

    constructors@ and methods of a 'a2a class.

    Class "#ntax:Wclass modifiersX class Wclass-nameX Aextends Wsuperclass nameXB Aimplements interface8@

    interfacenB 6

    //.ields

    Wfield modifiersX type name7//ConstructorsWconstructor modifiersX name!Wparameters listX#6//Methods

    Wmethod modifiersX Wreturn typeX name!Wparameters listX#6

    $o obtain information about classes@ %e ha2e to useHava$lang$Class andHava$lang$re3lect package.

    Iava$lang$Classhen the class is loaded into +

  • 8/13/2019 Core Java Part2

    69/74

    R

    . etting method!s# information

  • 8/13/2019 Core Java Part2

    70/74

  • 8/13/2019 Core Java Part2

    71/74

    +a2a bean is a reusable soft%arecomponent.

    In generally@ a +a2a )ean perform a specific

    task.

    Iava

    6eans F eusable "o3t*arecomponent G

    (ome +a2a beans are

  • 8/13/2019 Core Java Part2

    72/74

    ntrospection MechanismIntrospection is the process !or mechanism# of obtaining information about a +a2a )ean i.e.@

    getting

    information about properties@ e2ents@ and methods of a 'a2a beanclass. $he +a2a bean class ha2e follo%ing property types:

    I. (imple

    propertiesII. )oolean properties

    III. Indexedproperties

    1aming Conventions

    $he follo%ing table detailing 'a2a bean class method naming con2entions for e2ery property type:

    ropert# t#pe 1aming patterns Example

    (imple ;ublic $ get!#;ublic 2oid set!$ 2alue#

    ;ublic (tring getame!#6;ublic 2oid setame!(tring name#6

    )oolean ;ublic boolean is!#

    ;ublic boolean get!#;ublic 2oid set!boolean 2alue#

    ;ublic boolean isHoliday!#6

    ;ublic boolean getHoliday!#6;ublic 2oid setHoliday!boolean 2alue#6

    Indexed ;ublic $ get!int index#

    ;ublic $AB get!#;ublic 2oid set!int index@ $2alue# ;ublic 2oid set!$AB2alue#6

    ;ublic boolean getInputs!int index#6

    ;ublic booleanAB getInputs!#;ublic 2oid setInputs!int index@boolean 2alue#6;ublic 2oid setInputs!booleanAB 2alues#6

    Introspection mechanism usesHava$beans package from +3[ /;I to analy"e +a2a )eans.

    Iava$beans$ntrospectorIt contains static methods that allo% us to obtain information about properties@ e2ents@ and methods of a

    bean.

    ;ublic static )eanInfo get)eanInfo!Class beanClass#7

    $he abo2e static method returns )eanInfo ob'ect %hich contains complete +a2a )ean information.

    Iava$beans$6eann3ointer3aceNN$he follo%ing methods from )eanInfo ob'ect gi2es information about ;roperties@ E2ents@ and Methods o

    a +a2a

    )ean class.,# ;ublic ; ro p e rty 3 e s crip tor AB getropert#Descriptors!#0# ;ublic M e t h o d 3 e scrip tor AB getMethodDescriptors!## ;ublic E 2 ent( e t3 es c rip tor AB getEvent"etDescriptors!#

    Example:

    import 'a2a.a%t.)utton7import 'a2a.beans.)eanInfo7

    import 'a2a.beans.E2ent(et3escriptor7import

    'a2a.beans.IntrospectionException7import 'a2a.beans.Introspector7import

    'a2a.beans.Method3escriptor7

    http://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/beans/PropertyDescriptor.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/beans/PropertyDescriptor.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/beans/PropertyDescriptor.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/beans/MethodDescriptor.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/beans/MethodDescriptor.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/beans/EventSetDescriptor.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/beans/EventSetDescriptor.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/beans/EventSetDescriptor.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/beans/PropertyDescriptor.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/beans/MethodDescriptor.htmlhttp://d/SCJP1.6/softwares/jdk-6u18-docs/docs/api/java/beans/EventSetDescriptor.html
  • 8/13/2019 Core Java Part2

    73/74

    import'a2a.beans.;roperty3escriptor7public class ItrospectionEx, 6

    public static 2oid main!(tringAB args# 6

    try 6

    6eann3o beann3o > ntrospector$get*eanIn$o(6utton$class);

  • 8/13/2019 Core Java Part2

    74/74

    (ystem.out.println!N---------------------N#7(ystem.out.println!N+a2a )ean;roperties:N#7

    (ystem.out.println!N---------------------N#7

    ropert#DescriptorFG props >beann3o$getropert#Descriptors();

    for !;roperty3escriptor prop : props#

    6 (ystem.out.println!prop.get;roperty$ype!#.get(impleame!# J N N

    J

    prop.getame!##7

    (ystem.out.println!N------------------N#7(ystem.out.println!N+a2a )eanMethods:N#7(ystem.out.println!N------------------N#7MethodDescriptorFG methods > beann3o$getMethodDescriptors();for !Method3escriptor method : methods#

    6 (ystem.out.println!method.getam

    e!##7(ystem.out.println!N-----------------N#7

    (ystem.out.println!N+a2a )eanE2ents:N#7(ystem.out.println!N-----------------N#7Event"etDescriptorFG events > beann3o$getEvent"etDescriptors();for!E2ent(et3escriptor e2ent : e2ents#

    6 (ystem.out.println!e2ent.getame!##7

    catch !IntrospectionException

    e# 6e.print(tack$race!#7

    Conclusion:,# $he Geflection mechanism %ork at a lo% le2el and deal only %ith fields@ constructors@ and

    methods of a class. $he Introspection mechanism %ork at a higher le2el and deal %ith theproperties@ e2ents@ and methods of a +a2a )ean.

    0# Introspection mechanism internally uses Geflection /;I to retrie2e properties@ e2ents@ ormethods information.