Sei sulla pagina 1di 74

Core Java Part - II

Chapt ers: 1. 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 and Inter$ace

2. Exceptions

Introduction Exception Hierarchy Exception handling using : try-catch-finally Methods to display error information. Checked and Unchecked exceptions Multiple catch blocks. ested try blocks User defined exceptions !Customi"ed Exceptions# $hro% and $hro%s Hierarchy &b'ect class (tring (tring)uffer * (tring)uider !+dk,.-# .rapper classes /utoboxing and Unboxing !+dk,.-#

3. Java.lang Package

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 public methods. 3ata hiding says 4restrict access and modification of internal data items through the use of getter and setter methods5. Example: public class User6 //Data hiding private (tring username7 private (tring pass%ord7 public 2oid setUsername!(tring name#6 if!!name 89 null# ** name8955 #6 username 9 name7 :else6 (op!4Username cannot be null or empty5#7 : : public (tring getUsername!#6 return 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'


0

Encapsulation combines !or bundles# data members %ith method members together !or the facility that bundles data %ith the operations that perform on that data is called as encapsulation#. Example: public class /uthentication6 //Data hiding private (tring username7 private (tring pass%ord7 public 2oid setUsername!(tring name#6 if!!name 89 null# ** name8955 #6 username 9 name7 : : public 2oid set;ass%ord!(tring p%d#6 if!!p%d 89 null# ** p%d8955 #6 ;ass%ord 9 p%d7 : : //Method abstraction public boolean is<alidUser!#6 ==Use +3)C /;I for obtaining connection. Connection con 9 3ri2erManager.getConnection!4'dbc:oracle:thin:>localhost:,-0,:?E5@ 4scott5@ 4tiger5#7 Check %ith database %hether user is already registered or not. If 2alid user then return true7 else return false7 : : //Client program class /ccess(ite6 public static 2oid main!(tringAB args#6 /uthentication auth 9 ne% /uthentication!#7 ==set %ebsite username and pass%ord auth.setUsername!4aspire5#7 auth.set;ass%ord!4aspire,0C5#7 boolean success9 auth.isValidUser(); if!success#6 (ystem.out.println!4Dogged into I )&?E5#7 :else6 (ystem.out.println!4In2alid username = pass%ordE5#7 : :

nheritance
3efine common methods in base class and specific methods in subclass. Example: class Figure6 ==;arent class pri2ate int %idth7 pri2ate int height7 public Figure!int %@ int h#6 %idth 9 %7 height 9 h7 : public int get.idth!# 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 ==child class public Gectangle!int %@ int h#6 super(*+h);// nvo,es immediate superclass matching constructor : ==subclass specific method. double area()! return getHeight!#H get.idth!#7 : : class $riangle extends Figure6 public $riangle!int %@ int h#6 super!%@h# 7 : ==subclass specific method.

Double area()!

Geturn I.- H getHeight!#H get.idth!#7 : : - .igure -%idth -height JFigure!# Jget.idth! # JgetHeight! # /move() /resi'e() /hide() /sho*() (ectangle - 0riangle

JGectangle !# Jget.idth! # JgetHeight! # Jmo2e!# Jresi"e!# Jhide!# Jsho%!# /area()

J$riangle!# Jget.idth!# JgetHeight!# Jmo2e!# Jresi"e!# Jhide!# Jsho%!# /area()

1ote: 2ccessibilit# modi3ier ;ri2ate 3efault ;rotected ;ublic UM4 s#mbol K L J

In the abo2e example@ Gectangle "52 Figure. (imilarly@ $riangle "52 Figure. (o@ inheritance is also called as "52 relationship. $he base class common methods mo2e!#@ resi"e!#@ hide!#@ and sho%!# are reused in the subclasses Gectangle and $riangle. Hence the main ad2antage %ith inheritance is Code (EU"26 4 07$ $he base class is also called as superclass@ supertype@ or parent class. $he deri2ed class is also called 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

(ectangle 0riangle

Figure ,: Inheritance hierarchy $he classes higher up in the hierarchy are more generali'ed and the classes lo%er do%n in the hierarchy are more speciali'ed. Case 8: (ubclass specific methods cannot be in2oked using superclass reference 2ariable. Example: Figure fGef 9 ne% Figure!,I@0I#7 fGef.mo2e!#7 fGef.area!#7 ==Compilation error. Undefined method. Case 9: /s expected@ subtype ob'ect is assigned to subtype reference 2ariable: Example: Gectangle rGef 9 ne% Gectangle!,I@0I#7 rGef.area!#7 ==Compiles and runs %ithout errors. Case :: $he subclass ob'ect can be assigned to a superclass reference 2ariable. )ut@ the subclass specific methods cannot be in2oked using superclass reference 2ariable@ because the compiler only kno%s reference type methods but not actual runtime ob'ect methods. $his assignment in2ol2es a %idening reference con2ersion !upcasting#. Example: Figure fGef 9 ne% Gectangle!#7 ==Geference type %idening. (ubtype ob'ect is assigned to supertype ref 2ar. fGef.area!#7 == Compilation error. Undefined method.

;ol#morphism
Polymorphism translates from Mreek as man# 3orms !poly - many morph - $orms)% &2erloading and o2erriding are the t%o different types of polymorphism.

Method "ignature
It is the combination of the method name and its parameters list. Method signature does not consider return type and method modifiers. Example: public int add(int+ int)6: public float add(3loat+ 3loat)6:

Method overloading
$%o or more methods are said to be o2erloaded if and only if methods %ith same name but differs in parameters list !3iffers in umber of parameters@ ;arameter type@ or ;arameter order#@ and %ithout considering return type@method modifiers i.e. &2erloaded methods must ha2e different method signature irrespecti2e of their return type@ modifiers.

Example: class /ddition6

public int add!int x@ int y#6: public 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#6: public float add!float x@ int y#6: : /ll abo2e methods are o2erloaded %ith each other. /ddition ob' 9 ne% /ddition!#7 ob'.add!,I@0I#7==compiler maps %ith add!int@ int# ob'.add!,I@0I@CI#7 ==compiler maps %ith add!int@ int@ int# 0he overloaded methods are resolved b# the compiler at compilation time$ )ence overloading is also ,no*n as <"tatic ;ol#morphism= or <Earl# 6inding=$

Method overriding
/ subclass can re-implement superclass methods to pro2ide subclass specific implementation. $he method in superclass is called as overridden method@ %hereas method in subclass is called as overriding method.

Method o!erriding rules(


a# $he accessibility modifier of subclass method must be same or less restricti2e. 21D b# $he superclass and subclass methods must ha2e same return type. 21D c# $he superclass and subclass method signature must be same !i.e.@ method name@ the number of parameters@ parameter types@ parameter order#. 21D d# $he thro%s clause in o2erriding method can thro% all@ none or a subset of the checked exceptions %hich are specified in the thro%s clause of the o2erridden method@ but not more checked exceptions. Example: class Figure 6 int %idth7 int height7 Figure!int %@ int h# 6 %idth 9 %7 height 9 h7 : //overridden method ;ublic double area!#6 return I.I7 ==unkno% : : class Gectangle extends

Figure 6 Gectangle!int %@ int h# 6 super!%@ h#7 : //overriding method

;ublic double area!# 6 Geturn %idth H height7 : : public class &2erriding3emo 6 public static 2oid main!(tringAB args# 6 ==superclass ob'ect assigned to superclass reference 2ariable Figure fGef 9 ne% Figure!#7 (op!fGef.area!##7 ==I.I ==area!# from Figure class ==subclass ob'ect assigned to subclass reference 2ariable Figure fGef, 9 ne% Gectangle!,I@0I#7 (op!fGef,.area!##7 ==0II.I //area() 3rom (ectangle class$ : : $he method o2erriding is resol2ed at runtime based on actual ob'ect type but not Geference type. Hence 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!#7 fGef.area!#7 ==area!# method from Gectangle ob'ect is in2oked. fGef 9 ne% $riangle!,I@0I#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:


Criteria Method signature Geturn type /ccessibility modifier &2erriding &2erloading Must be same Must be different. Must be same. e2er considered. Must be same or Dess restricti2e. e2er considered.

$hro%s clause 3eclaration context Method call resolution

Must not thro% ne% checked exceptions. / method must only be o2erridden in a subclass. Method o2erriding resol2ed at runtime based on actual ob'ect type. It is also called as dynamic polymorphism or

e2er considered. / method can be o2erloaded in the same oro2erloading in a sub class. Method resol2ed at compile time based on Geference type. It is also called as static polymorphism or early binding.

Constructor
$he purpose of the constructor is initiali'ation follo%ed by instantiation. Constructor (ules: a# $he name of constructor must be same as class name. b# $he only applicable modifiers for the constructors are: i# ;ublic ii# protected iii# no accessibility pri2ate c# $he constructor must not return any type not e2en 2oid. Example: ;ublic class )ox6 Int %idth7 Int height7 Int depth7 public 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

i2#

3efault constructors construcotrs

;arameteri"ed

Implicit default constructor Geference type

Explicit default constructors

;rimiti2e type

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

$here are t%o types of default constructors: a) Implicit De$ault "onstructor If no constructor is declared explicitly@ the +a2a Compiler includes constructor %ithout parameters called as Implicit 3efault Constructor. Example: class )ox6: /fter compilation Class )ox6 6ox()!& //implicit de3ault constructor : b) E)plicit De$ault "onstructor .e can declare constructor %ithout parameters list explicitly is called as explicit default constructor. Example: Class )ox6 )ox!#6 ==explicit default constrctor .idth 9 %7 : :

;arameteri'ed Constructor
Constructor can take either ;rimiti2e or Geference type as its parameters is called as parameteri'ed constructo r. Example: class )ox6 int %idth7 int height7 int depth7 )ox!#6 ==no-arg constructor .idth 9,7 Height 9 07 3epth 9 C7 : )ox!int %idth#6 this.%idth 9 %idth7 height 9 07 depth 9 C7 : )ox!int %idth@ int height# 6 this.%idth 9 %idth7 this.height

9 height7 depth 9 C7 : =H)ox!int %idth@ int height@ int depth#6 this.%idth 9 %idth7 this.height 9 height7 this.depth 9 depth7 :H=

