Live Example.doc
-
Upload
rajanikanthmeka77766 -
Category
Documents
-
view
214 -
download
0
Transcript of Live Example.doc
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 1/72
Live Example : Simple Class Program [Area of Rectangle]
class Rectangle { double length; double breadth;}
// This class declares an object of type Rectangle.class RectangleDemo { public static void main(String args!" { Rectangle myrect # ne$ Rectangle("; double area;
// assign %alues to myrect&s instance %ariables myrect.length # '; myrect.breadth # );
// *ompute +rea of Rectangle area # myrect.length , myrect.breadth ;
System.out.println(-+rea is - area"; }}
Output :
*0riteshja%a1ja%a RectangleDemo+rea is ).
[336×280]
Explanation : Class Concept
1. Class Creation !eclaration :
Consider following class –
class Rectangle { double length; double breadth;}
• class defines a ne" t#pe of $ata.
• Rectangle is our new data type.
• %Rectangle& will be used to $eclare o'(ects of t#pe Rectangle.
• class declaration only creates a template. t does not create an actual o'(ect.
). Creation of O'(ect
Rectangle myrect # ne$ Rectangle(";
• !ctual Creation of "b#ect.
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 2/72
• *emor# is allocate$ for an o'(ect after e$ecuting t%is statement.
• &%is 'tatement will create instance of t%e class (Ractangle) and name of instance is
not%ing but actual ob#ect (m#rect(.
• +res, cop# of -nstance varia'les gets created for *res% nstance. [myrect now %a+e its
own instance +ariables ,- lengt%breadt% ]
• *ollowing fig s%ows one un/nown term – Constructor 1ont worry about t%is term
you will get more details in t%e incoming c%apters
. Accessing -nstance /aria'les Of O'(ect-nstance using !O0 Operator
myrect.length # ';myrect.breadth # );
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 3/72
• !s e$plained earlier 4ac% nstance5"b#ect gets t%eir o"n cop# of instance varia'les i.e
lengt, an$ 'rea$t,.
• e can access (m#rects) copy of instance +ariable using (!O0) operator as s%own
abo+e.
Java instance variables
Java instance variables
n t%e pre+ious program we %a+e learned %ow class concept is used in programmatic approac%.
7enerally eac% ob#ect %a+e its own set of instance +ariables. ow in t%is c%apter we are going to
see %ow different ob#ects access t%eir instance +ariables.
Live Example : Class 2it, 0"o O'(ects 3Eac, ,ave its o"n
cop# of -nstance /aria'le
class Rectangle { double length; double breadth;}
// This class declares an object of type Rectangle.class RectangleDemo { public static void main(String args!" { Rectangle myrect' # ne$ Rectangle("; Rectangle myrect) # ne$ Rectangle("; double area'2area);
// assign %alues to myrect'&s instance %ariables myrect'.length # '; myrect'.breadth # );
// *ompute +rea of Rectangle area' # myrect'.length , myrect'.breadth ; System.out.println(-+rea of Rectange ' - area'";
// assign %alues to myrect)&s instance %ariables myrect).length # '; myrect).breadth # );
// *ompute +rea of Rectangle area' # myrect).length , myrect).breadth ; System.out.println(-+rea of Rectange ) - area)";
}}
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 4/72
Explanation :
Eac, O'(ect ,as its o"n set of -nstance /aria'les :
1. In the above program we have created two objects of the class “Rectangle” ,i.e myrect1,myrect2
Rectangle myrect' # ne$ Rectangle(";Rectangle myrect) # ne$ Rectangle(";
2. As soon as above two statements gets exected , two objects are createdwith specimen copy of their instance variables.
!. In short myrect1"s version of lemgth and breadth gets created . #imilarlymyrect2"s version of length and breadth gets created.
$. %sing dot &perator we can access instance variable of respective object.
f you want to access instance +ariable of m#rect1 "b#ect –
myrect'.length # ';myrect'.breadth # );
f you want to access instance +ariable of m#rect) "b#ect –
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 5/72
myrect).length # 3;myrect).breadth # ';
'. (e can assign di)erent vales to instance variables of object. Instancevariable of dierent objects though have same name , they havedierent memory address , dierent value.
*. It is important to nderstand that changes to the instance variables of
one object have no eect on the instance variables of another.
Java declaring object in class
!eclaring O'(ect in Class : !eclaring Reference to an O'(ect
in 4ava Programming
9. %en we create class t%en "e are creating ne" $ata t#pe.2. ewly created data type is used to create an O'(ect of t,at Class 0#pe.
3. Creating ob#ect is t"o step process.
Creation of O'(ect involves t"o steps 5
9. 1eclaration
2. !llocation and !ssigning
Rectangle myrect' # ne$ Rectangle(";
t%is statement is used to create an ob#ect we are going to brea/ down t%is statement in two
separate statements –
Rectangle myrect' ;myrect' # ne$ Rectangle(";
Step 1 : !eclaration of /aria'le of 0#pe Class
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 6/72
9. !bo+e 1eclaration will #ust $eclare a varia'le of class t#pe.
2. 1eclared :ariable is able to store t,e reference to an o'(ect of Rectangle 0#pe.
3. !s we %a+e not create$ an# o'(ect of class Rectangle and we ,avent assigne$ an#
reference to m#rect1 it will be initiali6e$ "it, null.
Step ) : Allocation an$ Assigning O'(ect to varia'le of class0#pe
9. !bo+e 'tatement will create p,#sical cop# of an o'(ect.
2. &%is P,#sical Cop# is t,en assigne$ to an varia'le of 0#pe Class i.e myrect9.
3. 7ote : myrect9 %olds an instance of an ob#ect not actual ob#ect. Actual O'(ect is create$
else",ere an$ instance is assigne$ to m#rect1.
-n s,ort 5
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 7/72
9. *irst statement will #ust create +ariable m#rect1 w%ic% will store address of actual ob#ect.
2. *irst 'tatement will not allocate any p%ysical memory for an ob#ect t%us any attempt
accessing +ariable at t%is stage will cause compile time error.
3. 'econd 'tatement will create actual ob#ect rann$oml# at an# memor# a$$ress ",ere it
foun$ sufficient memor#.
;. !ctual memory address of "b#ect is stored inside m#rect1.
Java null keyword
0,e null 8e#"or$ : 7ull Reference insi$e -nstance /aria'le
9. ! reference +ariable refers to an ob#ect.
2. %en a reference +ariable does not %a+e a +alue it is not referencing an ob#ect suc% areference +ariable is said to %a+e a null +alue.
Live Example : 7ull /alue
class Rectangle { double length; double breadth;}
class RectangleDemo { public static void main(String args!" {
Rectangle myrect'; System.out.println(myrect'.length";
}}
Output :
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 8/72
*0riteshja%a1ja%ac RectangleDemo.ja%aRectangleDemo.ja%a' %ariable myrect' might not ha%ebeen initiali4ed System.out.println(myrect'.length"; 5' error
[;68×60]
Explanation : 7ull /alue
9. !s e$plained in t%e pre+ious c%apter Creating "b#ect is two step process.2. n t%e abo+e e$ample m#rect is not initiali6e$.
3. !efault value insi$e m#rect1 is null means it does not contain any reference.
;. f you are declaring reference +ariable at (Class Level) t%en you $ont nee$ to initiali6e
instance varia'le wit% null. !bo+e 4rror <essage = error is at println stetement
C,ec9ing null /alue
class Rectangle { double length; double breadth;}
class RectangleDemo { public static void main(String args!" {
Rectangle myrect';
if(myrect' ## null" { myrect' # ne$ Rectangle("; }
}}
• e can c%ec/ null +alue using () operator.
!ifferent 2a#s Of 7ull /alue Statements :
2a# 1 : Class Level null /alue
9. o need to initiali>e instance varia'le "it, null.
2. nstance :ariable contain $efault value as %null&.
3. <eaning of (null) is t%at – -nstance /aria'le $oes not reference to an# o'(ect.
Rectangle myrect';
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 9/72
is similar to –
Rectangle myrect' # null;
2a# ) : *et,o$ Level null /alue
9. 'uppose we %a+e to create any ob#ect inside (<et%od) t%en we must initiali>e instance+ariable wit% ull +alue.
2. f we forgot to initiali>e instance +ariable wit% null t%en it will t%row compile time error.
/ali$ !eclaration :
Rectangle myrect' # null;
-nvali$ !eclaration :
Rectangle myrect' ;
Java assigning object reference
Assigning O'(ect Reference /aria'les : Class Concept in
4ava Programming
9. e can assign +alue of reference +ariable to anot%er reference +ariable.2. ?eference :ariable is used to store t%e address of t%e +ariable.
3. !ssigning ?eference will not create distinct copies of "b#ects.
;. !ll reference +ariables are referring to same "b#ect.
Assigning O'(ect Reference /aria'les $oes not 5
9. Create 1istinct "b#ects.
2. !llocate <emory
3. Create duplicate Copy
Consi$er 0,is Example 5
Rectangle r' # ne$ Rectangle(";Rectangle r) # r';
• r9 is reference +ariable w%ic% contain t%e address of !ctual ?ectangle "b#ect.
• r2 is anot%er reference +ariable
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 10/72
• r2 is initiali>ed wit% r9 means – (r1 an$ r)) bot% are referring same ob#ect t%us it does
not create duplicate ob#ect nor does it allocate e$tra memory.
[;68×60]
Live Example : Assigning O'(ect Reference /aria'les
class Rectangle { double length; double breadth;}
class RectangleDemo { public static void main(String args!" {
Rectangle r' # ne$ Rectangle("; Rectangle r) # r';
r'.length # '; r).length # );
System.out.println(-6alue of R'&s 7ength - r'.length";
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 11/72
System.out.println(-6alue of R)&s 7ength - r).length";
}}
Output :
*0riteshja%a1ja%a RectangleDemo6alue of R'&s 7ength ).6alue of R)&s 7ength ).
0#pical Concept :
'uppose we %a+e assigned null +alue to r2 i.e
Rectangle r' # ne$ Rectangle(";Rectangle r) # r';
.
.
.r' # null;
7ote : 'till r2 contain reference to an ob#ect. &%us e can create %a+e multiple reference+ariables to %old single ob#ect.
Java class methods
-ntro$ucing *et,o$s in 4ava Class : Class Concept in 4ava
9. n @a+a Class e can add user defined met%od.
2. <et%od is eAui+alent to *unctions in C5CBB rogramming.
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 12/72
S#ntax : *et,o$s in 4ava Classes
return8type method8name ( arg' 2 arg) 2 arg9 "
1. return;t#pe is not%ing but t%e +alue to be returned to an calling met%od.2. met,o$;name is an name of met%od t%at we are going to call t%roug% any met%od.
!. arg1<arg)<arg are t%e different parameters t%at we are going to pass to a met%od.
Return 0#pe of *et,o$ :
9. <et%od can return any type of +alue.2. <et%od can return any rimiti+e data type
int sum (int num'2unt num)";
3. <et%od can return "b#ect of Class &ype.
Rectangle sum (int num'2unt num)";
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 13/72
;. <et%od sometimes may not return +alue.
void sum (int num'2unt num)";
*et,o$ 7ame :
9. <et%od name must be +alid identifier.2. !ll :ariable naming rules are applicable for writing <et%od ame.
Parameter List :
9. <et%od can accept any number of parameters.
2. <et%od can accept any data type as parameter.
3. <et%od can accept "b#ect as arameter
;. <et%od can accept no arameter.
D. arameters are separated by Comma.
6. arameter must %a+e 1ata &ype
Live Example : -ntro$ucing *et,o$ in 4ava Class
class Rectangle { double length; double breadth;
void set7ength(int len" { length # len; }}
class RectangleDemo { public static void main(String args!" {
Rectangle r' # ne$ Rectangle(";
r'.length # '; System.out.println(-:efore unction 7ength - r'.length";
r'.set7ength()"; System.out.println(-+fter unction 7ength - r'.length";
}}
Output :
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 14/72
*0riteshja%a1ja%a RectangleDemo:efore unction 7ength '.+fter unction 7ength ).
Explanation :
Calling a *et,o$ :
9. (r1) is an "b#ect of &ype ?ectangle.2. e are calling met%od (setLengt,3=) by writing –
<bject8=ame D<T! >ethod8=ame ( 0arameter 7ist " ;
!. *unction call is always followed by Semicolon.
*et,o$ !efinition :
9. <et%od 1efinition contain t%e actual 'o$# of t,e met,o$.2. <et%od can ta9e parameters an$ can return a value.
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 15/72
Java returning value from method
Returning /alue +rom t,e *et,o$ :
9. e can specify return type of t%e met%od as %Primitive !ata 0#pe& or %Class name&.
2. ?eturn &ype can be (:oid) means it $oes not return an# value.
3. <et%od can return a +alue by using (return) /eyword.
Live Example : Returning /alue from t,e *et,o$
class Rectangle { int length; int breadth;
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 16/72
void set7ength(int len" { length # len; }
int get7ength(" { return length; }
}
class RectangleDemo { public static void main(String args!" {
Rectangle r' # ne$ Rectangle(";
r'.set7ength()";
int len # r'.get7ength(";
System.out.println(-7ength of Rectangle - len";
}}
Output :
*0riteshja%a1ja%a RectangleDemo7ength of Rectangle )
0,ere are t"o important t,ings to un$erstan$ a'out returning values :
1. &%e t#pe of $ata returne$ '# a met,o$ must 'e compati'le "it, t,e return t#pe
specifie$ '# t,e met,o$. *or e$ample if t%e return type of some met%od is boolean you
could not return an integer.
boolean get7ength(" { int length # '; return(length"; }
2. 0,e varia'le receiving t,e value returne$ '# a met,o$ 3suc, as len< in t,is case=
must also 'e compati'le "it, t,e return t#pe specifie$ for t,e met,o$.
int get7ength(" { return length; }
boolean len # r'.get7ength(";
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 17/72
!. Parameters s,oul$ 'e passe$ in se>uence an$ t,e# must 'e accepte$ '# met,o$ in
t,e same se>uence.
void set0arameters(String str2int len" { ?????
????? ????? }
r'.set0arameters(')2-0ritesh-";
nstead it s%ould be li/e –
void set0arameters(int length2String str" { ????? ????? ?????
}
r'.set0arameters(')2-0ritesh-";
Java this keyword
t,is 9e#"or$ : Refer Current O'(ect in 4ava Programming
9. t,is is /eyword in @a+a.
2. e can use t%is /eyword in any met%od or constructor.
3. t%is /eyword used to refer current o'(ect.
;. Ese t,is 9e#"or$ from any met%od or constructor to refer to t%e current o'(ect t,at
calls a met,o$ or invo9es constructor .
S#ntax : t,is 8e#"or$
this.field
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 18/72
Live Example : t,is 8e#"or$
class Rectangle { int length; int breadth;
void setDiamentions(int ln2int br" { this.length # ln;
this.breadth # br; }
}
class RectangleDemo { public static void main(String args!" {
Rectangle r' # ne$ Rectangle(";
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 19/72
r'.setDiamentions()2'";
System.out.println(-7ength of Rectangle - r'.length"; System.out.println(-:readth of Rectangle - r'.breadth";
}}
Output :
*0riteshja%a1ja%a RectangleDemo7ength of Rectangle ):readth of Rectangle '
t,is 8e#"or$ is use$ to ,i$e -nstance /aria'le :
void setDiamentions(int length2int breadth" { this.length # length; this.breadth # breadth; }
• lengt%breadt% are t%e parameters t,at are passe$ to t,e met,o$.
• 'ame names are gi+en to t%e instance varia'les of an o'(ect.
• n order to %ide instance +ariable we can use t%is /eyword. abo+e synta$ will clearly
ma/e $ifference 'et"een instance varia'le an$ parameter.
Java Constructors
Constructors : -nitiali6ing an Class O'(ect in 4ava
Programming
9. "b#ects contain t%ere o"n cop# of -nstance /aria'les.
2. t is +ery difficult to initiali6e eac, an$ ever# instance varia'le of eac% and e+ery
ob#ect of Class.
3. @a+a allows o'(ects to initiali6e t,emselves ",en t,e# are create$. !utomatic
initiali>ation is performed t%roug% t%e use of a constructor.
;. ! Constructor initiali6es an o'(ect as soon as ob#ect gets created.
D. Constructor gets calle$ automaticall# after creation of o'(ect an$ 'efore completion
of ne" Operator.
Some Rules of ?sing Constructor :
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 20/72
9. Constructor -nitiali6es an O'(ect.
2. Constructor cannot 'e calle$ li/e met%ods.
3. Constructors are calle$ automaticall# as soon as ob#ect gets created.
;. Constructor $ont ,ave an# return 0#pe. e+en :oid
D. Constructor name is same as t%at of (Class 7ame(.
6. Constructor can accept parameter.
Live Example : @o" Constructor 2or9s
class Rectangle { int length; int breadth;
Rectangle("
{ length # ); breadth # '; }
}
class RectangleDemo { public static void main(String args!" {
Rectangle r' # ne$ Rectangle(";
System.out.println(-7ength of Rectangle - r'.length";
System.out.println(-:readth of Rectangle - r'.breadth";
}}
Output :
*0riteshja%a1ja%ac RectangleDemo.ja%a
*0riteshja%a1ja%a RectangleDemo7ength of Rectangle ):readth of Rectangle '
Explanation :
9. new "perator will create an ob#ect.
2. !s soon as "b#ect gets created it will call Constructor,
Rectangle(" //This is *onstructor {
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 21/72
length # ); breadth # '; }
3. n t%e abo+e Constructor nstance :ariables of "b#ect r9 gets t%eir own +alues.
;. &%us Constructor -nitiali6es an O'(ect as soon as after creation.
D. t will print :alues initiali>ed by Constructor –
System.out.println(-7ength of Rectangle - r'.length";System.out.println(-:readth of Rectangle - r'.breadth";
Java constructor example
Bet Anot,er Constructor Example : *ore !etaile$ Example
34ava Programming=class Rectangle { int length; int breadth;
Rectangle(" { length # ); breadth # '; }
void setDiamentions(" { length # @; breadth # ); }
}
class RectangleDemo { public static void main(String args!" {
Rectangle r' # ne$ Rectangle(";
System.out.println(-7ength of Rectangle - r'.length"; System.out.println(-:readth of Rectangle - r'.breadth";
r'.setDiamentions(";
System.out.println(-7ength of Rectangle - r'.length"; System.out.println(-:readth of Rectangle - r'.breadth";
}}
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 22/72
Output :
*0riteshja%a1ja%a RectangleDemo7ength of Rectangle ):readth of Rectangle '7ength of Rectangle @:readth of Rectangle )
Explanation :
9. !fter t%e Creation of "b#ect nstance :ariables %a+e t%eir own +alues inside.
2. !s soon as we call met%od values are reinitiali6e$.
Java parameteried constructor
Parameteri6e$ Constructors : Constructor 0a9ing
Parameters
n t%is article we are tal/ing about constructor t%at will ta/e parameter. Constructor ta/ing
parameter is called as (Parameteri6e$ Constructor(.
Parameteri6e$ Constructors :
9. Constructor Can &a/e :alue :alue is Called as – (Argument(.
2. !rgument can 'e of an# t#pe i.e ntegerC%aracter!rray or any "b#ect.
3. Constructor can ta9e an# num'er of Argument.
;. 'ee following e$ample – Fow arameteri>ed Constructor or/s G –
Live Example : Constructor 0a9ing Parameter in 4ava
Programming
class Rectangle { int length;
int breadth;
Rectangle(int len2int bre" { length # len; breadth # bre; }}
class RectangleDemo {
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 23/72
public static void main(String args!" {
Rectangle r' # ne$ Rectangle()2'";
System.out.println(-7ength of Rectangle - r'.length"; System.out.println(-:readth of Rectangle - r'.breadth";
}}
Output :
7ength of Rectangle ):readth of Rectangle '
Explanation :
Carefully obser+e abo+e program – Hou will found somet%ing li/e t%is –
Rectangle r' # ne$ Rectangle()2'";
&%is is arameteri>ed Constructor ta/ing argument.&%ese arguments are used for any purposeinside Constructor Iody.
• ew "perator is used to Create O'(ect.
• e are passing Parameter to Constructor as 2090.
• &%ese parameters are assigned to -nstance /aria'les of t,e Class.
• e can rite abo+e statement li/e –
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 24/72
Rectangle(int length2int breadth" { length # length; breadth # breadth; }
"?
Rectangle(int length2int breadth" { this.length # length; this.breadth # breadth; }
Iut if we use arameter name same as nstance +ariable t%en compiler will recogni>e instance+ariable and arameter but user or programmer may confuse. &%us we %a+e used ( t%is /eyword)
to specify t%at (/aria'le is -nstance /aria'le of O'(ect 5 r1(.
Java garbage collection
Dar'age Collection : !estro#ing O'(ect in 4ava
Programming
9. "b#ect is Created Esing ne" Operator.2. "b#ect gets memory inside (@eap(.
3. n CBB !fter Esing "b#ect *emor# for O'(ect gets $eallocate$ using $elete3=.
;. n @a+a !eallocation of O'(ect Can 'e $one automaticall#.
D. !utomatic &ec%niAue used in @a+a rogramming %ic% is used to de,allocate memory iscalled as (Dar'age Collection(.
6. @a+a is 'mart 4noug% to identify t%e ?nuse$ o'(ects or ?seless O'(ects.
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 25/72
Explanation :
9. 7arbage Collection is 1one Automaticall# '# 4/*.
2. !s soon as compiler detects t%at – "b#ect is no longer nee$e$ insi$e program 7arbage
Collection !lgorit%m gets e$ecuted automatically to free up memory from t%e %eap sot%at free memory may be used by ot%er ob#ects .
3. 1ifferent @a+a ?un times may %a+e $ifferent approac,es for Dar'age Collection. [&%isis reAuired information to understand 7arbage Collection – 1oing *urt%er ?J1 you
may +isit t%is]
Java method overloading
*et,o$ Overloa$ing :
9. n @a+a we can define number of met%ods in a class wit% t%e same name.
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 26/72
2. 1efining two or more met%ods wit% t%e same name in a class is calle$ met,o$
overloa$ing.
3. Compile determine w%ic% met,o$ to execute automaticall#.
;. &%e return type %as no effect on t%e signature of a met%od.
2,at is signature of t,e met,o$
9. &%e name of a met%od along wit% t%e t#pes an$ se>uence of t,e parameters is called
signature of t,e met,o$
2. Signature of t,e met,o$ s%ould be uniAue.
Signature of t,e met,o$ inclu$es 5
9. o of arameteres
2. 1ifferent arameters
3. 'eAuence of t%e parameters
Some Examples of t,e *et,o$ Overloa$ing :
int display(int num'2int num)";
"r
int display(double num'2int num)";
"r
%oid display(double num'2double num)";
Live Example :
package com.pritesh.programs;
class Rectangle { double length; double breadth;
%oid area(int length2 int $idth" { int area<fRectangle # length , $idth; System .out.println(-+rea of Rectangle - area<fRectangle"; }
%oid area(double length2 double $idth" { double area<fRectangle # length , $idth; System .out.println(-+rea of Rectangle - area<fRectangle"; }
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 27/72
}
class RectangleDemo { public static %oid main(String args!" {
Rectangle r' # new Rectangle(";
r'.area('2 )"; r'.area('.32 ).3";
}}
Explanation :
9. e %a+e defined 2 met%ods wit% same name and different type of parameters.2. %en bot% integer parameters are supplied to t%e met%od t%en it will e$ecute met%od
wit% all integer parameters and if we supply bot% floating point numbers as parametert%en met%od wit% floating numbers will be e$ecuted.
Java passing object as parameter
Passing O'(ect as Parameter :
package com.pritesh.programs;
class Rectangle { int length; int $idth;
Rectangle(int l2 int b" { length # l; $idth # b; }
%oid area(Rectangle r'" { int area<fRectangle # r'.length , r'.$idth; System .out.println(-+rea of Rectangle -
area<fRectangle"; }}
class RectangleDemo { public static %oid main(String args!" { Rectangle r' # new Rectangle('2 )"; r'.area(r'"; }}
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 28/72
Output of t,e program :
+rea of Rectangle )
Explanation :
9. e can pass "b#ect of any class as parameter to a met%od in #a+a.2. e can access t%e instance +ariables of t%e ob#ect passed inside t%e called met%od.
area # r'.length , r'.$idth
3. t is good practice to initiali>e instance +ariables of an ob#ect before passing ob#ect as
parameter to met%od ot%erwise it will ta/e default initial +alues.
!ifferent 2a#s of Passing O'(ect as Parameter :
2a# 1 : # $irectl# passing O'(ect 7ame
void area(Rectangle r'" { int area<fRectangle # r'.length , r'.$idth; System.out.println(-+rea of Rectangle -
area<fRectangle"; }
class RectangleDemo { public static void main(String args!" {
Rectangle r' # ne$ Rectangle('2 )"; r'.area(r'"; }
2a# ) : # passing -nstance /aria'les one '# one
pacAage com.pritesh.programs;
class Rectangle { int length; int $idth;
void area(int length2 int $idth" { int area<fRectangle # length , $idth; System.out.println(-+rea of Rectangle - area<fRectangle"; }}
class RectangleDemo { public static void main(String args!" {
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 29/72
Rectangle r' # ne$ Rectangle("; Rectangle r) # ne$ Rectangle(";
r'.length # ); r'.$idth # ';
r).area(r'.length2 r'.$idth"; }}
!ctually t%is is not a way to pass t%e ob#ect to met%od. but t%is program will e$plain you %ow to
pass instance +ariables of particular ob#ect to calling met%od.
2a# : 2e can pass onl# pu'lic $ata of o'(ect to t,e
*et,o$.
'uppose we made widt% +ariable of a class pri+ate t%en we cannot update +alue in a main
met%od since it does not %a+e permission to access it.
pri%ate int $idth;
after ma/ing widt% pri+ate –
class RectangleDemo { public static void main(String args!" { Rectangle r' # ne$ Rectangle("; Rectangle r) # ne$ Rectangle(";
r'.length # );
r'.$idth # ';
r).area(r'.length2 r'.$idth"; }}
Java returning object
Returning t,e O'(ect +rom *et,o$
n @a+a rogramming ! met%od can return any type of data including class types t%at you create.
*or e$ample in t%e following program t%e getRectangleO'(ect3 = met%od returns an ob#ect.
4ava Program : Returning t,e O'(ect +rom *et,o$
package com.pritesh.programs;
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 30/72
import ja%a.io.ile;import ja%a.io.B<Cception;
class Rectangle { int length; int breadth;
Rectangle(int l2int b" { length # l; breadth # b; }
Rectangle getRectangle<bject(" { Rectangle rect # new Rectangle('2)"; return rect; }}
class Ret<b {
public static %oid main(String args!" { Rectangle ob' # new Rectangle(@23"; Rectangle ob);
ob) # ob'.getRectangle<bject("; System .out.println(-ob'.length - ob'.length"; System .out.println(-ob'.breadth - ob'.breadth";
System .out.println(-ob).length - ob).length"; System .out.println(-ob).breadth - ob).breadth";
}}
Output of t,e Program :
ob'.length @ob'.breadth 3ob).length 'ob).breadth )
Explanation :
9. n t%e abo+e program we %a+e called a met%od getRectangleO'(ect and t%e met%odcreates ob#ect of class from w%ic% it %as been called.
2. !ll ob#ects are dynamically allocated using ne" you dont need to worry about an ob#ect
going out,of,scope because t%e met%od in w%ic% it was created terminates.
3. &%e ob#ect will continue to e$ist as long as t%ere is a reference to it somew%ere in your
program. %en t%ere are no references to it t%e ob#ect will be reclaimed t%e ne$t time
garbage collection ta/es place.
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 31/72
Java I!"# relationship
4ava 5 -n,eritance asics :7o 0erm !efinition
9 n%eritance-n,eritance is a process w%ere one ob#ect acAuires t%e properties ofanot%er ob#ect
2 'ubclass Class w%ic% in%erits t%e properties of anot%er ob#ect is called as su'class
3 'uperclass Class w%ose properties are in%erited by subclass is called as superclass
; Keywords Esed e$tends and implements
-SA Relations,ip "it, Example :',! is a way of saying = &%is ob#ect is a type of t%at ob#ect.
public class 6ehicle{}
public class ourEheeler extends 6ehicle{}
public class T$oEheeler extends 6ehicle{}
public class EagonR extends ourEheeler{}
Conclusions from a'ove Example :
*rom t%e abo+e e$ample we can say t%at –
9. :e%icle is t%e superclass of &wo%eeler class.2. :e%icle is t%e superclass of *our%eeler class.
3. &wo%eeler and *our%eeler are su' classes of :e%icle class.
;. agon? is t%e su'class of bot% *our%eeler and :e%icle classes.
-SA relations,ip of a'ove example is 5
T$oEheeler BS?+ 6ehicleourEheeler BS?+ 6ehicleEagonR BS?+ ourEheeler
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 32/72
Fence
EagonR BS?+ 6ehicle
Java instance$f keyword
Example : -SA Relations,ip /erification
class ourEheeler extends 6ehicle{}class T$oEheeler extends 6ehicle{}class EagonR extends ourEheeler{}
public class 6ehicle{
public static %oid main( String! args " {
ourEheeler %' # new ourEheeler("; T$oEheeler %) # new T$oEheeler("; EagonR %9 # new EagonR(";
System .out.println(%' instanceof 6ehicle"; System .out.println(%) instanceof 6ehicle"; System .out.println(%9 instanceof 6ehicle"; System .out.println(%9 instanceof ourEheeler";
}}
Output :
truetruetruetrue
-nstanceOf Operator :
n t%e abo+e e$ample we %a+e used t%is following statement –
System .out.println(%' instanceof 6ehicle";
t%e instanceof operator is used to c%ec/ w%et%er &wo%eeler is actually a :e%icle and
*our%eelet is actually a :e%icle.
-nvali$ ?se of -nstanceOf Operator :
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 33/72
System.out.println(%9 instanceof T$oEheeler";
Java extends keyword
Exten$s 8e#"or$ :
e can e$tend a class by using t%e exten$s 9e#"or$ in a class $eclaration after t%e class nameand before t%e parent class.
public class 0arent*lass {}
and we define c%ild class li/e s%own below –
public class *hild*lass extends 0arent*lass {}
0#pe 7ame Explanation
'uper
ClassarentClass &%e class from w%ic% anot%er class is deri+ed is called t%e superclass
'ub Class C%ildClass&%e deri+ed class t%e class t%at is deri+ed from anot%er class is called a
su'class
-mportant 7ote : Exten$s 8e#"or$
9. n t%e @a+a !ll t%e classes are c%ild classes of (ava.lang.O'(ect
2. "b#ect is t%e 'uper Class of all t%e classes in @a+a
3. Li/e CBB multiple in,eritance is not allowed in @a+a. Class can only e$tend one class.
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 34/72
Java %#!"# relationship & aggregation
Consider we are storing t%e information of t%e student t%en we may create a class li/e below –
*lass Student { int roll; String sname; +ddress address;
}
n t%e abo+e class we %a+e entity reference (!ddress) w%ic% stores again its own information
li/e streetcitystate>ip. li/e below –
*lass +ddress { String street; String state; String 4ip; String city;}
so we can say t%at Stu$ent @ASA A$$ress &%us if t%e class %as entity reference t%en entity willrepresent t%e F!',! relations%ip.
Consider t%e following e$ample –
A$$ress.(ava
public class +ddress {
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 35/72
String street; String city; String state; String 4ip;
public +ddress(String street2 String city2 String state2 String 4ip" {
this.street # street; this.city # city; this.state # state; this.4ip # 4ip; }}
Stu$ent.(ava
public class Student {
int roll;
+ddress address;
Student(int roll=o2+ddress addressDetail"{ roll # roll=o; address # addressDetail; }
%oid printStudentDetails(+ddress address'" { System .out.println(-Roll - roll"; System .out.println(-Street - address'.street"; System .out.println(-*ity - address'.city"; System .out.println(-State - address'.state"; System .out.println(-Fip - address'.4ip"; }
public static %oid main(String! args" { +ddress address'; address' # new +ddress(-'?ST-2-0=-2->ah-2-@'-"; Student s' # new Student('2address'"; s'.printStudentDetails(address'"; }}
Output :
Roll '
Street '?ST*ity 0=State >ahFip @'
Explanation : A$vantages of ?sing Aggregation
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 36/72
9. Hou can see t%e abo+e code in w%ic% we already %a+e t%e class (!ddress) w%ic% is used
to store t%e details of address. &%us using aggregation we %a+e reused t%e e$isting class.2. n%eritance can be ac%ie+ed only using t%e ',! relations%ip but using t%is F!',! we
can use e$isting code more efficiently.
Java protected access speci'er
Protecte$ Access Specifier
Consider t%e following e$ample –
package [email protected];
public class 0rotectedCample {
public %oid public>ethod("{ }
private %oid pri%ate>ethod("{ }
protected %oid protected>ethod("{ }
public static %oid main(String! args" { *hild*lass c' # new *hild*lass("; c'.test>ethods(";
}}
class *hild*lass extends 0rotectedCample {
public %oid test>ethods(" { public>ethod("; protected>ethod("; pri%ate>ethod("; //Crror }}
Output :*ompile Time Crror
Explanation :
9. *rom subclass we cannot access t%e pri+ate members of t%e superclass.
2. subclass you can access its superclasss public and protected met%ods and fields
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 37/72
3. f t%e subclass and t%e superclass are in t%e same pac/age you can also access t%e
superclasss default met%ods and fields
Java method overriding
Rules for *et,o$ Overri$ing :
9. <et%od <ust %a+e 'ame ame as t%at of <et%od 1eclared in arent Class
2. <et%od <ust %a+e 'ame arameter List as t%at of <et%od 1eclared in arent Class
3. ',! relation s%ould be maintained in order to "+erride <et%od.
2,# "e nee$ to overri$e met,o$
Consider t%e following arent Class –
class Guman { void talA(" { System.out.println(-TalAing Guman-"; }}
Conside following c%ild class –
class >ale etends Guman { public static void main(String args!" {
>ale m' # ne$ >ale("; m'.talA(";}
}
e want to pro+ide t%e different implementation to tal/ met%od for <ale and Fuman class.
Esing o+erride we can pro+ide different implementations for tal/ in arent Class and in C%ild
Class.
*et,o$ Overri$ing Example :
/e,icle.(ava
package [email protected];
public class 6ehicle {
public %oid %ehicle>ethod(" { System .out.println(->ethod in 6ehicle.-";
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 38/72
}}
0"o2,eeler.(ava
package [email protected];
public class T$oEheeler extends 6ehicle {
public %oid %ehicle>ethod(" { System .out.println(->ethod- - in T$oEheeler.-"; }
public static %oid main(String! args" { T$oEheeler my:iAe # new T$oEheeler("; 6ehicle my6ehicle # new 6ehicle(";
my6ehicle.%ehicle>ethod("; my:iAe.%ehicle>ethod(";
}}
Output of t,e Program :
>ethod in 6ehicle.>ethod in T$oEheeler.
Java method overriding rules
1. Same Argument List :
&%e argument list s%ould be e$actly t%e same as t%at of t%e o+erridden met%od.
pacAage [email protected];
public class BnheritanceRules {
public int calculate(int num'2int num)" {
return num'num); }
public static void main(String! args" { base*lass b' # ne$ base*lass("; int result # b'.calculate('2 '"; System.out.println(-Result - result"; }}
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 39/72
class base*lass etends BnheritanceRules {
public int calculate(int num'2int num)" { return num',num); }}
n t%e abo+e e$ample met%od is %a+ing t%e same set of parameter list –
public int calculate(int num'2int num)"
). 0,e return t#pe :
?eturn type s%ould be t%e same or a subtype of t%e return type declared in t%e "riginal
"+erridden met%od in t%e arent Class.
Consider t%e following met%od from arent Class –
public int calculate(int num'2int num)" { return num'num);}
t%en we cannot c%ange t%e return type of t%e met%od in t%e o+erriden met%od.
. *o$ification of access level :
!ccess le+el cannot be lowerd down or restricted t%an t%e o+erridden met%ods access le+el.
'uppose currently met%od in t%e arent class is %a+ing t%e access le+el public t%en we cannoto+erride t%e met%od wit% access le+el as pri+ate and protected.
below is t%e table w%ic% summari>ed t%e w%ic% are t%e allowed ways of modifing t%e access
le+el of o+erriden met%od –
Access Level in Parent Access Level in C,il$ Allo"e$
ublic ublic !llowed
ublic ri+ate ot !llowed
ublic rotected ot !llowed
rotected ublic !llowed
rotected rotected !llowed
rotected ri+ate ot !llowed
*ollowing met%od will t,ro" compile time error – pacAage [email protected];
public class BnheritanceRules {
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 40/72
public int calculate(int num'2int num)" { return num'num); }
public static void main(String! args" { base*lass b' # ne$ base*lass("; int result # b'.calculate('2 '"; System.out.println(-Result - result"; }}
class base*lass etends BnheritanceRules {
pri%ate int calculate(int num'2int num)" { return num',num); }}
because in t%e parent class <et%od %as !ccess le+el public w%ile we %a+e made access le+el as
pri+ate in t%e c%ild class.
F. Cannot Overri$e +inal *et,o$s :
e cannot o+erride t%e final met%od declared in t%e arent Class5'uper Class. Consider t%e
following met%od is written inside t%e arent Class –
final public int calculate(int num'2int num)" { return num'num);}
G. Cannot Overri$e Static *et,o$s 'ut Re$eclaration is
possi'le :
Consider t%e following met%od declared inside t%e arent Class –
public static int calculate(int num'2int num)" { return num'num);}
t%en c%ild class cannot o+erride static met%od from parent class but it can redeclare it #ust by
c%anging t%e met%od body li/e t%is –
public static int calculate(int num'2int num)" { return num',num);}
%owe+er we %a+e to /eep t%e met%od static in t%e c%ild class we cannot ma/e it non,static in t%e
c%ild class 'o following met%od declaration inside c,il$ class "ill t,ro" error –
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 41/72
public int calculate(int num'2int num)" { //$ithout static return num',num);}
H. Rule for *et,o$s t,at Cannot 'e -n,erite$ :
f a met%od cannot be in%erited t%en it cannot be o+erridden by t%e c%ild class. e cannot
in%erite t%e pri+ate met%ods of t%e parent class in t%e c%ild class. 'o pri+ate met%ods cannot be
o+erriden by t%e c%ilde class. Fowe+er redeclaration of pri+ate met%od is possible in t%e c%ildmet%od –
public class BnheritanceRules {
pri%ate int calculate(int num'2int num)" { return num'num); }}
class base*lass etends BnheritanceRules {
pri%ate int calculate(int num'2int num)" { return num',num); } }
Java super keyword
"a#s of ?sing Super 8e#"or$ :Super is use$ to refer t,e imme$iate parent of t,e class. %ene+er we create an ob#ect of t%e
c%ild class t%en t%e reference to t%e parent class will be created automatically.
e can user super /eyword by using t%ree ways –
• !ccessing nstance :ariable of arent Class
• !ccessing arent Class <et%od
• !ccessing arent Class Class Constructor
2a# 1 : Accessing -nstance /aria'le of Parent Class using
Super
pacAage [email protected];
public class 0arent*lass { int age*lass # ';
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 42/72
public static void main(String! args" { *hild*lass c' # ne$ *hild*lass("; c'.display(";
}}
class *hild*lass etends 0arent*lass{ int age*lass # );
public void display(" {System.out.println(-age*lass - age*lass";
}}
Output of t,e Program
age*lass )
Consider t%e abo+e e$ample –
9. e %a+e same +ariable declared inside t%e parent class as well as in c%ild class.2. %ene+er we try to access t%e +ariable using t%e ob#ect of c%ild class al"a#s instance
varia'le of c,il$ "ill 'e returne$.
'uppose we want to access t%e t%e same +ariable from t%e parent class t%en we can modify t%edisplay met%od as below –
public void display(" { System.out.println(-age*lass - super.age*lass";}
2a# ) : Accessing Parent Class *et,o$ using Super
pacAage [email protected];
public class 0arent*lass { int age*lass # ';
public int get6alue(" { return ); }
public static void main(String! args" {
*hild*lass c' # ne$ *hild*lass("; c'.display(";
}}
class *hild*lass etends 0arent*lass{ int age*lass # );
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 43/72
public int get6alue(" { return 3; }
public void display(" { System.out.println(-result - super.get6alue(""; }}
Output :
result )
n t%is e$ample we %a+e same met%od declared inside parent and c%ild class.
public void display(" { System.out.println(-result - super.get6alue("";}
n order to e$ecute t%e parent met%od from t%e c%ild class we need to use super /eyword.
2a# : Accessing Parent Class Constructor using Super
e will be learning super /eyword and constructor in more details in t%e ne$t c%apter .
Java super keyword ( constructors
?n$erstan$ing Constructors :
pacAage [email protected];
public class 0arent*lass {
public 0arent*lass(" { System.out.println(-Gello 0arent-"; }
public static void main(String! args" {*hild*lass c' # ne$ *hild*lass(";
}}
class *hild*lass etends 0arent*lass{
public *hild*lass(" {
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 44/72
System.out.println(-Gello *hild-"; }}
Output of t,e Program :
Gello 0arentGello *hild
Explanation of a'ove program :
%en you create an instance of a c%ild class @a+a automatically calls t%e default constructor of
t%e parent class before it e$ecutes t%e c%ild classs constructor. [ !lso 'ee – Constructor 4$ample
]
Consider t%e following code –
pacAage [email protected];
public class 0arent*lass {
public 0arent*lass(" { System.out.println(-Gello 0arent-"; }
public 0arent*lass(int %al" { System.out.println(-Gello 0arameter-"; }
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 45/72
public static void main(String! args" { *hild*lass c' # ne$ *hild*lass("; }}
class *hild*lass etends 0arent*lass{
public *hild*lass(" { super(3"; System.out.println(-Gello *hild-"; }}
ow n t%e abo+e program we %a+e written two constructors one wit% no argument and anot%er
wit% single integer argument.
public 0arent*lass("
{ System.out.println(-Gello 0arent-";}
public 0arent*lass(int %al"{ System.out.println(-Gello 0arameter-";}
!s we %a+e e$plicitly called t%e single argument constructor using t%e super /eyword Parent
Classs Parameteri6e$ Constructor gets calle$.
0ip I1 : Super *ust 'e +irst Statementf you use super to call t%e parent class constructor you must put it as first statement in t%e
constructor.
*ollowing is t%e +alid way of calling parent class constructor –
public *hild*lass("{ super(3"; System.out.println(-Gello *hild-";}
f we write it after ot%er statements t%en it will t%row compile time error –
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 46/72
0ip I) : !efault constructor
f you dont e$plicitly call super t%e compiler inserts a call to t%e default constructor of t%e base
class. n t%at case t%e base class must %a+e a default constructor.
f t%e base class doesnt %a+e a default constructor you will get compile time error.
Java 'nal keyword
2a# 1 : +inal /aria'le
f we ma/e t%e +ariable final t%en t%e +alue of t%at +ariable cannot be c%anged once assigned.
Consider t%e following e$ample –
pacAage [email protected];
public class Shape*lass {
final int SG+0C8SBDCS # 9;
void setShape(" { SG+0C8SBDCS # @;
}
public static void main(String! args" { Shape*lass c' # ne$ Shape*lass("; c'.setShape(";
}}
Output :
*ompile Time Crror
e cannot modify t%e +alue of t%e final +ariable we will get following error message –
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 47/72
2a# ) : +inal *et,o$
e cannot "+erride t%e final met%od as we cannot c%ange t%e met%od once t%ey are declared
final. Consider t%e following e$ample –
pacAage [email protected];
public class Shape*lass { int SG+0C8SBDCS # 9;
final void setShape(" { SG+0C8SBDCS # @;
}
public static void main(String! args" { Shape*lass c' # ne$ Shape*lass("; c'.setShape("; }}
class *ircle etends Shape*lass {
void setShape(" { // Crror Gere SG+0C8SBDCS # @;
}}
Output :
*ompile Time Crror
n t%is e$ample we %a+e declared met%od as final so we cannot o+erride t%e final met%od
ot%erwise we will get compile time error –
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 48/72
2a# : +inal Class
e cannot in%erit t%e final class.
pacAage [email protected];
public final class Shape*lass { int SG+0C8SBDCS # 9;
final void setShape(" { SG+0C8SBDCS # @;
} public static void main(String! args" {
Shape*lass c' # ne$ Shape*lass("; c'.setShape("; }}
class *ircle etends Shape*lass { // Crror Gere
}
Output :
*ompile Time Crror
n t%is e$ample we %a+e declared class as final so we cannot in%erit t%e final class
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 49/72
Some -mportant Points : +inal 8e#"or$
9. *inal Keyword can be applied only on <et%odClass and :ariable
+inal Entit# !escription
*inal :alue *inal :alue cannot be modified
*inal <et%od *inal <et%od cannot be o+erriden
*inal Class *inal Class cannot be in%erited
2. *inal :ariable must be initiali>ed at t%e time of declaration or inside constructor
3. ?e,!ssigning :alue is not allowed for final member +ariable
;. Local *inal :ariable s%ould be initiali>ed during t%e time of declaration
'. *inal and *inally bot% are different. *inally /eyword is used on 4$ception %andling in
@a+a
Java type casting ) Inheritance
!ifferent +orms of 0#pe Casting :
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 50/72
&%ere are two types of type casting.
Live Example of 0#pe Casting in -n,eritance :
package [email protected];
class 6ehicle {
String name<f6ehicle;}
class T$oEheeler extends 6ehicle {String %ehicle>odel;
}
public class Type*astCample {
public static %oid main(String! args" { 6ehicle %' # new 6ehicle("; 6ehicle %) # new T$oEheeler("; T$oEheeler %9 # (T$oEheeler" new 6ehicle("; T$oEheeler %@ # new T$oEheeler(";
}}
A. ?p Casting :
Hou can cast an instance of a c%ild class to its parent class. Casting an ob#ect of c%ild class to a
parent class is called upcasting.
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 51/72
Consider t%e following e$ample !ssuming t%at &wo%eeler is a subclass of :e%icle.
6ehicle %) # ne$ T$oEheeler(";
. !o"n Casting :
Casting an ob#ect of a parent class to its c%ild class is called $o"ncasting.
Consider t%e following e$ample !ssuming t%at &wo%eeler is a subclass of :e%icle. *ollowing
is an e$ample of t%e down casting –
T$oEheeler %9 # (T$oEheeler" ne$ 6ehicle(";
Java string handling
A. String Literals in 4ava :
n 'imple words we can say t%at 'tring Literal is 'eAuence of c%aracters written in doubleAuotes.
class irst0rogram { public static %oid main(String! args" { System .out.println(-Gello Eorld-"; }}
n t%e abo+e e$ample we can say t%at 'tring – (Fello orld) written inside ('ystem.out.println)
will be called as 'tring Literal.
. String Literals is use$ to Create an$ -nitiali6e String
O'(ect :
e /now t%at in @a+a rogramming 'tring is considered as "b#ect not an array li/e C5CBB.
class irst0rogram { public static %oid main(String! args" {
String name # -0ritesh-; System .out.println(-Gello - name -H-" }}
Output of t,e Program :
Gello 0ritesh H
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 52/72
Lets 'ee %ow 'tring Literal or/s.
C. 2or9ing of String Literals :
@:< always maintains a 'tring Constant ool. f we declared a 'tring and initiali>ed it wit%
'tring literal t%en 'tring will be searc%ed in 'tring Constant ool.
class irst0rogram { public static %oid main(String! args" { String Str'; String Str) # -Gello-; }}
Consider abo+e program we can see 'tring (Fello) will be created inside ('tring Constant
ool) and t%en reference to t%at 'tring is being assigned to a 'tring "b#ect ('tr2M.
Consider t%e below program –
class irst0rogram { public static %oid main(String! args" { String Str' # -Gello-; String Str) # -Gello-; }}
n t%is program "nly 'ingle "b#ect will be created inside Constant ool and reference to t%at'tring will be returned to bot% "b#ects 'tr9 and 'tr2.
!. ?nico$e C,aracters in Literals
n order to print 'ymbol we can use following 'ynta$ –
class irst0rogram { public static %oid main(String! args" {
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 53/72
String Str' # -u9*-; System .out.println(Str'"; }}
'imilarly we can print multiple unicode c%aracters in @a+a.
Java creating string object
n @a+a we can create 'tring in two ways – "ne by using String Literals and anot%er using ne"
operator.
2a# 1 : Creating String O'(ects using Literals
Consider t%e following Code 'tatement –
class irst0rogram { public static %oid main(String! args" {
String my=ame # -0R+SG+=-; System .out.println(-Gello - my=ame";
my=ame # -0R+:GI-; System .out.println(-Gello - my=ame"; }}
Explanation :
String my=ame # -0R+SG+=-;
&%e abo+e 'tatement will be pictorially represented below –
ow w%en we assign anot%er string literal to 'tring "b#ect t%en earlier string will be discarded.
my=ame # -0R+:GI-;
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 54/72
!ctual 'tring can be stored anyw%ere in t%e %eap but 'tring "b#ect – (m#7ame) will locate t%e position of t%e 'tring – (PRA@?) and stores t%e reference to t%at actual string.
2a# ) : ?sing ne" Operator
String name # ne$ String(-+J+SG-";
Consider t%e abo+e code line –
Entit# O'(ect/aria'le *emor# Location!K!'F "b#ect 'tring Constant ool
new 'tringN!K!'FN "b#ect on Feap <emory
myame ?eference :ariable ,
O?eference :ariable is ointing to a 'tring "b#ect – ne" String3%A8AS@&=
: -mmuta'le String
2,at is -mmuta'le O'(ects
%en you %a+e a reference to an instance of an ob#ect t%e contents of t%at instance cannot be
altered
Consider t%e following e$ample – class BmmutableString {
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 55/72
public static %oid main(String! args" {
String myString # new String(-B am li%ing in Bndia-";System .out.println( myString ";
myString.replace+ll( -Bndia- 2 -IS+- ";System .out.println( myString ";
}}
Output of Program :
B am li%ing in BndiaB am li%ing in Bndia
Explanation : -mmuta'le String O'(ects
n t%e abo+e e$ample we can see t%at
myString.replace+ll( -Bndia- 2 -IS+- ";
it will create anot%er string i.e –
B am li%ing in IS+
t%oug% ob#ect is created for (- am living in ?SA) string but reference +ariable (my'tring) is
still not referring to new string. e need to specify t%e reference e$plicitly using followingassignment –
myString # myString.replace+ll( -Bndia- 2 -IS+- ";
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 56/72
class BmmutableString { public static %oid main(String! args" {
String myString # new String(-B am li%ing in Bndia-"; System .out.println( myString ";
myString # myString.replace+ll( -Bndia- 2 -IS+- "; System .out.println( myString ";
}}
and output will be li/e t%is –
B am li%ing in BndiaB am li%ing in IS+
Java concatenate strings
4oining t"o Strings [Concatenate Strings] in 4ava :
Consider t%e following e$ample –
public class *oncatenateString { public static void main(String! args" { String Str' # -B lo%e-;
String Str) # -my country-; String Str9 # -Bndia-;
String myString; myString # Str' Str) Str9;
System.out.println(-*omplete Statement - myString";
myString # Str9 ' '; System.out.println(-*omplete Statement - myString";
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 57/72
myString # ' ' Str9; System.out.println(-*omplete Statement - myString"; }}
Output :
*omplete Statement B lo%e my country Bndia*omplete Statement Bndia''*omplete Statement )Bndia
Explanation of t,e Program :
n @a+a rogramming w%en two strings will be combined toget%er t%en it will create anot%er
ob#ect of string. Ielow are some t%umb rules w%ile adding or combining two strings.
Operan$ 1 Operan$ ) Result of Concatenationnteger 'tring 'tring
'tring 'tring 'tring
nteger nteger nteger
9. PB operator %as associti+ity from left to rig%t.2. 4ac% time B operator will c%ec/ t%e type of operands and t%en decide w%ic% operation to
perform.
3. f any of t%e operand is of type 'tring t%en anot%er type will con+erted to 'tring using
respecti+e wrapper classes.
+irst Concatenation :
myString # Str' Str) Str9; # -B lo%e - -my country - -Bndia- # -B lo%e my country - -Bndia- # -B lo%e my country Bndia-
Secon$ Concatenation :
myString # Str9 ' ';
# -Bndia- ' ' # -Bndia'- ' # -Bndia''-
0,ir$ Concatenation :
myString # ' ' Str9; # ' ' -Bndia- # ) -Bndia-
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 58/72
# -)Bndia-
Java comparing strings
n t%e last topic we %a+e learnt Concatenating 'trings in @a+a. n t%is c%apter we are loo/ing
anot%er 'tring operation in @a+a rogramming i.e Comparing two 'trings. &%ere are t%ree ways
for comparing t%e two strings.
7o Comparing Strings
ay 9 Esing eAuals met%od
ay 2 Esing QQ "perator
ay 3 Esing compare&o met%od
2a# 1 5 4ava Comparing Strings ?sing : e>ual3= met,o$
'tring Class pro+ides us two different met%ods for comparison i.e –
public boolean eKuals(<bject another"{}public boolean eKualsBgnore*ase(String Str)"{}
f we need to compare t%e content only t%en we can use 9st met%od specified abo+e and if we
need to compare t%e strings and cases bot% t%en we can use 2nd met%od. Ielow are t%e e$amples
for using bot% t%e met%ods –
class *omparingString{ public static void main(String args!"{
String str'#[email protected]; String str)#[email protected]; String str9#-*@7C+R=.com-;
System.out.println(str'.eKuals(str)"";//true System.out.println(str'.eKuals(str9"";//false System.out.println(str).eKualsBgnore*ase(str9"";//true }}
Output :
truefalsetrue
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 59/72
2a# ) 5 4ava Comparing Strings : Reference Comparison
3=
class *omparingString{ public static void main(String args!"{
String str' # [email protected];
String str) # [email protected]; String str9 # ne$ String([email protected]";
System.out.println(str' ## str)";//true System.out.println(str' ## str9";//false }}
Consider t%e abo+e e$ample – n t%e below statement
System.out.println(str' ## str)";
str9 and str2 bot% are referring t%e same ob#ect. %ic% ma/es str9 and str2 eAual. %ile in case
of 2nd line –
System.out.println(str' ## str9";
&%oug% content of str9 and str3 is same instance of str3 is not same as t%at of str9. str3 refers to
t%e instance t%at is created in t%e non,pool 5 %eap.
2a# 5 compare0o3= met,o$compare&o met%od returns t%e integer w%ic% tells us t%e comparison status – ?esult of Comparison?eturn :alue
str9 Q str20
str9 - str29str9 R str2,9 [5table] Consider t%e following code snippet ,
class *omparingString{ public static void main(String args!"{
String str' # [email protected];
String str) # [email protected]; String str9 # Lgoogle.comL;
System.out.println(str'.compareTo(str)"";// System.out.println(str'.compareTo(str9"";//' System.out.println(str9.compareTo(str'"";//?' }}
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 60/72
Output :
'?'
Java substring
n t%e last topic we %a+e learnt about comparison of two strings and different ways of comparing
strings. n t%is topic we are going to see finding out t%e substring in @a+a.
4ava Su'string : *et,o$ 1
n order to get substring from t%e gi+en string we %a+e following two met%ods pro+ided by
'tring Class of @a+a.
public String substring(int startBnde";
&%is met%od returns new 'tring ob#ect containing t%e substring of t%e gi+en string from specified
startnde$.
class SubString{ public static void main(String args!"{
String str' # [email protected]; String str) # [email protected];
System.out.println(str'.substring(""; System.out.println(str'.substring(M""; System.out.println(str'.substring()""; }}
Output :
4ava Su'string : *et,o$ )
public String substring(int startBnde2int endBnde";
&%is met%od returns new 'tring ob#ect containing t%e substring of t%e gi+en string from specifiedstartnde$ to endnde$.
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 61/72
class SubString{ public static void main(String args!"{
String str' # [email protected];
System.out.println(str'.substring(2)""; System.out.println(str'.substring(92N""; System.out.println(str'.substring()2M""; }}
Output :
c@earlearn.
Explanation :
Consider statement –
str'.substring(2)"
t will include all t%e c%aracters from 0 to 2 e$cluding t%e endnde$. i.e 09 will be included
only and 2 will be e$cluded
Java *xception %andling
Exception @an$ling in 4ava Programming :
9. !n e$ception is an e+ent.2. 4$ception occurs during t%e e$ecution of a program w%en normal flow of t%e program is
nterrupted or disturbed.
3. 4$ception Fandling is mac%anism to %andle t%e e$ceptions.
@o" Exception @an$ling 2or9s in 4ava
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 62/72
9. %en any error occures in a met%od t%en new ob#ect i.e 4$ception "b#ect is created by
a met%od
2. 4$ception "b#ect contain information about error suc% as type of error and state of t%e program.
3. ewly created e$ception ob#ect is passed to t%e ?untime 'ystem.
;. ?untime system will %andle t%e e$ception to /eep system stable
A$vantages of Exception @an$ling :
n t%e pre+ious programming languages w%ene+er any illegal condition is e$ecuted t%en program flow gets disturbed. n #a+a programming e$ception %andling ensures t%at program
s%ould run smoot%er. Consider t%e following e$ample –
public class CceptionCample { public static %oid main(String! args" {
int num' # 3; int num) # ; int ans;
ans # num' / num); System .out.println(-Result of Di%ision - ans"; }}
n t%is e$ample we /now t%at any number di+ided by 0 will cause program to go into
une$pected situation. f program contain suc% une$pected statements t%en its better to %andle
t%ese une$pected results. Ielow is t%e une$pected error output –
Cception in thread -main- ja%a.lang.+rithmeticCception / by 4ero at Di%ide:yFero=oCceptionGandling.main( Di%ide:yFero=oCceptionGandling.ja%aO"
ow we %a+e done slig%t modification in t%e program by pro+iding e$ception %andling code in
t%e program –
public class CceptionCample { public static %oid main(String! args" { int num' # 3; int num) # ; int ans;
try { ans # num' / num);
System .out.println(-Result of Di%ision - ans";} catch( ArithmeticException e" { System .out.println(-Di%ide by Fero Crror-";}
}}
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 63/72
so t%e output of t%e abo+e code will be –
Di%ide by Fero Crror
Java *xception %ierarchy
0#pes of Exceptions in 4ava :
@a+a 4$ceptions are di+ided into 3 types – C%ec/ed 4$ceptionsEnc%ec/ed 4$ceptions and
4rrors.
n @a+a t%ere are multiple situations t%at can cause e$ception. &%ese situations are di+ided into ;different types –
Situation Cause of Exception
Code 4rror
4$ceptions occurred due to wrong or in+alid data. f user try to
access t%e array element greater t%an si>e or somet%ing di+ided by
>ero error t%en t%ese e$ceptions are called as code errors or dataerrors.
'tandard <et%od 4$ception4$ceptions may be t%rown if we try to access t%e standard
met%ods wit% in+alid input parameter.
"wn 4$ceptionEser may generate %is5%er own e$ceptions depending on situationand type of code.
@a+a 4rrors 4rrors occurred due to @:<
below are t%e different types of 4$ception in @a+a –
A. C,ec9e$ exceptions :
9. ! c%ec/ed e$ception is an e$ception w%ic% is error or a problem occurred because ofcode written by programmer
2. C%ec/ed 4$ception cannot be neglected by t%e programmer.
3. 'uppose we are opening t%e file and file is not present t%en e$ception occurred during t%e
compile time can be considered as c%ec/ed e$ception.
;. &%ese e$ceptions cannot 'e ignore$ at t,e time of compilation.
D. Class t%at e$tend t%rowable class e$cept ?untime4$ception and 4rror is considered asC%ec/ed e$ception.
. Runtime exceptions:
9. Classes t%at e$tent ?untime4$ception class is called as ?untime 4$ception.
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 64/72
2. ?untime e$ceptions are ignored at t%e time of compliation.
C. Errors :
9. &%ese are not e$ceptions but t%e problems t%at are beyond t%e control of t%e user or t%e
programmer.2. *or e$ample 'tac/ o+erflow :irtual <ac%ine <emory!ssertion4rror
Java +ry"Catch lock
0r# Catc, loc9 :
e need to put code inside try bloc/ t%at mig%t t%row an e$ception. &ry bloc/ must be wit%in a
met%od of a #a+a class.
try { //Statement ';
//Statement ); //Statement 9; }catch(Cception e" { //Cception Gandling *ode }
abo+e is t%e synta$ of try catc% bloc/ in #a+a. f an e$ception occurred during t%e e$ecution of
'tatement 9..3 t%en it will call e$ception %andling code.
0ips for 0r#Catc, loc9 :
9. &%e code wit%in try bloc/ may or may not raise an e$ception. f &ry bloc/ does not t%rowany e$ception t%en catc% bloc/ gets e$ecuted.
2. &%e catc% bloc/ contains an e$ception %andler and some statements used to o+ercome
t%at e$ception
3. 4ac% and e+ery &ry Iloc/ must %a+e catc% or finally statement associated wit% it.
0r# loc9 Present Catc, loc9 Present +inall# loc9 Present Legal Statement
resent resent , Legal5Complete &ry Iloc/
resent , resent Legal5Complete &ry Iloc/
resent , , llegal5ncomplete &ry Iloc/
Explanation "it, Example :
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 65/72
public class CceptionCample { public static %oid main(String! args" { int number' # 3; int number) # ; int result; try {
result # number' / number); System .out.println(-Result of Di%ision - ans";} catch( ArithmeticException e" { System .out.println(-Di%ide by Fero Crror-";}
}}
Consider t%e abo+e e$ample – e /now t%at di+ision of any number wit% >ero is not possible.f
we attempt to di+ide any number by >ero in #a+a t%en it may cause an error.
result # number' / number);
abo+e statement may cause an e$ception so we need to put t%at code inside try bloc/. %ene+eran e$ception occures t%e catc% bloc/ gets e$ecuted.
} catch(+rithmeticCception e" { System .out.println(-Di%ide by Fero Crror-";}
nside catc% we %a+e simply displayed an error message i.e %!ivi$e '# Jero Error&.
Exception t,ro"n an$ 0#pe of Exception O'(ect :
4$ception t%rown by try bloc/ is of type !rit%metic 4$ception so it can be catc%ed inside t%ecatc% bloc/ because we %a+e pro+ided t%e %andler of same type.
try { result # number' / number);
System .out.println(-Result of Di%ision - ans";}catch(ile=otoundCception e" { System .out.println(-Di%ide by Fero Crror-";}
f we e$ecute t%e abo+e code instead t%en t%rown e$ception is of type Arit,metic Exception
and 4$ception &ype pro+ided into Catc% bloc/ is of type +ile7ot+oun$Exception t%en
e$ception may not be catc%ed. &%us abo+e code can cause compile time error.
try { result # number' / number);
System .out.println(-Result of Di%ision - ans";}catch(Cception e" { System .out.println(-Di%ide by Fero Crror-";}
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 66/72
n t%e abo+e code we can catc% all types of e$ception because 4$ception is superclass of all t%e
e$ceptions. [?efer t%e 4$ception Fierarc%y]
Java -ultiple Catch locks
*ultiple Catc, loc9s : Catc,ing *ultiple Exceptions
public class CceptionCample {
public static %oid main(String arg%!" {
int num' # '; int num) # ; int result # ; int arr! # new int3!;
try { arr! # ; arr'! # '; arr)! # ); arr9! # 9; arr@! # @; arr3! # 3;
result # num' / num); System .out.println(-Result of Di%ision - result";
}catch ( ArithmeticException e" { System .out.println(-Crr Di%ided by Fero-";
}catch ( ArrayIndexOutOfBoundsException e" { System .out.println(-Crr +rray <ut of :ound-";
}
}}
Output :
Crr +rray <ut of :ound
n t%e abo+e e$ample we %a+e two lines t%at mig%t t%row an e$ception i.e
arr3! # 3;
abo+e statement can cause array inde$ out of bound e$ception and
result # num' / num);
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 67/72
t%is can cause arit%metic e$ception. &o Fandle t%ese two different types of e$ception we %a+e
included two catc% bloc/s for single try bloc/.
}catch (+rithmeticCception e" { System .out.println(-Crr Di%ided by Fero-";
}catch (+rrayBnde<ut<f:oundsCception e" { System .out.println(-Crr +rray <ut of :ound-";
}
ow nside t%e try bloc/ w%en e$ception is t%rown t%en type of t%e e$ception t%rown iscompared wit% t%e type of e$ception of eac% catc% bloc/.
f type of e$ception t%rown is matc%ed wit% t%e type of e$ception from catc% t%en it will e$ecute
corresponding catc% bloc/.
7otes :
9. !t a time only single catc, 'loc9 can 'e execute$. !fter t%e e$ecution of catc% bloc/control goes to t%e statement ne$t to t%e try bloc/.
2. !t a time "nly single e$ception can be %andled.
3. !ll t%e e$ceptions or catc% bloc/s must be arranged in order. [?efer t%e 4$ception
Fierarc%y]
Catc, loc9 must 'e arrange$ from *ost Specific to *ost
Deneral :
f we wrote catc% bloc/ li/e t%is –
}catch (Cception e" { System .out.println(-Crr Cception <ccurred-";
}catch (+rrayBnde<ut<f:oundsCception e" { System .out.println(-Crr +rray <ut of :ound-";
}
9. !ll t%e e$ceptions will be catc%ed in t%e *irst Catc% bloc/ because Exception is
superclass of all t%e e$ceptions.2. n t%e abo+e program Arra#-n$exOutOfoun$sException is an subclass of Exception
Class.
riting abo+e code will t%row following error message after compiling it –
Enreac%able catc% bloc/ for !rraynde$"ut"fIounds4$ception.t is already %andled by t%ecatc% bloc/ for 4$ception
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 68/72
Java Catching -ultiple *xception
Catc,ing *ultiple Exception in single catc, :
%ene+er try bloc/ will t%rown any e$ception of t%ese type t%en and t%en only we can %andle
t%e e$ception.
catch (B<Cception e" { System .out.println(-B< Cception-"; throw e;} catch (SP7Cception e" { System .out.println(-SP7 Cception-"; throw e;}
9. f in a try bloc/ we need to %andle multiple e$ceptions t%en we need to write e$ception%andler for eac% type of e$ception.
2. e can combine t%e multiple exceptions in catc, 'loc9 using Pipe 3K= Operator .
catch (B<CceptionQSP7Cception e" { System .out.println(-Cception thro$n-"; throw e;}
abo+e single catc% bloc/ can %andle " as well as 'SL e$ceptions. 'o it is better to use ipe"perator to %andle multiple e$ceptions instead of writing indi+idual catc% bloc/ for eac%
e$ception. !lso ?efer t%is oracle guide for more information.
Parameter Accepte$ '# Catc, loc9 is +inal :
9. f a catc% bloc/ %andles more t%an one e$ception type t%en t%e catc% parameter isimplicitly final.
2. n t%is e$ample t%e catc% parameter e$ is final.
3. e cannot assign any +alues to it wit%in t%e catc% bloc/.
7ote :e can use ipe T to catc% multiple e$ceptions only in @a+a '4 U or in %ig%er +ersions.
Java .ested +ry lock
ometimes situation occurred w%ere we need to catc% multiple conditions. n t%e pre+ious tutorial
we %a+e learnt about t%e catc%ing multiple e$ception using only one catc% bloc/ . n t%is c%apterwe will be learning nested try bloc/. Consider t%e following snippet –
public class CceptionCample {
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 69/72
public static void main(String arg%!" {
int result # ; int arr! # ne$ int3!;
arr3! # 3;
result # ' / ; System.out.println(-Result of Di%ision - result";
}}
n t%e abo+e e$ample of nested try bloc/ we can see t%at
arr3! # 3;result # ' / ;
bot% t%ese lines will generate e$ception.f we put bot% t%ese codes in same try bloc/ t%en it willgenerate one e$ception and t%e ne$t code wont be e$ecuted.
public class CceptionCample {
public static void main(String arg%!" {
int num' # '; int num) # ; int result # ; int arr! # ne$ int3!;
try {
try { arr3! # 3;}catch (+rrayBnde<ut<f:oundsCception e" {System.out.println(-Crr +rray <ut of :ound-";}
try { result # num' / num);}catch (+rithmeticCception e" { System.out.println(-Crr Di%ided by Fero-";}System.out.println(-Result of Di%ision - result";
}catch (Cception e" { System.out.println(-Cception <ccured H-"; }
}}
n t%e abo+e nested try bloc/ code eac% and e+ery e$ception is %andled. n order to %andle eac%
e$ception we need to use try bloc/.
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 70/72
Java /inally block
+inall# 'loc9 : Exception @an$ling in 4ava
9. *inally Iloc/ in always e$ecuted irrespective of exception is ,an$le$ or not
2. *inally is not a function t is 9e#"or$ in #a+a
3. *inally performs t%e functions suc% as closing t%e stream or file and closing connections.
;. *inally always gets execute$ 'efore terminating t,e program by @:<.
D. *inally s%ould be after try and catc% and is optional
6. 4ac% try bloc/ %as minimum 0 and ma$imum 9 finally bloc/.
+lo"c,art for +inall# Statement 5
+inall# 'loc9 : S#ntax
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 71/72
try {??????????????} catch(Cception e" {??????????????}finally {
}
0ip 1 : +inall# 'loc9 is optional
n t%e program we can %a+e minimum >ero and ma$imum one finally statement.
public class >yCceptionCample { public static void main(String! a"{
try{ int i # '/; } catch(Cception e"{ System.out.println(-Bnside 'st catch :locA-"; }
try{ int i # '/'; } catch(Cception e"{ System.out.println(-Bnside )nd catch :locA-"; } finally { System.out.println(-Bnside )nd finally blocA-"; }
}}
n t%e 9st try statement bloc/ we can see t%at we dont %a+e finally bloc/ but in t%e 2nd try bloc/
we %a+e finally bloc/. 'o finally bloc/ is always optional.
finally { System.out.println(-Bnside )nd finally blocA-";}
2nd try bloc/ does not t%row any e$ception but still after t%e e$ecution of try bloc/ code
e$ecutes finally statement bloc/
Output :
Bnside 'st catch :locABnside )nd finally blocA
0ip ) : +inall# 'loc9 is not execute$ in 'elo" t"o cases
7/23/2019 Live Example.doc
http://slidepdf.com/reader/full/live-exampledoc 72/72
9. f following statement is included in t%e try bloc/ &erminating code using system e$it
System.eit(";
2. f t%e t%read e$ecuting t%e try or catc% code is interrupted or /illed t%e finally statement
bloc/ may not e$ecute [*or more info]
Java +hrow !tatement
t,ro" 8e#"or$ :
9. &%e t%row /eyword is used to e$plictily t%row an e$ception.
2. e can t%row eit%er c%ec/ed or unc%e/ed e$ception. &%e t%row /eyword is mainly used
to t%row custom e$ception.
Re>uirement :
e want to s%ow an error message if t%e mar/s of student are below UD. e need to t%row an
error message – (lease reappear for e$am).
class StudentCcepeption{
static %oid %alidate>arAs(int age"{ if(marAs O3" thro$ ne$ +rithmeticCception(-Reappear for eam-"; else System.out.println(-Student is ha%ing Distinction-";
}
public static %oid main(String args!"{ %alidate>arAs(O'"; System.out.println(-Remaining code...-"; }}