//short cut approach )ox!int %idth@ int height@ int depth#6 this(*idth+ height); //calls matching constructor 3rom the same class this.depth 9 depth7 : )ox!6ox b#6 this.%idth 9 b.%idth7 this.height 9 b.height7 this.depth 9 b.depth7 : : public class Constructor3emo 6 public static 2oid main!(tringAB args# 6 )ox b, 9 ne% )ox!,@0@C#7 )ox b0 9 ne% )ox!b,#7 : : Constructors are overloaded *ith each other$ 2lso+ Constructors cannot be inherited to subclass$

Constructor Chaining
(uper class constructors are al%ays executed before subclass constructors is called as constructor chaining. Example: class &ne6 public &ne!# 6 (ystem.out.println!N, N#7 : : class $%o extends &ne6 public $%o!# 6 (ystem.out.println!N0 N#7 : : class $hree extends $%o6 public $hree!# 6 (ystem.out.println!NC N#7 : : public class ConstructorChaining3emo 6 public static 2oid main!(tringAB

args# 6 $hree ob' 9 ne% $hree!#7 : : ?/;: , 0

super or this
$here are t%o forms of OsuperP or OthisP: i# %ithout parantheses ii# %ith parantheses <this= %ithout parantheses is used to in2oke same class fields and methods. <super= %ithout parantheses is used to call its immediate superclass 3ields and methods. <this()= is used to call matching constructor from the same class. <super()= is used to call matching constructor from immediate superclass. Example: Class &ne6 Int age 9 0I7 : Class $%o extends &ne6 Int age 9 CI7 <oid disp!# 6 (&;!age#7 == CI (&;!super$age#7 == 0I : :

3inal
OfinalP is a modifier used %ith: a# <ariables b# Methods. c# Classes

3inal *$r$t variables


$he 2alue of the final 2ariable is al%ays $i)ed i.e.@ once it is initiali"ed@ it ne2er re-initiali"ed. Example: final int (IQE 9 ,I7 ==(IQE 9 0I7 ==C.E. Final 2ariable cannot be re-initiali"ed. It is al%ays recommended to use Upper case for final 2ariables names.

.inal *$r$t methods


Final methods are al%ays fully !completely# implemented. Example: Class Figure6 3inal void move() !& 3inal void resi'e()!& 3inal void sho*()!& 3inal void hide() !& double area!#6: : Final methods cannot be o2erridden i.e.@ final key%ord prevents method o2erriding.

3inal *$r$t classes

If all methods in class are completely implemented@ then instead of declaring e2ery method as final@ better declare class itself as final. )y default@ all methods in a final class are final. Example: final ;ublic class &ne6 2oid meth,!#6: 2oid meth0!# 6: : Final classes cannot be extended. Example: final class &ne6: class $%o extends &ne6:=/C$E 1ote: ,# Final %ith 2ariables pre2ents re-initiali"ation. 0# Final %ith methods pre2ents method o2erriding. C# Final %ith classes pre2ents inheritance.

"tatic
(tatic is a modifier used %ith: a# <ariables b# methods. c# )locks

(tatic members are ndependent of any ob'ect creation i.e.@ static members are Common across all ob'ects i.e.@ static members are @lobal for all ob'ects. (tatic members ne2er associated %ith any ob'ect but associated only %ith class. Hence@ static 2ariables are also called as Class variables or @lobal variables$ Example: Class )ox6 ;ri2ate int %idth7 ;ri2ate int height7 ;ri2ate int depth7 ;ublic static public int count7 ==static 2ariable )ox!int %@ int h@ int d#6%idth 9 %7 height 9 h7 depth 9 d7 count//: : )ox b, 9 ne% )ox!,@0@C#7 )ox b0 9 ne% )ox!R@-@S#7 )ox bC 9 ne% )ox!T@U@V#7 (op!)ox.count#7 == C (tatic members are loaded %hen class is loaded into +<M. Hence@ static members are accessed %ithout !before# creating an ob'ect itself. 1ote: ,# Instance 2ariables are associated %ith )eap area.

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

"tatic methods
Rules( ,# / static method cannot access instance 2ariables. 0# / static method cannot access instance methods. C# 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
<abstract= is a modifier used %ith: a# methods b#classes. 3eclare method as abstract if the method implementation is un,no*n. /l%ays@ abstract methods must ends %ith semi5colon. Example: ;ublic abstract double area!#7 2bstract class (ules: a# /tleast one abstract method@ but all other methods are concrete. b# /ll methods are abstract methods@ i.e.@ none of the method is a concrete method. c# /ll methods are concrete@ i.e.@ none of the method is an abstract method. If a class inherits abstract class using extends key%ord@ the subclass must either implement all abstract methods or declare subclass also as abstract class. /bstract classes must not be instantiated@ but abstract classes are used as reference 2ariables to achie2e dynamic polymorphism. Example: public abstract class Figure6 Int %idth7 Int height7 Figure!int %idth@ int height#6this.%idth 9 %idth7 this.height 9 height7: ;ublic abstract double area!#; : Class Gectangle extends Figure6 Gectangle!int %@ int h# 6super!%@ h#7: >&2erride ;ublic double area()! (eturn *idth A height; & : Class $riangle extends Figure6 $riangle!int %@ int h#6super!%@ h#7:

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

& : 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!,I@0I#7==(ubclass ob'ect is assigned to superclass ref 2ariable (&;!fGef.area!##7 == area!# method from Gectangle is in2oked. fGef 9 ne% $riangle!,I@0I#7 (&;!fGef.area!##7 == area!# method from $riangle is in2oked. : : 2dvantages *ith 2bstract classes: ,# Forces the subclass to pro2ide method implementation 0# /chie2es 3ynamic ;olymorphism.

nter3aces
Interface pro2ides ser2ice details but not its implementation details. For example@ the stack interface says its operations push!# and pop!# but not its actual implementation details such as array or linked list. .e !ser2ice pro2ider# can change stack implementation 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 E interfacen6 Wfield declarationsX Wmethod declarationsX :

.ields *$r$t nter3ace


)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 ,I7 ==3eclaring public static final explicitly is redundant but not error. b# static final int (IQE 9 ,I7

c#

final int (IQE 9 ,I7

d# int (IQE 9 ,I7 /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!#7 b# abstract 2oid meth!#7 c# 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 ,I7 public 2oid push!int x#6 ==impl using arrays : public int pop!#6 ==impl using arrays : : "tac, s(e3 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 using extends key%ord. Either class or an interface can inherit any number of interfaces. Example: ;ublic interface &ne6: ;ublic interface &ne6: ;ublic interface &ne6: ;ublic interface &ne6: ;ublic class $%o ;ublic interface $%o ;ublic interface $%o6: implements &ne6: extends &ne6: ;ublic class $hree ;ublic interface implements &ne@ $%o6: ;ublic $%o6: interface$hree

+a2a supports multiple inheritance by inheriting multiple interfaces. $he subclass of an interface either implement all abstract methods or declare subclass as an abstract class. $he accessibility modifier of the subclass method must be public. Example: Interface &ne6 ;ublic 2oid meth,!#7 ;ublic 2oid meth0!#7 : Class $%o implements &ne6 ;ublic 2oid meth,!#6: ;ublic 2oid meth0!#6: : abstract Class $%o implements &ne6 ;ublic 2oid meth,!#6: :

Mar,er nter3ace
If our class gets special pri2ilege by inheriting an interface@ such an interface is called as marker interface. Example: +a2a.io.(eriali"ab le +a2a.lang.Gunna ble 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 an interface is also called as Marker Interface. Example: +a2a.lang.Gunnable - run!# method. Duestion: $hough interface is a pure abstract class@ %hy do %e need an interfaceY 0o support multiple inheritance and if a subclass already implements another class@ then subclass cannot inherit our abstract class. $his restriction is not applicable for an interface@ since a class can inherit any number of interfaces.

Di33erence bet*een abstract class and nter3ace:


2bstract class Can contain concrete methods. Can contains non final * non static 2ariables. Can contains any number of constructors. 3oes not support multiple inheritance. nter3ace /ll methods are abstract. /ll 2ariables must be static and final. e2er contains constructors at all. (upports multiple inheritance.

EXCEPTIONS
ntroduction Exception )ierarch# Di33erence bet*een Exception E Error Methods to displa# error in3ormation$ 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 an exception. For example: /rithmeticExcetion@ /rrayIndex&ut&f)oundsException@ File otFoundException@ etc. Example: public class Exception3emo 6 public static 2oid main!(tringAB args# 6 int a 9 Integer.parseInt!argsAIB#7 int b 9 Integer.parseInt!argsA,B#7 int 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 is Hava$lang$0hro*able. $he t%o main subclasses of $hro%able are Exception and Error. Di33erence bet*een Exception and Error: Exceptio Error n Exceptions are caused b# our Errros are not caused by our application and program and hence recovarable. /fter rather they are caused due to lac, o3 s#stem reco2ering !handling# exception@ the resources such as memory@ etc. Hence@ errors are not recoverable. program %ill continue as if there is no exception. $he

,V

Throwable

Exception

Error

InterruptedExceupted

RunTimeException

IOException

AssertionError

VirtualMachineError

FileNotFoundException

EOFException

OutOfMemoryError

tac!O"erFlowError

ArithmeticExcepton

IndexOutOf#oudsException

$lass$astException

Null%ointerException

ArrayIndexOutOf#oundsException

trin&IndexOutOf#oudsException

0I

0,

Methods to displa# error n3ormation:


$he Iava$lang$0hro*able class contains the follo%ing C methods to print exception information: 8) ;ublic void print"tac,0race() $his method is used to print follo%ing error information: a# Exception name b# Exception Message c# Dine number %hich causes the exception d# Method belongs to the abo2e line number e# Class belongs to the abo2e method. f# File name belongs to the abo2e class. Example: Exception in thread NmainN 'a2a.lang./rithmeticException: = by "ero at Exception3emo.main!Exception3emo.'a2a:-# 9) ;ublic "tring to"tring() $his method is used to print follo%ing error information: a# Exception name b# Exception Message Example: 'a2a.lang./rithmeticException: = by "ero :) ;ublic "tring getMessage() $his method is used to print follo%ing error information. a# Exception 3escription. Example: = by "ero

Exception handling using tr#5catch53inall#


It is al%ays a good programming practice to handle an exception for graceful termination ! ormal termination# of the program i.e.@ the purpose of handling an exception is to continue program execution as if there is no exception.

0r# bloc,
It contains the statements %hich likely to thro% an exception. If an exception is raised@ the remaining statements in the try block are s,ipped. $ry block must be follo%ed by either catch or finally or both.

Catch bloc,
Catch block is used to handle an exception. $he catch block is executed only if try block thro%s an exception. Catch block cannot be %ritten %ithout try block. For each try block there can be "ero or more catch blocks.

.inall# bloc,
It is not recommended to place clean up code inside try block@ because there is no guaranty for the 00

execution of all statements inside try.

0C

It is not recommended to place cleanup statements inside catch block because it %onZt executed if there is no Exception .e 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 as finally block. Hence the main ob'ecti2e of finally block is to maintain cleanup code. &nly one finally block can be associated %ith try block. Example: public class ExceptionHandling3emo 6 public static 2oid main!(tringAB args# 6 int a 9 Integer.parseInt!argsAIB#7 int b 9 Integer.parseInt!argsA,B#7 try6 int c 9 a=b7 :catch!/rithmeticException ae#6 (ystem.out.println!N3enominator should not be IN#7 /e.print(tack$race!#7 : (ystem.out.println!NEnd of main method.N#7 : : Iava Exception)andlingDemo 8B B ?/;: 3enominator should not be I 'a2a.lang./rithmeticException: = by "ero at ExceptionHandling3emo.main!ExceptionHandling3emo.'a2a:S# End o3 main method$ (1ormal 0ermination)

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 a Unchecked exception@ other%ise@ it is a checked exception. Example: Unchec,ed exception Chec,ed exception 'a2a.lang.&b'ect 'a2a.lang.&b'ect 'a2a.lang.$hro%abl 'a2a.lang.$hro%abl e e 'a2a.lang.Exception 'a2a.lang.Exception 'a2a.lang.Class otFoundExcep Hava$lang$(untimeException tion 'a2a.lang./rithmeticException Checked exception must be handled@ other%ise the program %ill not be compiled. Example: 0R

$ry6 $hread.sleep!,III#7

0-

:catch!InterruptedException ie#6: Unchecked exception may or may not be handled. $he compiler %ill ignore unchecked exceptions. Example: <oid meth!# 6 (&;!,I= I#7 : $he unchecked exceptions are caused due to in2alid input data entered by end user at runtime@ %hose information ne2er kno%n by compiler in ad2ance. Hence@ unchecked exceptions are ignored by 'a2a compiler. $he checked exceptions must be handled by the de2eloper other%ise the compiler %ill not let the code to be compiled.

0r# *ith Multiple Catch 6loc,s


$he %ay of handling an exception is 2aried from exception to exception@ hence it is recommended to place separate catch block for e2ery exception. If the statements in try block thro%s multiple exceptions@ it is recommended to handle them indi2idually. In case of try %ith multiple catch blocks@ the order o3 catch bloc,s present is ver# important and it should be 3rom subclass exception t#pe to superclass exception t#pe$ $he catch block for a super class exception should not shado% the catch block for the sub class exception i.e. the order of the catch blocks is from sub class to the super class exception@ other%ise the program %ill not be compiled. Example: $ry6 $ry6 $ry6 IntAB arr 9 ne% IntAB arr 9 ne% IntAB arr 9 ne% intA-B7 (&;!arrA,IB#7 intA-B7 (&;!arrA,IB#7 intA-B7 (&;!arrA,IB#7 (tring str 9 4hello57 (tring str 9 4hello57 (tring str 9 4hello57 (&;!str.char/t!,I# (&;!str.char/t!,I# (&;!str.char/t!,I##7 #7 #7 : : : catch!/rrayIndex&ut&f)oundsE catch!/rrayIndex&ut&f)oundsE catch!Index&ut&f)oundsExcep xc eption e#6 xc eption ae#6 tio n ae#6 e.print(tack$race!#7 : : catch! ndex?ut?36oundsExce catch!/rrayIndex&ut&f)oundsE : ptio n e#6: xc eption e#6 : catch!(tringIndex&ut&f)ounds Exc eption e#6 ==&[ //C$E$ (op!e.to(tring!##7 : ==&[

1ested tr# bloc,s


$ry block %ith in another try block is called as nested try block. Example: $ry6 $ry6 :catch!#6:

0S

:catch!#6: If an exception is raised inside inner try block@ initially it %ill look for inner catch block@ if it is not matched@ 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.

0T

User de3ined (or Customi'ed) exceptions


Dike 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 extends ;ublic class 3i2)y&neException extends (untimeException6 Exception6 ;ublic 3i2)y&neException ! #6: ;ublic 3i2)y&neException ! #6: ;ublic 3i2)y&neException !(tring ;ublic 3i2)y&neException !(tring message# message# 6 (uper!message#7 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 calling method to handle an exception rather than implementation method. $he Othro%Pkey%ord is al%ays used at bloc, level but not at method signature le2el. /ll built-in exceptions are automatically thro%n by the +<M. )ut@ built-in exceptions can be programmatically thro%n by the de2eloper using thro% key%ord. /ll user defined exceptions must be programmatically thro%n using Othro%P key%ord. "#ntax: thro% Wthro*able obHectX7 Example: thro% ne% /rithmeticException!4= by "ero5#7 Example: public class 3i2ision6 public static 2oid main!(tringAB args#6 try6 di2!,I@I#7 ==method calling :catch!/rithmeticException ae# 6 ae.print(tack$race!#7 : : ;ublic static 2oid di2!int x@ int y#6 ==method implementation If!y99I#6 thro* ne* 2rithmeticException(J/ b# 'eroK); : (ystem.out.println!x=y #7 : :

6uilt5in exceptions *$r$t thro* ,e#*ord

Using thro% ke%ord %ith built-in exceptions is optional. Hence the result of the follo%ing t%o programs is exactly same. class $est6 Class $est6 public static 2oid main!(tringAB public static 2oid main!(tringAB args#6 args#6 thro* ne* 2rithmeticException(J/ b# LeroK); : "#stem$out$println(8B/ B); : : //($E : 2$E : //($E : 2$E User de3ined exceptions *$r$t thro* ,e#*ord User defined exceptions must be thro%n explicitly using thro% key%ord. Hence the result of the the follo%ing t%o programs is not same. class $est6 Class $est6 public static 2oid main!(tringAB args#6 public static 2oid main!(tringAB args#6 "#stem$out$println(8B/ thro* ne* Div6#?neException(J/ b# ?neK); 8); : : : : // ($E : Div6#?neException : / b# ?ne ?/;: Compiles and (uns *ithout exception$

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# 8 Mthro*sN WException$ype X E 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 be specified at method signature using Othro*sP key%ord. Example: class $est6 class $est6 p.s.2 main!(tringAB args#thro%s I.E6 p.s.2 main!(tringAB args#6 do(tuff!#7 do(tuff!#7 : : ;ublic static 2oid do(tuff!# thro%s IE6 public static 2oid do(tuff!#6 doMore(tuff!#7 doMore(tuff!#7 : : ;ublic static 2oid doMore(tuff!#thro*s public static 2oid doMore(tuff!#6 E6 thro* ne* nterruptedException(); thro* ne* nterruptedException(); : : : : //C$E: Unhandled exception //($E: nterruptedException t#pe : nterruptedException$

Unchec,ed exceptions *$r$t thro*s ,e#*ord:


$he compiler does not 2erify the unchecked exceptions in thro%s clause i.e.@ if the thro% propagates unchecked exceptions inside method block@ then thro%s may or may not specify unchecked exceptions at method signature. Example: class $est6 class $est6 p.s.2.main!(tringAB args#thro*s p.s.2.main!(tringAB args#6 2rithmeticException6 thro% ne% /rithmeticException!#7 thro% ne% /rithmeticException!#7 : : : : //($E: 2$E //($E: 2$E

0hro*s *$r$t method overriding


$he o2erriding method in subclass must not thro% more checked exceptions than o2erriden method in superclass@ i.e.@ the o2erriding method in subclass may thro% none+ all+ or sub5set o3 chec,ed exceptions 3rom overridden method 3rom superclass+ but not more chec,ed exceptions$ $his rule is not applicable for unchecked exceptions Example: class &ne6 class &ne6 class &ne6 public 2oid meth!#thro%s public 2oid meth!#thro%s public 2oid meth!#thro%s I&Exception6 I&Exception6 I&Exception6 : : : : : : class $%o extends &ne6 class $%o extends &ne6 class $%o extends &ne6 public 2oid meth!#thro%s public 2oid meth!#thro%s public 2oid meth!#thro%s Exception6 InterruptedException6 File otFoundException6 : : : : : : //C$E: "ub class method //C$E: "ub class method must //($E: ?Exception must not thro* supert#pe not thro* di33erent chec,ed exception$ exceptions$ $he o2erriding method in subclass may thro% different unchecked exceptions than o2erridden method in superclass i.e.@ the o2erriding method in subclass may or may not specify unchecked exceptions in o2erridden method unchecked exceptions in superclass. class &ne6 //1o compilation error$ class &ne6 public 2oid meth!#thro%s public 2oid meth!#thro%s Index&ut&f)oundsExcepti Index&ut&f)oundsExceptio on6 ns6 : : : : class $%o extends &ne6 class $%o extends public 2oid meth!# &ne6 public 2oid : meth!#thro%s : GuntimeException //1o compilation error$ : :

class &ne6 public 2oid meth!#thro%s Index&ut&f)oundsExceptions6 : : class $%o extends &ne6 public 2oid meth!#thro%s /rrayIndex&ut&f)oundsException : : //1o compilation error$

Di33erence bet*een Chec,ed and Unchec,ed exceptions:


Chec,edException Except for GuntimeException@ Error@ and their subclasses@ all other exceptions are called checked exceptions. /ll checked exceptions must be handled@ other%ise the program %ill not be compiled. If a method thro% checked exceptions@ they must be specified in the thro%s clause. )ut@ more checked exceptions must not be specified in the thro%s clause. UnChec,edException Exceptions inherited from Error or GuntimeException class and their subclasses are kno%n as unchecked exceptions. $he compiler %ill not force unchecked exceptions to be handled i.e.@ unchecked exceptions may or may not be handled. (pecifying unchecked exceptions in thro%s clause is optional.

JAVA.LANG PACKAGE
)ierarch# ?bHect class "tring "tring6u33er E "tring6uider (Id,8$C) Prapper classes 2utoboxing and Unboxing (Id,8$C)
$his package is automatically imported into e2ery source file at compile time. $his package contains most common classes in 'a2a.

&b'ect

(tring

(tring)uffe r

(tring)uilder )oolean

Math <oid

umber

Character

)ig3ecimal )igInteger

)yte 3ouble

(hort

Integer

Dong

Float

.igure: ;artial Hierarchy &f 'a2a.lang ;ackage classes 1ote: ,# 0# C# R# -# $he six numeric %rapper classes are )yte@ (hort@ Integer@ Dong@ Float@ 3ouble. $he three non numeric %rapper classes are Character@ )oolean@ and <oid. /ll %rapper classes@ (tring@ (tring)uffer@ (tring)uilder classes are final. /ll %rapper classes and (tring classes are immutable. /ll %rapper classes and (tring classes are Comparable and (eriali"able.

CI

C,

?bHect class
E2ery 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:


,. 0. C. R. -. S. T. U. V. public (tring to(tring!# public boolean e1uals!# public int hashCode!# protected &b'ect clone!# public Class getClass!# public 2oid %ait!# public 2oid notify!#7 public 2oid notify/ll!# 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 %idth7 int height7 int depth7 )ox!int %@ int h@ int d#6 .idth 9 %7 Height 9 h7 3epth 9 d7 : Int 2olume!#6 Geturn %idth H height H depth7 : public "tring to"tring()! return JPidth>K/*idth /K )eight>K/height /K Depth>K/depth; & : )ox b, 9 ne% )ox!,@ 0@C#7 )ox b0 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 C .idth9R height 9 - depth 9 S C0

;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@C#7 )ox b0 9 ne% )ox!,@0@C#7 )ox bC 9 b,7 (&; !b, 99 b0#7 ==false (&; !b, 99 bC#7 ==true (&; !b0 99 bC#7 ==false It is al%ays recommended to o2erride e1uals!# method to compare t%o ob'ect states. >&2erride public boolean e1uals!&b'ect o# 6 ==Comparing %ith null reference al%ays returns null. if !o 99 null# return false7 ==Comparing incompatible types al%ays thro%s ClassCastException. if !8!o instanceof )ox## thro% ne% ClassCastException!#7 ==alias comparision. if !this 99 o# return true7 )ox b 9 !6ox# o7 ==content comparison if !!this.%idth 99 b.%idth# ** !this.height 99 b.height# ** !this.depth 99 b.depth## 6 return true7 : else 6 return false7 : : )ox b, 9 ne* )ox!,@0@C#7 )ox b0 9 ne* )ox!,@0@C#7 )ox bC 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==tru e (ystem.out.println!b, 99 bC#7==false (ystem.out.println!b,.e1uals!bC##7 = =false (ystem.out.println!b,99bR#7 ==true

(ystem.out.println!b,.e1uals!bR##7==tru e

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


>> operator Used to compare reference 2alues but not actual ob'ect states i.e.@ used for (e3erence comparision$ eQuals() method Used to compare actual ob'ect states !Content comparision#.

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 is associated %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. >&2erride public int hashCode() ! final int prime 9 C,7 int result 9 ,7 result 9 prime H result J depth7 result 9 prime H result J height7 result 9 prime H result J %idth7 return result7 : )ox b, 9 ne% )ox!,@0@C#7 )ox b0 9 ne% )ox!R@-@S#7 )ox bC 9 ne% )ox!,I@0I@CI#7 )ox bR 9 ne% )ox!RI@-I@SI#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. C# 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$"tring
In '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#. "trings are created in R *a#s: ,# (tring Diterals Example: (tring str 9 4aspire57

0# (tring ob'ects

Example: (tring str 9 ne% (tring!4aspire5#7 C# (tring constant expressions. Example: (tring str 9 4aspire 5 J 4 technoloiges5P7 R# (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 is created. )eap Memor# aspire str /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 perform changes. 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# (tr, (tr0 !str, 99 str0# ==true (tr,.e1uals!str0# ==true. String literals are al&ays 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 already exists@ then reference 2alue of the existing string literal is returned. )ence+ "tring Constant ;ool ("C;) never allo*s duplicate string literals$

"tring Constant ;ool ("C;) hello

Case 9: "tring obHects (tring str, 9 ne* (tring!4hello5#7 (tring str0 9 ne* (tring!4hello5#7 )eap Memor# hello (tr, (tr0 hello

==string ob'ect ==string ob'ect "tring Constant ;ool ("C;)

!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 literal 23ter compilation (tring str, 9 4hello57==Gesol2ed at compile time into string literal. )eap Memor# (tr0 (tr, !str, 99 str0# ==true (tr,.e1uals!str0# = =true. (tring constant expressions are computed at compile time@ henced they are string literals@ %hich is stored 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'ect 23ter Compilation: (tring str0 9 ne* "tring6u33er(str8)$append(JloK)$to(tring!#7 )eap Memor# hello (tr0 "tring Constant ;ool ("C;) hel (tr, "tring Constant ;ool ("C;) hello

!str, 99 str0# ==false (tr,.e1uals!str0# ==true. Example S9: 6e3ore compilation: (tring str, 9N$his is N7 (tring str0 9Ntesting the N7 (tring strC9Ndifference 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 / strC / strT/strU; 23ter compilation: ne% (tring)uffer!str,#.append!str0#.append!strC#.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 heap memory.

"tring Constructors
,# ;ublic (tring!# Creates an empty string %hose length is "ero. ;ublic (tring!(tring str# Example: (tring str 9 ne% (tring!4hello5#7 ==string ob'ect ;ublic (tring!charAB 2alue# Example: charA/ value > +<a=+=b=+=c=&; string str 9 ne% (tring!2alue#7 ==5abc5 ;ublic (tring!byteAB bytes# Example: byteAB bytes 9 6VT@VU@VV:7 (tring str 9 ne% (tring!bytes#7==5abc5 ;ublic (tring!(tring)uffer sb# Example: (tring)uffer sb 9 ne% (tring)uffer!4hello5#7 (tring str 9 ne% (tring!sb#7 ;ublic (tring!(tring)uilder sb# Example: (tring)uilder builder 9 ne% (tring)uilder!4hello5#7 (tring str 9 ne% (tring!sb#7

0# C#

R#

-#

S#

"tring Methods
8$ ;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 begin ndex+ int end ndex) 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!I@ S#7 ==5aspire5 ;ublic "tring substring(int begin ndex) 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 last ndex?3() methods are overloaded$ ;ublic int lastIndex&f!char ch# ;ublic int lastIndex&f!(tring str# Example: (tring name 9 4'a2a.lang. nteger57 (tring c ame 9 name.substring!name.lastIndex&f!O.P# J,#7 ==5Integer5 (tring p ame 9 name.substring!I@name.lastIndex&f!O.P##7 == 4'a2a.lang5 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

R$

C$

T$

U$

(&;!str.length!##7 ==V$ public "tring to4o*erCase() Geturns string in lo%ercase format. Example: (tring name95G/ME(H57 (tring after 9 name.toDo%erCase!#7 ==ramesh public "tring toUpperCase() Geturns string in uppercase format. Example: (tring name95ramesh57 (tring after 9 name.toUpperCase!#7 ==G/ME(H

W$

8B$ public "tring trim() Gemo2es leading and trailing spaces@ if any. Example: (tring str 9 4 ramesh 5 (op!str.trim!##7==5ramesh 5 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'ect07 Geturn I@ then both ob'ect, and ob'ect0 are e1ual. Example: (op!4a5.compare$o!4b5##7==, (op!4b5.compare$o!4a5##7== J, (op!4a5.compare$o!4a5##7== I

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 existing ob'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 specified string. $he initial capacity of the string buffer is : 8T / str$length()

Example: (tring)uffer sb 9 ne% (tring)uffer!4hello5#7 (&;!sb.capacity!##7 ==0, (&;!sb.length!##7 ==C# ;ublic (tring)uffer!int initialCapacity# Creates an empty string buffer %ith specified initial capacity.

"tring6u33er Methods
,. 0. C. R. ;ublic int capacity!# //1ot available in "tring class Geturns the current capacity of the (tring)uffer. It means@ the maximum number of characters in can hold. &nce it reaches it capacity@ it automatically increases. ;ublic int length!# Geturns the actual number of characters contained in the (tring)uffer. ;ublic char char/t!int index# $he follo%ing are append!# o2erloaded methods in (tring)uffer class ;ublic (tring)uffer append!(tring s# ;ublic (tring)uffer append!)oolean b# ;ublic (tring)uffer append!char s# ;ublic (tring)uffer append!int s# ;ublic (tring)uffer append!long s# ;ublic (tring)uffer append!double s# ;ublic (tring)uffer append!float s# ;ublic (tring)uffer append!&b'ect s# 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@ (tring s# ;ublic (tring)uffer insert !int pos@ )oolean b# ;ublic (tring)uffer insert !int pos@ char c# ;ublic (tring)uffer insert!int pos@ int i# ;ublic (tring)uffer insert !int pos@ long l# ;ublic (tring)uffer insert !int pos@ float f# ;ublic (tring)uffer insert!int pos@ double f# 1ote: (tring does not ha2e this method. Example: (tring)uffer sb 9 ne% (tring)uffer!4,00,5#7 (b.insert!0@5CC5#7 ==,0CC0, ;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,0CC0,5#7 (b.delete!0@R#7 ==,00, ;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

-.

S.

T. U.

V.

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

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$C)
(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 by more than one thread at a time. (o@ ;erformance is good %ith (tring)uilder. 3ifferences bet%een (tring)uffer and (tring)uilder: "tring6u33er "tring6uilder (ynchroni"ed class !i.e.@ thread-safe# on-(ynchroni"ed class !i.e.@ non thread-safe# ;erformance is lo% ;erformance is high Degacy class Introduced in +dk,.-

Prapper classes

?bHect

1umber

6oolea n

Character

Void

6#te

"hort Double

nteger

4ong

.loat

.ig: Prapper classes .rapper classes are used to %rap !store# primiti2e data into an ob'ect. Hence@ primiti2e types can also be handled 'ust like an ob'ect. )y default@ all %rapper classes are final@ hence cannot be inherited. /lso@ the instance of all %rapper classes are immutable i.e.@ the 2alue in the %rapper ob'ect cannot be changed. ;ublic final class Integer extends umber6 private 3inal int value; public Integer!int 2alue#6 this.2alue 9 2alue7 : ;ublic Integer!(tring 2alue#6 2alue 9 parseInt!2alue# : public byte byte<alue!# 6 return (b#te)2alue7 : public short short<alue!# 6 return (short)2alue7 : public int int<alue!# 6 return 2alue7 : public long long<alue!# 6 return !long#2alue7 : public float float<alue!# 6 return !float#2alue7 : public double double<alue!# 6 return !double#2alue7 : :

Constructors

/ll %rapper classes except Character ha2e t%o o2erloaded constructors: ;rimiti2e type and (tring type constructors.

Iava$lang$ nteger
;ublic Integer!int 2alue#6: ;ublic Integer!(tring 2alue# Example: Integer iGef, 9 ne% Integer!R#7 Integer iGef, 9 ne% Integer!4R5#7

Iava$lang$4ong
;ublic Dong!long 2alue#6: ;ublic Dong!(tring 2alue#6: Example: Dong lGef 9 ne% Dong!,I#7 Dong lGef 9 ne% Dong!,ID#7 Dong lGef 9 ne% Dong!4,I5#7 Iava$lang$.loat ;ublic Float!float 2alue#6: ;ublic Float!double 2alue#6: ;ublic Float!(tring 2alue#6: Example: Float fGef 9 ne% Float!C.-F#7 Float fGef 9 ne% Float!C.-#7 Float fGef 9 ne% Float!4C.-F5#7 Iava$lang$Character !Contains only one constructor# ;ublic Character!char 2alue# Example: Character cGef 9 ne% Character!OaP#7 Character cGef 9 ne% Character!4a5#7 //C$E

Iava$lang$6oolean ;ublic )oolean!boolean 2alue# ;ublic )oolean!(tring 2alue# /llocates a )oolean ob'ect representing the 2alue true if the string argument is not null and is e1ual@ ignoring case@ to the string NtrueN. Example: )oolean bGef 9 ne% )oolean!4true5#7 )oolean bGef 9 ne% )oolean!4$rue5#7 ==true )oolean bGef 9 ne% )oolean!4$GUE5#7 )oolean bGef 9 ne% )oolean!null#7 )oolean bGef 9 ne% )oolean!4yes5#7 )oolean bGef 9 ne% )oolean!4no5#7 ==false

)oolean bGef 9 ne% )oolean!4aspire5#7 Iava$lang$Void /lthough the <oid class is considered as a %rapper class@ it does not %rap any primiti2e 2alue and is not instantiable i.e has no public constructors. It 'ust denotes the Class ob'ect representing the key%ord 2oid.

.ields
$he follo%ing constants are declared for each %rapper class except )oolean: ;ublic static final primiti2e type MI \</DUE ;ublic static final primiti2e type M/?\</DUE ;ublic static final int (IQE ;ublic static final Class $^;E7 $he follo%ing constants are declared only for )oolean class: ;ublic static final )oolean F/D(E7 ;ublic static final )oolean $GUE7 ;ublic static final Class $^;E7

Method s

type<alue!# 2alue&f! #

;rimiti2 e data parse$ype! #

static to(tring!primiti2 e

.rappe r ob'ect

2alue&f!# to(tring! #

(trin g 2alue

0he methods are: ,. type<alue!# methods Getrie2es primiti2e 2alue from %rapper ob'ect. 0. parse$ype!# methods Con2erts numeric string into numeric 2alue. C. o2erloaded 2alue&f!# /lternati2e to constructors. R. o2erloaded to(tring!#Geturns string representation of primiti2e data. 8$ t#peValue() methods Getrie2ing ;rimiti2e 2alue from %rapper ob'ect. a) "ix Methods:
$he follo%ing methods are applicable for all numeric %rapper classes:

public byte byte<alue!# /ll numeric %rapper classes A)yte@ (hort@ Integer@ Dong@ public short short<alue!# Float@ 3oubleB contains six methods. public int int<alue!#

RR

public long long<alue!# public float float<alue!# public double double<alue!# b) booleanValue() $his method is applicable only for )oolean %rapper class. Example: )oolean bGef 9ne% )oolean!4yes5#7 (&;!bGef.boolean<alue!##7 == false c) charValue() $his method is applicable only for Character %rapper class. Example: Character cGef 9 ne% Character!OaP#7 (&;!cGef.char<alue!##7 == OaP 9$ parse0#pe("tring) Methods E2ery %rapper class except Character class contains follo%ing static parse$ype!# method to con2ert (tring 2alue to ;rimiti2e data. Prapper class parse0#pe("tring) Example +a2a.lang.)yte parse)yte!(tring# byte b 9 )yte.parse)yte!4,5#7 byte 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,.IF5#7 +a2a.lang.3ouble pase3ouble!(tring# 3ouble d 9 3ouble.parse3ouble!4,.I5#7 +a2a.lang.)oolean pase)oolean!(tring# )oolean b 9 )oolean.parse)oolean!4no5#7
:$ value?3() method $he o2erloaded static 2alue&f!# methods are alternative to constructors to create %rapper ob'ect. ;ublic static .rapper type 2alue&f!primiti2e type# ;ublic static .rapper type 2alue&f!(tring# Example: Integer iGef 9 Integer.2alue&f!,I#7 Integer iGef 9 Integer.2alue&f!4,I5#7 Integer iGef 9 Integer.2alue&f!4ten5#7==thro%s ;E

R$ to"tring()
/ll %rapper classes o2errides to(tring!# method to return %rapper ob'ect 2alue in string format. /lso@ all %rapper classes ha2e o2erloaded static to(tring!primiti2e type# method to con2ert primiti2e 2alue into string format. Example: (tring str 9 Integer.to(tring!,I#7 == 4,I5

Integer iGef 9 ne% Integer!,I#7 (tring str 9 iGef.to(tring!#7 == 4,I5 /lso@ the Integer@ Float@ 3ouble classes contains the follo%ing xxx(tring!# methods for con2erting primiti2e to )inary@ &ctal@ and Hexa format. to)inary(tring!int# to&ctal(tring!int# Integer Float or 3ouble Example: (tring s 9 Integer.to)inary(tring!,I#7 ==,I,I (tring s 9 Integer.toHex(tring!,I#7 ==a toHex(tring!int = float= double#

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 ,I. 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!,I#7 23ter compilation: Int I 9 ne* nteger(8B)$intValue()7 ==unboxing.

(e3lection Mechanism
Geflection 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@ E interfacenB 6 //.ields Wfield modifiersX type name7 E //Constructors Wconstructor modifiersX name!Wparameters listX#6: E //Methods Wmethod modifiersX Wreturn typeX name!Wparameters listX#6: : $o obtain information about classes@ %e ha2e to use Hava$lang$Class and Hava$lang$re3lect package.

Iava$lang$Class
.hen the class is loaded into +<M@ a class ob'ect is created in heap area. (uch a class ob'ect contains complete information about specified class. Methods: ,. public static Class 3or1ame!(tring fully 1ualified class ame# thro%s Class otFoundException Example: Class c 9 Class.for ame!4'a2a.lang.(tring5#7 == Geturns class ob'ect but not string type 0. C. Metting class modifiers ;ublic int getModifiers!#7 Metting class name ;ublic (tring get ame!# Geturns fully 1ualified class name. ;ublic (tring get(imple ame!# Geturns 'ust class name %ithout 1ualified %ith type. Metting superclass information ;ublic Class get(uperclass!# Metting interface!s# information ;ublic ClassAB getInterfaces!# Metting field!s# information ;ublic .ieldAB getFields!#7 Metting constructor!s# information ;ublic ConstructorAB getConstructors!# RT

R. -. S. T.

U.

Metting method!s# information

RU

;ublic MethodAB getMethods!# V. Creating ne% instance ;ublic &b'ect ne* nstance()

Iava$lang$re3lect$.ield
E2ery field in a class must ha2e the follo%ing format: W3ield modi3iersX W3ield t#peX W3ield nameX7 Methods: ,# Metting field modifiers. ;ublic int getModifiers!# 0# Metting field type ;ublic Class get$ype!# C# Metting field name ;ublic (tring get ame!#

Hava$lang$re3lect$Constructor
E2ery constructor in a class must ha2e the follo%ing format: Wconstructor modifierX Wconstructor nameX!Wparameters listX# Methods: ,# Metting constructor modifier ;ublic int getModifiers!# 0# Metting constructor name ;ublic (tring get ame!# C# Metting constructor parameters ;ublic ClassAB get;arameter$ypes!#

Iava$lang$re3lect$Method
E2ery method in a class must ha2e the follo%ing format: Wmethod modifiersX Wreturn typeX Wmethod nameX!Wparameters listX# Methods: ,# Metting method modifiers ;ublic int getModifiers!# 0# Metting method return type ;ublic Class getGeturn$ype!# C# Metting method name ;ublic (tring get ame!# R# Metting method parameters list ;ublic ClassAB get;arameter$ypes!# RV

+a2a bean is a reusable soft%are component. In generally@ a +a2a )ean perform a specific task. (ome +a2a beans are <isible and others are In2isible. / +a2a bean may contains ;roperties@ Methods@ and Events.

Iava 6eans

F (eusable "o3t*are component G

Iava beans (ules:


,# +a2a )ean class must be declared %ith public modifier. 0# +a2a )ean must support ;ersistence !"eriali'ation) by extending 'a2a.io.(eriali"able interface. C# +a2a )ean must support ntrospection$ $o support introspection@ )eans must pro2ide access methods to properties. R# +a2a )ean must pro2ides Qero-argument constructors. Example: package edu.aspire7 ==Gecommended ;ublic class Employee implements "eriali'able6 ;rivate int eno7 ;rivate (tring ename7 ;rivate long mobile7 ;ublic Emplo#ee()!& ;ublic 2oid setEno!int eno#6 this.eno 9 eno7 : ;ublic int getEno!#6 return this.eno7 : ;ublic 2oid setEname!(tring ename#6 this.ename 9 ename7 : ;ublic (tring getEname!#6 return ename7 : ;ublic 2oid setMobile!long mobile#6 this.mobile 9 mobile7 : ;ublic (tring getMobile!# 6 return this.mobile7: : ==)ean property methods. ==)ean properties

-I

ntrospection Mechanism
Introspection is the process !or mechanism# of obtaining information about a +a2a )ean i.e.@ getting information about properties@ e2ents@ and methods of a 'a2a bean class. $he +a2a bean class ha2e follo%ing property types: I. (imple properties II. )oolean properties III. Indexed properties 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 (tring get ame!#6: ;ublic 2oid set !$ 2alue# ;ublic 2oid set ame!(tring name#6: )oolean ;ublic boolean is !# ;ublic boolean isHoliday!#6: ;ublic boolean get !# ;ublic boolean getHoliday!#6: ;ublic 2oid set !boolean 2alue# ;ublic 2oid setHoliday!boolean 2alue#6: Indexed ;ublic $ get !int index# ;ublic boolean getInputs!int index#6: ;ublic $AB get !# ;ublic booleanAB getInputs!# ;ublic 2oid set !int index@ $ ;ublic 2oid setInputs!int index@ 2alue# ;ublic 2oid set !$AB boolean 2alue#6: 2alue#6: ;ublic 2oid setInputs!booleanAB 2alues#6: Introspection mechanism uses Hava$beans package from +3[ /;I to analy"e +a2a )eans.

Iava$beans$ ntrospector
It 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$6ean n3oMMinter3aceNN
$he follo%ing methods from )eanInfo ob'ect gi2es information about ;roperties@ E2ents@ and Methods of a +a2a )ean class. ,# ;ublic ;roperty3escriptorAB get;ropert#Descriptors!# 0# ;ublic Method3escriptorAB getMethodDescriptors!# C# ;ublic E2ent(et3escriptorAB getEvent"etDescriptors!# Example: import 'a2a.a%t.)utton7 import 'a2a.beans.)eanInfo7 import 'a2a.beans.E2ent(et3escriptor7 import 'a2a.beans.IntrospectionException7 import 'a2a.beans.Introspector7 import 'a2a.beans.Method3escriptor7

import 'a2a.beans.;roperty3escriptor7 public class ItrospectionEx, 6 public static 2oid main!(tringAB args# 6 try 6 6ean n3o bean n3o > ntrospector$get*eanIn$o(6utton$class);

(ystem.out.println!N---------------------N#7 (ystem.out.println!N+a2a )ean ;roperties:N#7 (ystem.out.println!N---------------------N#7 ;ropert#DescriptorFG props > bean n3o$get;ropert#Descriptors(); for !;roperty3escriptor prop : props# 6 (ystem.out.println!prop.get;roperty$ype!#.get(imple ame !# J N N J prop.get ame!##7 : (ystem.out.println!N------------------N#7 (ystem.out.println!N+a2a )ean Methods:N#7 (ystem.out.println!N------------------N#7 MethodDescriptorFG methods > bean n3o$getMethodDescriptors(); for !Method3escriptor method : methods# 6 (ystem.out.println!method.get am e!##7 : (ystem.out.println!N-----------------N#7 (ystem.out.println!N+a2a )ean E2ents:N#7 (ystem.out.println!N-----------------N#7 Event"etDescriptorFG events > bean n3o$getEvent"etDescriptors(); for!E2ent(et3escriptor e2ent : e2ents# 6 (ystem.out.println!e2ent.get am e!##7 : : catch !IntrospectionException e# 6 e.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 the properties@ e2ents@ and methods of a +a2a )ean. 0# Introspection mechanism internally uses Geflection /;I to retrie2e properties@ e2ents@ or methods information.

Potrebbero piacerti anche