0% found this document useful (0 votes)
9 views

1 2 3 4 5 6 Merged Java Notes

Java is a class-based, object-oriented programming language designed for minimal implementation dependencies, enabling developers to write code once and run it anywhere (WORA). It features a Java Virtual Machine (JVM) for executing bytecode, a robust runtime environment, and supports various programming paradigms including multithreading and dynamic flexibility. Java's key features include portability, high performance, security, and a rich set of libraries, making it suitable for diverse applications from web services to mobile development.

Uploaded by

pramodmauryapk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

1 2 3 4 5 6 Merged Java Notes

Java is a class-based, object-oriented programming language designed for minimal implementation dependencies, enabling developers to write code once and run it anywhere (WORA). It features a Java Virtual Machine (JVM) for executing bytecode, a robust runtime environment, and supports various programming paradigms including multithreading and dynamic flexibility. Java's key features include portability, high performance, security, and a rich set of libraries, making it suitable for diverse applications from web services to mobile development.

Uploaded by

pramodmauryapk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Unlt-1 lage- 1

Java- Jwa is clas based, obje ct orieuted frogramwming


Kongepe that is designcd to have as few mblementation
debendencies as fossible. 91 is intended to Jet afplication
ony shere (WORA), meanin
oeveloberS wnik once , subpots
Code Cam um n all flakeform that
that comþile d Jowa
Jav wtthout the nced for eConpilati on ?t have sevral feafrves
veleased ?n 199S.
Htctoy:- Twa was fist in 19?5 {t is developed y
stteity, vebustness,and seeuvit eatnes much of its gava
gauting at Sim mtcrosycems.
micvosyskms Sun releated
ather) James 2o07.
irtual machine as fee open softvare on
tmþlementation et Java ajplication agram
2 Cembile
3 Run
beset
Tu TDk shuld be instlled n the Sysen omd its þatha shald

Class Test
publ'e sfafie void main (shing CI aogs)
Tavac Testlass n

Java v irtual Machine Hhis fs also kniwm as JUM the poppram


execution sess Qre

* woik tu þoogram omcd sava with "Jave extenyion


itgenerafes
Com þile utm the JArnc Conpiler it is in TDK
byt code fom þrngam helf of TUM as output
run the byte Cod with ?ndépendeut
So Java is kngwt as hlatjorm
þlateformm idejondet dongage
he (Tavab)-tanbe wede
byte Code a diasiembler
i6 we won to view
fage-2
Tava Devete me kit (JDk) 9t is a Comblek kêt that includes
Combiler ; JRE, Jawa debugers,gawa docs. etc. for the program olevlob
~ment we hawe to ?nstallTDK.

Jave Runtime mviomment (TRE)- TDk inudes TRE. TRE 0ncude s


a broier, TUm, abþlet susport and plyins, for runn ing the gawa
þrogramm. But we Cannet Cormpile ît:
harbage Col ector - rogrammers Cant delele te ohjectr. To delele oreole ct
JVM hs aorogram called Gorbage colle cter. /t(t can ne collect

the obje cts that ave not vejerenced if s Yelatd to memoy mamagoneut
Class-hatt: The clashath the tilepath
ilehath Where the Java untime amd Jawa
lomile Aooke tor class fles to lead. By decault, sdk faidte
þroide manmg Ltbranies tt you want to ncude exterral libronies
Should be added to the clascsath
features of Java- () Platefovm Tudlehendeut (2) objectoriente d
(6) Dishibuted
programng anguge (3) simhle ( obust (s) secure
() multithneading e) Portable (9 Higu þerformamce (o) Dynamic
exlbily (9 Samdbox cxecution
() Tava byte Codle Can un any where (Anchoid, windonss, Linux)"So Java is PI.
) The language have teur tore Cencepts of o0Ps
(a) abshaction (b Encapsulation (c) nheritance (d) Yolymorbnis
in Short we Can (AEIP) angag
(3) Stble stands tor it docs not have Complex features ike
þoinlers, ojerator overloading multiple nherifance and Exlictt
memot allocation
ru) Robust tor some heateres hat Tava make it brbut
ond Meme allocatiom:
garbage Colle ctien, Excephon handting
(S) Cannot access out-of beund amay- Jawa showS
Excettion ve to do so semal securiy keafuret ike stack
Comuti on or butte bver}lsw fo explort in Java.
(6) he Ca Create dishi butida apication using the Java feature
Hncat allows Concurent exeCution on all machines . RMT Omd EJB
Q wted for cisibwed as lication in Jawa.
(7) everload } abpicatio
fage-3.
(8) ortable - JaVa Code wri Hen o ne can be nn Cnywhere Solt ic
s
Called octable
(9) iigh þerfomam ce - Java ses Just in time (JIT) Combiler that exeeuks
Code om demand basis wwre it only combiles those
methods that are
Called making aphlications to enccute faster
(to) Dynamic ttexibiL: gava being Comhlete iy object -osiated gies
Te add classes, new methods to existing us the tetibiliy
classes, md een Create newcasses
Through sub-classes. Java eren sutports
sueh s C,tt wtch ame ntened totumctions wien in othr lamguages
as naive methode.
) Sand box exCcution- Java
allows wrer to execute thir þrogra
nn n a sebarat sþace that
system wtth helb ot a bye Codeahblicatioms
veritier
without atrecting
wmdering
Class keyword is used to declare the class.
þubiic
Static
access shectyier for þublcally vistbiulty
to make tumction sfatic Cwe do'not require to create
moinC) method tor Atnttng Compilahoy? object oc he class)
Sking EJ sermay opt to emter þaroameters to the
Java
at Commamd ne lt an be wsed as also progromg
Gem mnd ine 'or Cemsole
Sickemcut prinin To print

Ristony Tava.
Jawa was develohed b Sum miCro systems (Tames
goslingi mike sheridon Katricle maughton)
’ dn this year (99) James qatking his tiend stont
bvojeet (Team- geenteam)
James Aesling Gnd his tiend went to cae to dain kname
t Jawa cafe and buk go that the
Cofee me

ls belng are d in caBe

Use ot Jawa Jawa


Settop Goxes
Televisi on intonet Dishibutre Ayicati ons
App s siweb serUices.
Remote
kge-y
Andoid
Core Ardvamce Java
JaNa
(Soturare)
JOva
(Mebile AH )
(web sites)
Commemt
Gosmment:- lominent! ane te stateents that ane tetally Igmord
&y the Con biler or ntertretees. he Conmmenti Can be wbed
to þrovide explanation abbat the fogren ad ît is also used for
the documentation r underA tom d abilty of h rogrem
ch stngle ine
) Muliline

dittereut sies and valacs tha


Atore d in the
Ape cty
wariable:
Can be

Datatye
User-defincd
CNon-rimitive)
(imiti) c lass
Hintetace
umeric Nom-Numeric
+ Char (2) sing
Dectmel b boolean (it)
integer
Hshort(2) b double (8)

ariable is the hame


locat ion,in other wvds
Vaiablei hame which ser. Variable
it fs wsr defimed
values
Con Atore any types ot
pes of vaiable
loeal.
mstomce
Oxal variable - a .vniable
vaniable whtch fs eclared inide the body of
Jocal vaatable is de clave d inside the body of thu mehod oPage
S

method þarametes Metod þaramets.


Syn tex: vodun
int x}

Instance : a variable which is declaed inside he class but outside of


all Hhe methods is Called instance variabl e.
Synter! Class A

public Atotie void main (O

Static veiable! A variable wich is declard with the hls o Atatic


keyuvo s Called btatie variable.
Syntex!tate fnt X
ne
dalabyjhe to amtther datadype is celled
tyjoe castig
impleir xpitett
(1) impliet - (Small to Bi) it is automatically perormed by
the Conbiler
class AJ
Fublie static void main
t a -lo /4bye
double b=a; 8 bye output e (0.
System out print (b) ?
small) - By deBalt he Combile, does' t
) nltetexplieit
t (3ig to
allos the type castirg
double X lo-S n8 byk
Y= (int) x;
lege-&
dnbut X output in Jra; Input (Tava Console cla ss)
pre-defined class in
() nbut ( scamner Class) - Acamner is a
wuich s avallable in Javaoutil
util pac kage. Jt is wed
to get Dnbut tom tonsole.
Rules: it we wse Scanner class. we must have to Creat
object ot Btaner class.
= New stanner (Syskm.
btanner, obj- nameSystcm.ensol in)
Shing xt = eu. eadLin eC)
(2) SCanney ctass Metihods;
(a) next fne (); / to input shing
(b) next Lnt C); I Datger
(e) nextfto at () ; / float value
() next Boolean C); // true /false value
( next Deuble () |double alue
lass fa ckage at the tos of ines of þrapram
(9 Inport Stanner
Smtex! Tmþort Jawa util scamner

() oong mþut Cinput mismatch Excestion)


which we Cam
Om outtut statement in java trough wich
ts am
2) output: 9+
9+is
and
variables value, ressi on velucs amd atatoments
the
tontets.
Spstem. out pintc)
Here! System tetefinee etass avaflabte
arat lable t9ty Java-Jlomg
þackage
class.
out Alatte member oB Ssem
pre dejined method
print:
Java util scanner)
þeinting Somchtng on Console.
Ex: imþsrt
Class A
Stotic void maine shing aags C)
Outbut
enterdata s data')
System out print ("entrr stammer
getdata 5 (sysiemin)o
Snney obj nCmd
Q: obj nextInty*
System out-prinísh ("Giet data" + a)
fage- 7
lokens 9+ s th Amalest element a toogram that is
identified by a compiler eerny Java sbtement amd eeþvesslon
are coate d by ol tokens
Ex:
Class

Pubt'e Ataftic void main(Shing angsto){


int aclo, b20;
(t c atb
System out print C) ;

Lokens ame
shals
) keyward ) fdentiier ij eterator iv) sefaralor (V)
Ex. ci) keywrords: i t , Shatie , void totel 5o.
C? identiier ! variable, method, class, paCKages,
)
ete.
sharators;
(V) tals
sed
Keywords QT fhe neserre rds
by onguage, which have thir

ster booleam
tnt absha ct
tis
Shot reak inteoqace Switch Case
deBaudt native
byte synchronised Catch
double
Hhrows Class
if extends þactage Const *
pivate throw
ese imþlements
þrokched goto *
for inal Shhict*
while Publie hransiet
enumt***
Ytuy oid
do while toat qssert ***
Static volati le
char import
Not wed
Note Added in .2V
**
Atded in 1.4V
Added ?n Sov.

n Niall Just dike


Keyuvds but tay ar actay
Tue /alse Camnot
Hhese
we
as
Alterals you
frogrom
fage-8
operators ; oterats fs the symbol, Dsed to þergorm operations
requi mentr.
ohtrator s Typc
Unany Arithmatic
t*, , %
Relational
Binary< ,>>*,=l=
Jogtcal
Btwise
,I, <<, S>,^,
, t , - , * = , / , %= Assignment

Ternar ?: Ternayo he rator.


Statements:
Decisi on Making
False Taue
Test
Ex
taMC
work done În
Statemet ony Case

it-else
Palse Tue
Test
Bhatement;
else work dene
False ln Both situation
Slaement

Neshe d ?-else
false Tnue

false
Tetséf
9 else-i} Cadder
luge-9
T
X

felse it (C2) 2
telseit (C3)

clsef
A
multible
Buiteh Ex bresion: Con e B Case fs executed out of
Calesj
Suitch (exyresion)
Case Case Cunstomt; Statement
break
Cake Costot stakcnent
break

default: Satoment
Certain atemet senal.
epeat
to ebeat
LoopS whenever we have
times is called loo: when
wred loop " Jt is wsed
for tor looh is mest
comonly
iteration, condition and Tncremunt /dec.
we wa to besjorm ewhy Cenhok loop
eherati on tn single ine. Stis
Sytex or ( inihialization Test lon di hon mefdee)
Batememts
(2 ouile Loolo : while soop is a pre- ext loo,it kage- lo
1S wwed when we donlt knout the no of ikration fn
aduamce ?s lso
9t is kmo
also ,kmoum as euty tonhal loot
whtle looh Spntex;
initialization; CI yu Sak
saile ( Con di tion)
No
Shatoments
1eratiom&

Joop is a post- test Aoop, Jt


Jo- whie Loop; do ohie at least
to execute Loo bodty
Is wed when we want
telse. Gt is also knonn as exit onbol
me eren Condition s
when
Statement

fnitialtiation yes
do No

Btatements
ikrationS)
ohile ( Con ditiom);
Por each is mainly used to fekh he
;
( U for-each leoscollechion ike aney
values trom a
for 'ensh ( dataty þe varl: var) element No
Collechiem
yes

Statemnt
Ex! Var2L3= {lo2034,4o, So} ene

which contain
Nested for Loop; ALoob
ouler Anothur tor leop 9nsite u be
fs called nested fer Loop
der ( ihialiation; tondi tion iteratien )
Syntex
SFatements
Keles ot raúable deelaration ;
eombinafion ot choraclers
) The name of the vaniable s he
special symbol such
CA to2 or a to), Numbers (0-?) and tun
as wnders(ore (-) and doller (-)
nt a2
Voiable name aluays mention in 4he left side ot
avignmant oferator
int ar lo
characher ot variable name must be a
leHers or unders tore o doller
nt a o (ntcag int fa
their &hould be no bl anks betwen the name ot the
Vaiable
Int Sum lo
nt Su-m_ |o
($) Case-Seniie n Jova
oue
Int ab
Can't wte Kegyword as variable name.

s(Jara)- An Aray- is an object in Jawa ,ahich ontains


Siilar tpe oB data mContiguous memoy locatien
mdex

(1)
dotethe
data.ype ver nameL] cthyle a[
Declaration :(a) nt aLJ; 3
aLT mew mt a[51;
(5) nt al] mew nt 5]
(C) int aL] = {10,20 3e, 4o
TDAing le -dintndi'nal Aroy ( I-D)
DMti. dimentional ray (2 -D)
ge- 12
We hae to wse in tuo ditfent Modes.
Static Dymamic
Int aL]= new int SJ int size,i;
Scanner new BCanne (Systtmin)
Sys km-outbrint ('enter size oc omay');
a 2]=o size
int ac] = new mt [sizc];
4 [4J =So for (i=0; i<size ; itt)
for(int fe o; i<i)
a[i]= rnextInt()*
System out- þrint ( ati);
Syskm outprint(" Frinting ry element
Out put: lo2030yo So for( i=o,i< sizc; it)
Mehods in Jara; Method is aiJ=r. nextIntC)9
grous | block ot Code which Sytem outþrint(aLiJ+ " )
take mþut fom thu user
þrocessed it ond gie ouBput! .
method runs onty when it is calleol
eny
Types oB Methodi
Userdefined
( Name suZsested by User)
þrint(); Add ()
LortO; Sub()
Sqrt); mull)
nexIntC) Show() Ranamees
Syntea' Tekunn bybe tunction. name ( ) toith their datetypcs.

tatements

e metedy

) declare ine of code


(2) Rerdabi li y
(3) Reuseabiliy
(y Portability
fage-13.
mles ot method decloratiom
() defin tion
(9 (aling
C lass A

Publle static void mtn Sring C] ag)1


Disp03
Void Dis ()
Bystemm out frintbot"e togaay );

Static Me kuodi 3t is a method that belongs to a clas t , But


1t does not belong to am ngtamce of that class This method
Cam be Called aith out the instanee
object, of that class
or
wthout
method in fava defaults to a non-skatic method
it Non-skabie mehsds Can acCess
static nethods
Alatic keyword freedingvariable, wlthot Creating an instam Ce of
Btatic methed or tatic
hte
the object Non-Static Methods
Diterence between stati c ond
beh
the ditherences Belew are the Vaoious im pov tomt
letus claeiy these bontrs as ollows
derences amneng
1. Acessing memberS Omd wethods
2' Calling process
3 Bindia peotess
.S. Overi"ocation
Meme
process

Static Method Non- static Methed


boints
A Stakic Methed is a methed that bveny mehsd in Jav is nog- sli
not wibut statc these Can be
Drfinition. class,but it cloes
beteng totoaan LnStance ot that class Skatie variableSkatic nethed am
alaO: withot
betong
Cnd ths method Can be Called
tothout 0nstamce a ebiccl of tha
lsing objcct y fhat claa
C(asso
The Static method wses The No- stetic method ses
þroces Combile-time or eany Yuntime or dymomie biting
Accessin g
Ginding In the non-static method, the metuo
the method Can only access tatic doata membcrs
members'omd ny atic deta members 0cn aCKess
method amd toathc mehods aellas
Cmd satic metod of t/non- static mem berS an d meted
Omother class or the sum e
ot anoter class
Class but cannot access mon
Statie method and vaiable class
th no-Steic method Can be
thu static metod eanmot be
verridden beca use of entime
oveingl orerriddem because ot ey
binding
dn he Atatic method, egs
binding eXtlutien
meh memoy is wed to allotion
bec awse hehe memy
cution
Menay
alscatiem hemoy iswsed or exe
becabe eneminy allocatien
habpens whn fhu mehhol is invoked
ond th memoy s allotated
ti me &en henethd is
hatpene eny onleecause evyalled
thustatte keywerd fired a
anticular mimong or that methad

Ex| class hulser


þubli'e statie int swm (int a, nt b)
eturn atb

Class tut
þubl'e Statie oid main (shing] °)
Int n=3,M=6
nt S= hlser sum (n, m)"ts);
sysm: oudifrint ('sem e

Class tut

þublic Btatic void unc)

ncalling of statie method.


tut uic)
fage- 15
lass tut
þublic void un C)

Corating otject
tut = new tut ()°
teutie
Non-s method
Calling tou

(overiding E,
Cs Parmt f 7S t a c Meth
Static void Showl)

Systom out þrinkn Yarnt)


class.
/pavent lnheritoin Chaild
Class Child tends Rarnt
Void s h o t
S
Sys tem 'out prittn ("chad)
Class tut

fuslic tatic void maine Shg LIggs)


P= e
Shon)3 ( Calling parmt's S
I/ Cannot yide parent's ho Parnt c= new cutld C)
C. sh cell'ing ch'ld's shs )

Methods n JaNa ;
Hou to, Use

Class Demo

t n,m2}
þublic static void main ( Shing Cg)
ne Demo()
Demo rf
ref npwt)
ef process C)%
age - l6
void input)
SCanner :new Sconner (System:in)
ays tm Out. point ("ener tuso No;
h]=ynextInt ()

Void þro Cess()


1 tnt add, Sub, multliv;
Sub n-2)
div n/12)
Void outbut ()
Sys tem out. brintfeda4asd) :
Sysm"ow print ('sub"+ Sub):
sskmou pr int ("me+ mly

).
Caled
Re cursion in Jawa , A mehwd that Calls its elt is ecursion.
recursi¡n method and this te chniqu e is knon as

rtum methodname ( þonrametrs)

method-name (harametors);
Sunot n matul numbcrs by nelusion.
Class A

þubalie bloatic void man (Stlng- [] rgs)


Int a = Sum(1o) /| Calli
sys hem-out piintln (" Sum o naturul numbers'+ a)

ntun b+ sum (b-1);


fage-i7
are object that allows ws to Atore
Sequence ot charac ters wtich mayy lontain albha numeric values
nclose l in double quo kes. Exl "RAM"
mmutable inJawa
(2) 9+ (ontains Me thods Can peform certain
that
Conlatc), equal(), length C) ete.
ofcrations en &rings
(3) there ane tuo mays to Crale Shíng objcch
() Sking leral (b) e wkeyword
(4) Simg tral
dei
a= "devi"
shing b "devi" b
Sitng ring tenst þool
(b) Shini Sing ('deoi) HEA P Mermuny
Class A

þublie Statie void main Skin Cinst poot


devi
v) a
Heas Memey
Shinp a= " ankit"
Sysiein out psint nta)
Anket

Cons ole class Console is a bredefined cla ss thet is Qvailable


St is wsed to get user nput at
at nn time

Noki() Console class me tuods:


read line ()

2 Syste m. tensolc )
(n) mpost achagee
Synter! Cosole cjectname = Syctem Console ()
fage- 18
Ex. Imbort Jawa. io. Cendole ;
class A

Sing sh, char ch k3;


Pusti diatic void main (shing [] arge)
Cosole obj = Syskm Console ();
Syskm out rint ("btr lwemome)°

Syst mput frintln (" Eer fassword):


ch obj. reedpasnord ();
Systcm- but þrinttn (Username "+ sh)

Java vsRython!
) Jara is Compiled. Aanguage Pyfuon is a 'mtertrehed language'
aticalty tydlagye9t is dynamically typed anguge.
9Semi colen is Conpgo4tr eaon semitolen is obtional
Stetement
Y Conplex to learn tham býpthon éaby to learn Suse

$+ is Alower them gara /oopand


Ex
Cláss A Ex:
main PRrint (" Hello'):
pualie bktie void
Syctom-out þrint("Helo"):
’ Hello:
} outfut eutput
ELC chass We have a clas but inst de he class
BLC omd bsiness logic
e hav not main methd thin that class is called
class. Class A
£x.
fage -19
Note. we can wwe above BLC Class In ew al projects
What is ELC?-ihwe wite then tain methsd inside a class
hen th class is called enecutable osic class.
£x

þublle staie void moin (Sking ] arg) t


BAC is accessiable
l Here, BLe

Note ; A| BLC s ELL clas rept in Bame tobies:


cOPS in TANA 00PS Atonds tor otject Orientd figpramming
Janguage si ng the main þurpose of oop is to deal wi h real wotdl
Prgraming amgagmal ansidend coargey
eutiy GOPd teatures
sinall taltositedas ivstbo
A clasS in Java can lo tan
try ooplagg
Class . Felds
"Methcds
Object Cnsheos
’ nhuri famce Blocks LntotaCe
" Nested class and
Poymonthie m PHp tthem
Encapsulafion co langages are Jara, ctt, C,
’ Absha ction
loletion ot objects and ?t does not ake
Clas elass is a alo called as blue þrint
Class is
is
Ony sace n memsy thatClass has Shake ond behavior isknanai ebject
hm emtity,lex. chair,
/logical entity class bike, arker 3 Com be frysical or logical
Statt. ehrents the data (value) ofobj.
Behavior- fenchionai y
Sserdetid identity- Unique 1D fuse in JVM
tedefined tojdentit each other
Scamne Dog
Honsole A
defi nud .
System B9 detault class membersan
b]ect jSthe ntance octass. fhat exeute the class.on ce
the object is Creatd it dakes ut shace ike otty vaniable.
in 3is real word entitH, untime emity , twhich has bhate and behavior
memo Cmd it has an indtomc e ot class
obj = nw csmome ()o
Classmome
class name cbjc t
erence
DMA
consuctos
Conshctor AConsctor s a shecial yþe fege
o -ao
method whose name is the same as class name

Note ')The main purhose ot Conshuctoris to initialise the


Cbje ct
iy Eveny Java claus hes a Cons hhector
(tiy AYehuetor is automatitally called at the time of
ebje ct creation
(N) A Conbheetor never ton tain
Void
run type nc ding
clas Class-n amme

Clasmame O
) Default lonshuctor - A Conshutor sthi e h doeg not
hare baametr is called defaut Conshu tor:
class A{
AOE h No panametr msde tmcion

Clas A
it a shing b; beelean ej
a =lo0 be "devi C ue

otd dish)
Syskm out print Cat" +bt" "+c)

class B
publ'e siatie
Ar= new AO
vaid main (
Soing c] enys) !
age-2)
(2) faraMeherised Consctor! A Coshu ctor through thi ch
Com tass ene baramekrs is called parameerised
lonsheetoo
Syntex! Class A

Class A

method
A( inta. int b) lonshuetort
}

",*+)
Class BL
þvibll e latie void main (Shing [Jargs)
Ar hes A(loo200)

ukput Lo0, 2o0


(3) Coby Cons muetor;- whener we pass object itene
Consmetu:
to the Cenhu ctor them i6 is Called Coby
Cass elassname

classname (obj ref) (oty Coyhuc tor

lass A

int a shing 6
a=lo b= 'devi
Page-22
Syskn out hrint Cat,"+b)° Gutput
A(A ref) fo, deUi
2 lo, dev
b=refb
Sshem: out print (a +", "+b);
Class B

þubl'e Skatie void man (sbing 3 ags)

( hivate lon'hae t t - n Tawa, g+ is ossfble to wnik


lonshetori a

but accovding
brivake but
lonshctor as a þrivake according to the nle we Can't
tO the
qCcess private embeTS utside the Cas .
Syntex
Class clasMOme
private classNeme ()

class A

it a; double b; hing e;
brivate AO
U= lo b=305G C= "devi
Systemout þrint (a++bt,"+ c)
putie staie void maln (Sbmg [] 4ags) 1

Output to, 3o-5e deu?


fage-23
Method overT0ding Cnel Method overtoadng i
Metod oventid.ing i Sub class Cchig clasr has the sSame metod
as the dectared in the þarent ela ss, 9t is known as metaod ovariding

UsesijMekod overiding is ed to provide the specific


imlementeton ot a mehod whtch is aleady þrovideed by tk
Bulereless
() 3+ is ured for Qchive untime paly
Rules: ) The method mst hawe dhe samemarbhism
name as in porent
Cti) The method hare bame eranetersa
( ) Jhve must be n 15-A nelations hip CEnheritonce) .
Class A

Void unes butput


Syatom ut bointln c"a'"); B

Class ß extends As

Syc hem-eub þrintln "B)


publie btatie void matn ( Shing [] angs){

Nete: Static method Cannot be override.

Mehoel overloading it a clas has multible metheds having


the some mame but dijferent þoramelkrs. Stis knonm as methd
orerlond
tvom hagi 3tincreanes the suadability o} he
tuo types o weys to overload a meted in gawa.
frgram
1. Gy chomging mumber o} gments in Ja
2: oy changing deta ty sei
fage -24
y orgmends chonge- Sn this exampie we ae
totie methods sothat e dot't need to Creae lnstom c
for caling nemethsd
Class A
Atatic nt add. cint a, intb)} return atb;
static nt add (inta int b, mt c) { etusn
atbt C
Cless Testovertoad

þublic static void mal (shing ang)


Sys ko out jinttn
ym orut fintln (A: add ( ,2,3))
methrds
C) changi ng date ty pe.-- We have to Cratc tro
hawe "difjernt Aataytes
elass A
Aatic int add int , int b) retun atb93
Aatie ole add (double q. double b) retun atb
Clas Testoverod

þublte statie void main (Sing (0arg4)


Skm out printlne Aadd (,12))
Sstem out.þrintAn Aadd (2.3, 1-[) )

Notc! 9t is not ossible tochoge Hhe etusn type n metodl


ovenleadi ng becaase oy ombijaity
lorshucto verloading:- whunever we have mre thn cne
tonshu ctoT in owr clan is called Cershector evertoading..
Coyider the Jan Cuample in which tve hane luid
dittevent Conshuclos in t class.
kage- 24
Pablic class studnt we con wse this keywod inside the
Coshe chor, which con be wwed to
0int id mvoke the othe Conyn ctor of the samt
Shing name
Shudint)
Sysem out prinddn ("his is default tons huetor );
shudetcint i, shing n)
id ai;
nome =n

puslle statie veBd main (Shing (J ongs)


Shudent s= new Shudent )
Conshctrr valics
Sysem outþrintdn(" Defaut id"+sjt "Shaletnome "+ S. mome)
Shudent
Sytm out þrintln ('farametris
printly " ed Cos'metr ralues y
Syskm out student ( /0,
Shudnt shu = nen "1nshudeut name:"+
cShudent id "+ shu. td+
Sytem ou þrintly
Shu-name)

Instomce klock in Java: intonce block is Aimilar tomehhed


wthich has noname 9+ com. be writen nsideaclass but not
0side a methsdl
Nok:)3t alays executed befoe the Constructor
2) wee tam ohe variable mly inside the instance block not
$) we wrik Hrae couming Code inside a ing lance bleck llke metd.
TDBC conne ehivi
Smtex Class A

-Code / Lastonce block t, No name.

Static Block: Statie klock is Such Kind of Block in


Tava. which Contoug get exccuted at the time
theclass ile into JYM Memoy.
we con se this heyud inside the
kaje- 24
Pahlic class student
Constuctor, wh ch con be wwed to
Int id Invoke the otheY Cony mucor ot the same
Srimg amme
Shulntl)
Syslem out þrintdn e"his is default Cns hneetor");
shudnt cinti, steing-n)
id ai;
name n

þublic btatie veld main ( Shing 1] org)


3hudent s ew ShudentC)
frintln (" Defauet Cnsuctr vales:
Sysem out
Shudent id "+sjd+" shdentnome"+ S. name)
Systegoutprintln (' amctr values)
fargmeterised Cont
syskm out frintnC" shudent ( /o, Ydevi
Shudnt shu new shudeutname:"+
CShudent id + Shu. id+ "1n
Bytem ouþrintln
Shu-name)

Instomce klo Ck in Jwai in tonce block is Similar tomehed


wtich has noname gt (am. be writen nside aclass but not
ide a methsd
Nok :)3 t always executed before the conshructo
2) we can he variable only tnside he instance block not
() we wrie Hme tonsuming code inside a ing tence block leke methd
TbOc connechivi
Smtex Class A

Code I/ Lnstonce bleck ut, No m


ame.

Static Bleck: Statie Block is Such Kind of Block in


Tava. which Csntoa get exeCuted' at the tme
theclass le into JTM Memy
fag e-2
A.Java TaNa C ’ArclasScass Lsader
Shahic Bye Code
Glock Veviier
Class A
Pruomaticly Eecution
Enginc
Static TVM

Static Alock,.

DiBeren ce ot static vs lngtamce;


static
Tnstomce
I: Instomce Bock Cant access |. Aaic block can exe Cute
twithout object without objcct access wih clas
Can access Non sttie take Access en ly saticvaTiable
vari ab les
3. mstam ce block thn Consectot Stic int b 20
bleck wil ee Cule

Inheri tenee inn Jawa when we Cohuet a ne Class


that the ne Cass Can
from exishng class, in such a O,taca is called Zaheritom (e.
access al t
Exknds keyuord is wed to pertn
Note'u)Ty Tane, these
Dnheritomce
code rwscability
(I ean't aCce Ss boivak members ot arent class.
() A child class ean access A( the teatures ct farent so e
Subelas
have to eeate an object ot
(y) methed overriding ony þastible dirrayh Inheritence.
Syn t: Class A
farn
1/membrs

Class 6 extends A
Child
I/mem brs
Iypes o Buhritomeei
) Single Inheritomee- one Super class A
extends thi ub class B Suber A
Syniex: Sub
Class B extends A
Class A

2) Multi- level
inhuritomce
Class & extends A Sabor

class e exknds s Class A


eSub 2|

Cass D extends e

3) Multible Inhenitomce Tara do'es not Suport mutile


Inhitamce dire ctlyy But 3t suþort thogh Jntajace
whener a sutb class
Super 1 (Ser wants to inherit the brahuty
ok tuso or more Subelass
Sub l lsdt that hawe doe
9 Hieranehical Juheri lomce - methd, Tava (ombi ler
Can't decicde which
Suher class mnethed it Shaul d
nherit
then their might Le
Subi Sub2 |Sub3| a chon ce ot memey
dubli cation (ie sava
does not Supþort mltiple Lnheritonce throuph class.
Super and this keywodi
Suber Keyrrd i 94 ferns to the object ot suser class
itis used whem w want to Call' the sufer
class vaiable ,methods and Conshuctor tmugh sub clos s e e
fage-27
Note () whenererr the suer class cme Susclass Vaotable
Omd methsd nane botth ae Same then it an be wed only.
(2) To avoid thu Contuon between super clas and subclas
Vavlable ond nethods that have Bame name we shold we
Suter heywovd ) vaniasle (access) / incu
Suterf) method (call
A() Cons huctor C
) 7 Incude
Call) defoult
in þarameter loss tructrr.
Syn ex () frogram Jer vani aste Acess.
Cass A Clas A
{
AO

Clas &extnds A
1nt a 220
class s extend A Void Show)
Systemm eu print (a)
System oud printn (super a) :
Class Test

publie Btatie void main (shing og)

() ogrom }or Meinad : rShowC)9


Class A

Void gBow)
Class Test
Sytom.ou pintlnc"Helle A);
publie Atatic void main
Class Bextends A (Shing C] rg)
Void ghon) rShow()
Suser show()9
Syskem'ont prindkn ( Hello &ye
fage- 28
frogram tor Consuclos:
Clas A

AC)

Systemy ot- print ("Hello A):

class extends A

6()
Syper ()3
Systeny ont. þrint "Hello BI
Class Test
þubl'e Static void maun

This keyword i- This keywor referes to the curent obje ct


Inside a metod or Conyhcfor
fage- 29
This keyuTdi this keywrd s to the Cument obËcct baide a

Ex! Class A

His A

Ar= new A C)
Ex Clas A

Votd eho)
Sysemot -brint this) ; 49 708197d
fublie bteuti e void main (Shing arys)
Ar nw AC)
System outbrintln (r);

wwnever the name ot nstaonce and local Vai ables beth ane
Same fhen o untime envIrenment JUM get CoNtue Gn cwiCL
me is local vaniab le amd wich oneis tngace vai able, to avid
Hhis brot Tem we Shold e tats kepuoré
Axomple: Clas A

jnt a
ACinta)

Vold showC)
bytem. out- paint (a)s
man
public Btalic vor'd main (5ting lIorys)
ShoC)
(HI) 9t is also wed whcn we wont to call the default Conshuctor

Synte lass A
Class A

Syslcyoutpintln (" Hetlo"):


A (it a)

Sytlem:ot paint n(a)


Cutputi
IHello htte statie void main (Stsiny [om
l00

(iv) 3t is alio caled þaramecheris ed Consnuctor of fE owm clas


Sunter!
Class ClassA
AC)

Hhis lo)' Huis (lo)9

System eut þrint (a):


publle Afatic vord main (srimg Jar

4)
poly morhim fs the ek vwd toose
Some ohjcct houng dijevet behav10u
method hore
(stooner
Some chje ct hae
bie ferson
eiylcoxtbehavieg
Teactu
lage-36

) void beoson (leachci)(0 vord horson (shudeatj


() voied peason (tiond) iy) void oenton (Cwtaer)
Tyhes: þolymobhismg

(omile iie Rumtine


(S tat'e, eanly bindig) (Dynamic, mle, late Binding )
(a) Comile Time folymarhitm poy morbhisa whi'ch is exists
t the tme of Com bilation , is calle d Com
bile ime cr eany
eanly bindig
tyþe uelhwd-name (banameter 1):
ekurn tyþe mehod.nome Cpana1,ogo 2, þona 3) 2
xanhle
class A
od addc)

Void add (int x, inty)

System out print (O;


vod add Cintdouble )
double C
Systm out þrit (c)
bubl'e Alatle void main ( Shing IJarys)
Ay nCw AC)°
Yadd ():
T-add ( (oo,200)
iadd (So, 21S3)o
(in Runtie olymor þhio; A polymoyphicm whlch exists at
the time execution of þrogram is Caled un timc bolymor}
Examßle meuod oveniding
lohemeyer drile
e write mcthnd in Suber cnd subclass in uct
a had metod nome Gand panqmctex must hare Same
Called me Ruod eveniding
class A torona:
class shabe
Vord show() 2
Void drawc )
Sytkmout faint C"Bhefectasu'

totd sww() tlas Squar ectendd Shabe


votd drant)
2
sys)emaut-þint ("square ctas?;e
Lncabsulattn 9+ is a mechanis class demo
throush which we lan wras the data bubl'e latle void main (Shing
þublic
members Cml wember methods ot
Shabe
Class in a single Unit, Called Erg new bguave C)
drawc)9
Note- declare dhe class Vaiabtd
as a fuívale
2) declae the ctass method as puslic:
Exam le Class is a best examyle o Cncapslati on
metnod
yariablee
void disþlay ( tht a)
Encaprulafion
fage-31

Ax A
classA

oivale int yalue ! data hiding


bublie void setvalue (int x) data abstaction

Vaue

pislie imt gehvalue ()

bklelatie vaid main CString L7ergs)


Y Setvalue (too)
Sysitom- out þint (rgelvalue (0)?

Abshrahion: An Absthrat ion is a proces of hiding the injermatien


o deiais om dhe User
User only.
only the hi_ lipated set'o seruices
pavided o the oser:
Add)
Code behind te Calc.

Calc
Advatage (1) Secuity (ti) enhancement
0) obeta ct clos cb) inlece
Abshroc! class Can't ceae object) class boti'ch
aon ta ns hL abskact keyucnd in s declaratin is Caited abshac
ciass nd we cant crak objeci yor abshract class
Synter) abshract class A
:
cT mat not lontain abshact method 3t Cam hae ahshract
and Non-ahsha ct metuod lo use m abshact class, you have
to inherit i rom Subcloss: a class tentain bant ial imcmen
-tation then Should declare a cacs as absha c
Lx! abshact Class A
Seme action but
di fernt Implementation

abs hract class @nimal

Pubie abshact void Sond l)

Class dog. exiends antmel


ubtle tvotd soun dt)
Syskenm out print ( Dog. barksJ

class lon erlcnds animal


publ'c void soumd )
Sys lem out brind ( " n roar)o

Clay tet

Szaes publie statie void main (Shing LJors)


Dog d = Dog 0;
d Sound ()
Albshract method Amethod which contain abhra Ct mmodtier at
the time ot declaadion, is Called abshra it method.
mly be wed in absact ctass
() 9+ doc shW contain ony body and alueys end
Abshract method mwst be verridn in Aub -cdess
Ofhuwise it wil alyo be come a absira ct class
(V) whenever the action is Cormen but implementation are
diterent Hen he Sheuld whe abshra ct method

abshact class og
þublic abs hact ord devlop ;
tass html exends pre f cluss Test
Ooveride þubl'c static void main
(Sirmy LJars)
Syskem out þrint (" Relo)g
Class Jwe
9overide
þuolic oid derelop ()
Syskem. out þrint (" wordd )

ata tace;- Inter face is Just dike a class ohich lonfans


nly abslra ct method 7o achieve mberace Jaa þrovidec
keywrd called implemants.
Jotc ()inr7ace methods are by defautt publie and abshact
d ntra ce vaiasles are by defautt bublic t static +inal
iy ntrtace metnods must be overiden inslde the imþle men
-ng Classes
( Titrtace nothing but ceals with cient Server
Souree tode hidden ee ile given to Client
Source Code hidden
Exe jile givnto the clicate
loo%
Teguiemant Developer
client

Exomble Tukrlece cient


void input () þubli'e
I/ abshsact
void tutput () Il þublie abshact
Class dewi impemnts ciet
Shring name ; double sal
Output þublie void input C)
enterSName Scamer ra nw Stamner (Syslem: n)
deu? System out- printtn Enter Username")
name i nextlinc()
Soeoo, 3o
devi sooeo.30
Sys tonn out bintth (' Ekr.
Sal = r nextdouble C)

þublie void out put c)


Systemout. pint n(name +*
þaslle statte vaid. maln (sking I3 ey
client C = new devj ()

Coutfut();
Why initace vanables are þublie, Atatie and nal
Ex,
Intadace bustonerRay
lnt amt = 5 / ablie t satic + fnal
void burthase C) |ll bublic +abshract
age-3

Class sellersenju Imdements Castom


overide
public void þurchase()
Syctom: out þrintin (" Raj ne ds't amt t tor farchae ")
Class cheek
i baklle Atutie void main (String =]orgs)
Customer C= nem selersamju ()3
C purchee 0;

Mulijle Intieritayee, with Latrja ce; - wewe Ca achieve the


maltihle inheri lam te toigh intortace becauie jntorgace csnfains
only abshrect methrd,wtich imementation is faovided in the
Sub-class.
Note class c extends A, B X wrog (Notþocstble
Class cc im blements A,B
A

NStSupbrte

Class A Class c önblash exlends A, B


yoid chow ()
fnother fsogrami
System out þrintln ("A):
intrgace
class B void show()

Void show) mtogace


vola Show)
Class c imþlements A, B
þublic void shoo()

þuslie statie void main (Shing Carg)

m Show ()

Output itorgece AR8.

Intrgace oithu exkond keyuovd (Erknding latrya ce) ;


interface Cale
Class Test
void add )
þublic Atatc void main
Iderace Raj extends Calc (Siny CJg)
void sub0;

Class ankit mplements Ray


ouerride
þublic void add o out þut
addshiy B0
Int az lo, br 20, C;
C=atb
Syshem: ot println C"Additien "+)
'Ooverride
public void Sub C)
Int a =2o,b= 1o,c
C=a-b°
SySkm Out baithy c'Subhaciion'+ c)
fege-3y

indertace (Takl8) Betore Jdk i.8 interace can only have


abshract mehods and al the abshact methods of ntertlces must
be veride imM Im7lementing Class as hell ak mettods are publie
ond apustrect by default"
Examjle- interface A
void aI): / publie f-t absracf
void e 2 (9 I| þublicf abs hraut
defaul! oId asc)? ofer 2 yeart

Class s implemnts A Class c imblements A

Rublic void atO; q2()


Public void q2(0;

Pinal Keyword: final is a moditier wtich provides


reshic tion in gav Codey w
we Can e
inal in three ags
Anal

Vaniable lass
method
Fnal vaniable ne nwe declare a vai able a aa jinal
Con't berjorm re-ásignment
Sntex:
final method i ohenever we deel are. q method as a final
it can't be Overridden fo ouY ertended elass
Syntex; {nol void mi)

inal cass- whene declae ac las assaa fral


Can't be cxtended or inheried do Sub-class
Synkw: Jinal class A
New keywordi Ne Key word Cre ates nenw obje ct omd
3+ wed to allocate dyamic memsy at run- tim e
Class A Cass A
I/ olata member dada
methods ,methrdy
Conyhector

method; (Benp rea)


D Call Inshance vaniable Non-s ltie methocl.
2) Call longhuetor
3) Call y
ovexride - this amnolation is a new eature inhocdueed
Jawa from jdk1.S. 9+ oovides a loos Cleantty for the
deviagors ond Gompilezs thon the mehod is oenide mensd
hen the Compiler will genrat an emor

Covani ant reum tye in gaie: Gofore this Cont ept genrally
we hasoe com't Chamge the neturn type of overridden method
but ne Conceþt inhoduced in TaNa Called Covarint
where we Cam
Change th rhn-j e ot oreidden metnod.
Class A
A Shonw)

return tis
}
clas extends A

metun tis,
lage- 35

Va-args method - Van-args Known as Vai able rumber of orgumnts


methsd Omd 3t is nens moduced in pdks S by wsing two Gonugth
We
tals
Cancallngfais methods
anyy no of foramdias ineuding yero þormaiers to
Classdemo
?
þublic Ahatie void main (Sh ing 3arzs)
void add ( int.. . a)
radd (0;
Y add (to) su=0
radd (lb, lo)9 dor(tSotSuata
r add Cio,lo, lo;

System ot- pr int (Sum)

Java Ya ckagei ATae kackage is agroub o similer types of


sub- þackages"
Classes, Inkertaces and Sub-
Rackage
built-in User-deined
Advantage:
() Tara backage is wsed
fackag< fackaje to catcgorised the classes
(Jara, mg, awt, Javax, and in es jaces so that th
Swig, net, 1o, util,spLetc)
can be casily mamaseel
t Access þookctioy
Jawa package () moves naming catisior

lawt
1 Button
Syskm.clacs Awaylist. Classes
Shimg clasr nap
Acces Modlikiersi within within udsde package Outside
by sub-ch packoge
pivate
Class
fackape
default X Y
þokcted X
Public
ote aa
Jhe þackage keyword is wed to Crole package in gava
þackage mypeck ;
þalte lass Simjle f
þukle Shatic void main (Shring QugsL)
system. out þrint Lon ("wellam to þackage');

lom þilation Javac -d directon tlename


B Jarac -d simblejava
) sþecijies the destination shie put the genrated class ile.
0r you can e (o) for Aame cire ctony
Java myback"simþle
To Acces the backage tom outside tthu hackage We wbe the

ACCess Alt Classes omd Lnttace


Not Sub þackages
) mhort þackage *
() tmbort þackage. classnamme; ’ on ly declare d class
nam e Acces siable.
ScaSS os Lntertace
when two þackage hare Same
Class nam ej thn iFis wed
Clas puth for localing classes; Cassþath /s an enunonment
vbniable needed for the Taa Combiler and untime to locate
the Jora backageelasses wsed in Jawra prapram:
Creating JAR- TAR Stamds for Java archive, w'hose tormat
is based om thu ziþ tormat t is colectiom of tles into single
stis single C*oss- plak for m archive fomat, that hondles, imags
Qudio.od class tiles t is ba ckword corn batib le
Own Jor tiles wtng elipse IDE:
() Select Éxport trom ile
(2) SeceCt Tawa JAk 1hen cick on Next
(G) choose yava jar gile sheci<icat on
check thu cheeckbox Ex þort I ava source
hetoe
(S) 4he m cllck nish.
Page-36

Jave statte 'onport:- The state imþont eature of Jawa 5


facilitate the Java þangramwer to access any static membr
a class directly'here is no nud to gualiky y the
ClassnQme
Advomlage :()Les Cading is required i youtae
Qccess ony Atatie member o} cass o}eny
( Disadrmlage- you overwe the shatie imjbor t feakure
t makes the þrogram Cunriadable and Unmaintaineble.

Dierenee between im þor t Gmd Batte import i- impurt


allows the tsoramer to acess classes of a pa ckge
without hackase quelificati'on hereas the Saie import
featne allows to access the Btatc members ot a class
without the class qual'fication:
The imbort
inerhces bouides brouides
accessibiliy to classe s anel
whereas statte acessi
importpi oovides
muides accessibili ty
to the tatfe members o the class.
e Cam wey an
acessibig
Import statoment to mport classes anel
interkace of a barticalor backage hen
whenever We are
using
imbort statement, f is ot requird to wte the
fueli ficd name amed e Can wre Shurt name directly
we can we staic tmport to mbort Matic, memberfoUM
a þonticular cla ss and package whenee We a
wsing satte mþort it is not equtred to
not requird to wse tu class
- ngmme to aCcess Shatic member mel we Can
hm portShatementi oTo access a cloSS dire e+ly.
mothur package we meed to wse, tuty queli7icd name or
we Con Whe
ACcesstbilty is baved on the access modijiers
Jova Aong is auto atically im bortd by Jawa.
Skattc Imþortt
Jt imports
mbots all Shatic data so that we can wsc
taithet a class ncme. intodu ced in Java S. Gnd ts Advan tagc isredci no
key shokes and reusability
Unit
Excephonal Hondling i-- An exception is atunexfeced umwonted
abnomal sttuation that occured Yuntime Called
excephion we hondle exception to Continue the how oal
execut'on till the last- time. o that the normal ttow of
the abhlicedion Can be main tained
Exceb tion is an abnormal Comdition and it js an event
that disnetts dhe nomal }tow o rogyam:
Ae mec hanism to hondle that.
Handling ts
Ex Clas Not found Exce ption , 10 Exception, SALEXC <ptiom
Remote Exceptigm etc.
Throwable class is the voot class ot Tava txception
Towailong:
hieranchy,in heriked tuith tso subclasses Excep tion and Eror
[owablc

Exeepiom Eron
10 Exceshoy. Sakover7aw Eror
VitualMa Chine Eror
JclassNo foundExce tioy | foutof Memory Eo

Runtine bsception
SArihmatle Eacesho
NallbointerExce7tion
-Pumber jarmatfxceptiom
ndexontof boumd Excehtien
rvaylndes butef Bonda Ecotia
Sing dex @utoj boundlstxc
ton
page-37

Java fxcebtion keywords :


JE is ed to Shecity block whee we shodld lace
Cxcebtion code 34 neans ie Can't use ry block
blo clone. j is
jollawe dby ciker
eiher Calch or
firalty
Catch- The catch block 0s wwed to hondle he excebtiorn 34 (om be
block lalr wth out ny we Cay not we
Cotch
firaly:
program 8t fs exetwted whetheY
Code of the

Or not
exception.
tnows- JE is used to declare excestions gt doemt throw
an exceþtion gt aþecifies hat tnere OCCur an exceptoy
In tu method gt is used witn metod sijnature
Start

exeeute
y block
Catch CExcestiom c)
No
Syskemm out iinthn (e); exception
yes
ignone cateh
ex blo ck

bls ck
S2 ersr may be
Catch l Exception e) exe cut catch
block
handle wtth sy
findty
de fault Block,
J

S6;
Inkertace V Abshaet class
absract class
Interjace
Iniergace Contatns only- abstractAbsho ct class cntains bothe
Abshact
) abs ta ct Non-absta ct metho
methed
2) St suyorts multþle inheritamce-9t cdoesn't Supborts multible
inhiri tomce
inertace
3) 6y olefault ixheottanee there ane no eshiction om
method þubli, absha ct
ar abstract class method moditicr
No Ned to declare variable
) By defa«lt intcrace
Vahiables ane þublie Statie hi t as þublic t static+ final
inal Abshract Can declare lensut
S. /nkrtace doesn't allos to
allow to default delere
as Coheeo.

Cheeked vs unchec ked;


Cheeked ncheeked,
the exceshon sthich are OThe eKeeption ushich an not
Checked by Combiler fr Amoth Checked by Combiler and it
exccuhi'on of þrogrem at un- time dlrectly taken care by Jum:
Checked excejotiom are ) mchecked excepion ae
Commonly occured exception OCCumed excebi 6n s0,
-so, th Combiler akes veny thatCompiler does not take
much ae about fhese Vey much Cane about hese
excephion exception.
fnalize
ni method in TNa ; inize is a metnod, which is
available in objectofsuper class The þurpase of this is to
elease the esources that is allocatet by unwse d object
esources that
beioe emoving. 4mured obje ct by gorbage Collector
lage-38

mal
Vaniable finalty f'nalize
obiec.
Keywrd class Chn sed ahat method
(Énol) method
0 allocate d is releahed

atch( sinilize
Cleon ub Code.

Throw keywssdi gtis wed to thow the user defincd o Customised


exceshion objcct to the gum ex þlicity tor thet burpos e we
Ube trow
Synex throw new exception

else
Throws keywod-Jtis wsed hen we oloes not went to
nondle the excebtion ond ny to send the exce btio to the
Class throws Demo

publie statie void main(Shing C] gs) throws Intemte


2
tor Cinti:l:i<elo; j4t) Erceptisn
Syctemm outprint (i)9
threal slecpl loo)
Exception fopagaion: 9t is a tcchnigue. thrngh wwhtch
througl he can
hondle the exception In the Caler mcthoc
main.) mi)
Ex'
mi)
m20 Call System undtint (1o)
)

with iles and


Handling. car (ilk Hondling);- Hehond 'ing rdefine s
ewanct
how read oik data on a ileile
steage.
To þackagc Contains all tu classes tough uhich we
Java 10
Can þergorm al' injt and outfut oevations întn the gie.the besis
Sbeami - Sheom is a sequence of data on
l th classes dired tnto tuwo
fackage Srecm

byics Characters

methods
File handling () get Name C)
(3) getAbrolteþatn ()
(3) Create Neu fileC) (91 Mkdir)
(4) Delek) (t0) st )
(S) Exists() (1) Readc)
(2 ricc) (13) enameToC)
(6) lengtn ()
Classes
pile Handlin
() file (S) AleOputsheam
(2) file reader (6) Bulferinbut Sheam
(3) Pile uwrites () Bueroutpd sheam
(4)
(9 file Inþutsheam
Oherationd o< file
() Create a fi le
( get file in tomats
(3) read
(4) orite
(S) Atpend
() Delete

PiiArcadng i Condurrend process 7umning at thu same Hme


fs Callesd multitasking. gt can be acheived
by to
ways Multi tasking

Rrocest
babed
VThread(mit orendtng)
bahed

Jt fs the fang baocess to execute multisle threads at the sametime


twithout dejendency ot othr threads called multithrealing
mainC)
de posit C) ’tI (lo Min)

minuts wtydrawe) l2 (lo Min) less Hme


Cheekout) cPesgormance intoeate)
-t3 (to Min)
threedi Thread is a fredefined class ohtch ir auailable
in Tawa. on þackage . 9+ is a beste Unit of CPU
3tis wcll hmo fr pndefendence execution.
How to Creatc, threal?
By xtend
fkknding
ghread class
Lmplomeating Runnable inkryace
Runnable nkergace - Class A mjlements Runnable
fublle vod nen C)
state vovd main
Juslie)Y: (Shing args L) 2
Thead t
new AC)
neno thneed()°
nCode ef threaeljob/ Threal.
tstartt)
Hmead class
Class A ekleds hread Cla ss 6
Joveide public slatie ovd malnc
þubllc void n) Siy l3ary)
h Code 'stantC)°

Thread Schdular i- Thrcac schedalan is fant ot Jm which


executed mutible thrcel en r single processor randomly
Thnead scheduten will decide with ysk wi) execute Istand
How long
JVM
) SM
D FCFS (Hist lome tigt
t Sy Setve)
2) SJF (Shorlest Job tirst},
SM 3) Round Robin
Thnead Schedular CPU

Thread life cyclei - As we kne a thread is well knawn


eK Ccution ding the life cycle atread
tor indebondent exccuhion
Can more trom dittenent a .
New statk ( Born )
Rumable Statec Ready)
(h) Running State (execution) t.suspend ();
t|· Wake);
waltin state ( Blocked) ty: Slepo;
(V) Dead Bate (exit)
tresumel?
tSoinCO,;
Blocked
ti.Join);
tË-stant; TS
Bom Ready) fuanniny)
tstoþo:
JUM

Dead
lage-to

Malli hreading Sleep methdi Skep is the Static metuad ot


Ahread classshich taegugh throws checked excoi on 1:e
Dnbupted excebhion.
The main þurhase ot sleap-melhod to put a threul into
cmberony waiting slak Miliseconds.
Symtu! Tread sleep ( laoo);
threadt= ne threacl );
t'slkep (laco)
Join Methodi The main þurbare ot Join method is to
but the thread into
execute Comslete knforan witing
walting-
ay oticular tread
state it We want to
all the threadls
available In thL thrad hoo
’ Join method also tuouo a checked
Lwasted Fxcestim eKCeptien.
Ex:
Ty CaCatch.
A ti= new AC)
A t new AC)

te' Join); -’ whn erer is executd it wl


exccu til tatËme
Methodt resume c) metod
the Maun burpos
is to put thre thread ton
nnning State to baon
A t = new AU
waiting
state.

= ne A(

tiStort); Atr gäki.|. tus method does not


tLStantc); Suppert.
ts'stent
t- sus þond l)
Resume methdi gis ned to ettd redume Aussended
thread trom haihing stte to unnable sta
tyaresume ()
Yield mmetod )s Yjeld iá a methad ot thread clean that alloo Ws
to un an hyr thad whhch has same
u r t tmead.
At mew A );

nent A);
ta yield c)}
Stop ) melnodi Slop is a metsl of thread cass
which is
whed to tminate a thnad bemanent
Atl = new AO

At3 ne A)
t. StutH),
t estos 03
t3- tant)

lsAliec) method) isAlive is aa bredefincd methol of threalO


Cass through whi e Cam weathr a thread isAlive

NOt i) ik thread is Alive it will etum


o

we method befor the htant method Hheu


whe 0salin
1t ie þrint talie but tae afr stot method
it will þrint tue.
Lnterubt method);- It is a metnod o thread class that is
wwcd to Intemubt the thread.
or bloCked state.
Nott, 0) i7 ony thnead is in slecbing
then eaily in kmust th execatiom of thnead by the
we cn
throwing Intmat aception
() i tnead not is Sle fing m waiting- Shake then toreadl
Cxccute nomaly
’ Setbriority () HpoO-
ame Ln Jawa it is ossible to asion
the bricyih
ihe bxiayi H t Tose
o tnad To the jrioriy of reed, Jara threal cless
sethe
has bapvided two þredefin cd melhod
() sepriority)
The Thad class has also providcd thre predefined tinal slatic
Vni able and its value will be bewen | to 1o.
Thread MiN_ PRIORITY 1
Thread NOA M- PAIORITY ’5 defaut
Thread MAX PRIORITY

3 Ati
3 A t ner A0;
At = new A ():
Synchrni tation; þroblem otth mulitreadi ng- Multi fhrading
is good
Doss ble
Whenerer We hcmt to complek our
but in sTme situation it may provides
itareadig
task as Aoon as
Som e
result G7 cumbted data this situatin 0Ccur whwneer
Seme nsource Ls ble
acce ssible by mutiple thread at the
Aame- time
Synchronitotion the technipue througl Jhich we Can Conol
rnlible thneeds r among the no o tmeads. cnly an
Qne
tomead will enter jnside the Synchronitaticd anea.
The Main burhese ot synchronitehicn is to overome
tne broblemn ot multi tnealing whn mlti ble threads
Cme to acccss Bome SoUrces at t e same time
6n that siuation Jt þDundes Some
hread Synchronitation is clastificd into three Caltgories
metnod level Synchrpnitatoy
(2 blo ck lerel Synchonitation (best,tast and time sarer )
() Static synchronization
Sotuien þublic synchvonitd void rn()
Rubiy void un) h same resource:
/ Som e resource
tlStart);
t . Stant); t2Starto; oinent byene
Same
ime. t2.StutC);
t3-Sat C) t3-startCO
faye- ss
Tmaf mheacei- mat inkrtace is prusent in java td þackae rorsets
a maping beku
a
betwen akey amd naleo Java Mas intrtace is not a
Subtyjpe ot the calle ction inertace. Therefore it behaves a bit dite neutty
trom e the rest oB the ollectiom types A mat tontains wnique ke
mass are heYect to wwe ter key--value asotiation mabping eh as
dictionaues. he Mats are

Bomeone womts to rehieve and ajpdak elements by heyt


Bome Commm scemarios ae cs follws;
A mat o} enor cdes and ther descr bion.
A map ot 2 iþ Cades and cihes.
(Treemat
Im plements
ca
cacs
Linked Hash Mal Class
extends.
|Sortedrlap inhorace (HaLahaf class

extonds| mplements
T

Creating Ma objccti ntutace


Map is on inter7ace, objects Camnot be creatdof
we al ays need a class that cxknds tuis map in order to Create
am objct
Ex. Ma hm new
ttesttaplO;
mat camnet Contain duslicate keys Cmd each key ean te maf to at
moit ohe value. Eee
method wsed
to clear and remove
(() clearc) - tis method usd n Jaa Mas intertace
A o the elements or mafbings tom a þecited
map collection.
wsedin Jara to check whethna
(1) Con tains hey Cobject)- this method 0s or
Maf Not gttakes the feey element
matpd into te thatelement is mapjaed in the Mas.
þantcular key is being retms
as a baraneler Omd hue it
alue sbeing
(y Confains Vauelobjet);- 3+i to cheek apaticular
key in tha Maf in Jaura tocreate
) set O this method is wned in Maf Intrtace
emhy sam e elements lenaned iy the
mab
a Bettot e
Java Map intortace to check fu
(W) cquals (obíe t): This wmehod is wbed in
welity bet
betueetuo naß s.
(Vi) et Cobjcct); his method is wned to netieve or tetch the velue
In the farameher
maped by a ponti cular key mentioned hasheode
(v) Hahcode - This metnod is used in mat intertae to generate a
omd alues.
7or te given nat Containing Key
bge-s4
i) iaewmby )- Ths mctdis wed to cheek it a mat is
(ix) keuset U- Thls mekmod ls wed in Maf noya ce to retusn
hawiganyuiy
a setvien ot thekeys
Cntadned in this mab
() þut (object, objecty-7his method s whed to assoriate the speelhied value
bui the Apeeitied key in ti mab.
(«) pua rMap)- Ths melhod ia wwed im Mop intogace to Caty al o} the mofsing
fom he speited maf to this maf. .
(X) remove Cobiect) This method is wd tormo mapings er a key
(x) i2e ) - The method is sed b retun the number ot key /value pairs.
(0) values() - gt is used to Create a Coleetiom eut ot n values bt themaf.

cxtends
Linkedtashrab (memat
extends tmplementt

Mab Hieranehy n
tah Map 9+is a bart ot collechion iM Java l2 3t þrovides fhe batC
Java. 9t Atore s the data in
Im plementation of the Mas inkrtace ifh
Cep vlue)hairs. wesa
TÙ Access t e vale one must know 'ts key. This class
teehnque of lonverting a lange
Technique called Hasing. Hesing is athe ame "sring
0m port Jawa util *
þublic clas A
þuatie statie void main( Shing LJrgs) 1
Mas < Aringnteger m
map but("vishel", lo) ;
ma 'put ("An kiti 2oj
map put ("sachin', 30)
tor( map. Euy <shing Dateger> ei mb- eugyet)

JNked Hah Mapi st i4 Just ke tastma sith the additignal teaure of


maintaining an order ot element 'mserkd into ît Hashmat rovided the
advatate ot quck nsertion, beach, amd deletion, but it nener maintainea!
tha hack aned orderot insertion wich the Lin ked HesA eb frovides shre
the elements cam be access ed in their msertion oreler
fage- ss
Êx import Jawa uhl*
þubi e Atatie void main (Sking J org3){
<Sking ,Inieqer> rag new Lheedtast MafO;
mat but"ishal", lo);

System out println(e getkey() +" +egealue());

Thee Mat;-g+ is wsed to implennetim Maflaterjace and Nawigatimtat


sorte d according to Natural
aleng with thu Ats haet class The mab 1s
deing o is keys, or by a lom þaatorr provided at mas creation tme,
wsed
on which cons huetr )s
defev,
ThiS proVs to be an
Value bairs
R iMmport gava util*
þubli'c class A !
þualie cats stutie void main (String LJargs) l
m== new TreeMas
Ma<Shing,Luteger> m
mþut (Mvisne', lo);
mibut (Sachin, 3)

Systomn Gd printla (epetKgjt


J
Hashtable lass mplements a hash table ,wich
Hashtab le in Tava : The object canbe wsed as a key
Arp Non-null
mabs keys to velues. toe ond neheive objects from a has table,the
Value To successtully i im þlement the hash Code ethod anel the
objechs yed as must
ke?
94's re conmmended to wr thu Mab }nkefate
Cq hel wmethod.
þementat uns mstead ot the tasthtable class
Im
Imbort Jara util. Enumeration
Imþort Java: ttil tashtable:
buslle class Malnf
þublie static votd main( Sling [I ang)1
lage- s6
Hahable<sing, Lnteger> s 2 nem Hat table<? (0;
ha.put ("8*, 2)
s-þut ("c, 3);
System outprinttn (" valu e of A:'t volA);
kecka hs remone ("BJ
Enumeratrin <Shig> keys hs. Keys );
ohile ( keys. hasorelements ()!
Omg key keys. nex+ Element );
Sytiom vit printn ("key:"+ *y);
Velue ot A= |
Keyic,value =3
features ot talh table:
() 3+is similar to hautmab ,but is synchroni
() hashtabie tores kyyale paur in hatttable wsed as a
(3) n hashtable Gm objcet asttey thatis
avel ade we went to asioiate to theut hey. hkes i hen hashed
Yesultina hash code is wed as the index atwhich He value i dtored thaig
the table
Dedaati om
þublie class Hahtable <k,V> extnds Dichiomany. <k,v) imþlements Map
<K,V>, cloneable, Serializable.
K’ Keys,V’ olues.

Serialzable
Dictimag
Hashtab le
clonesble

Implemeuts intofec.
(Romferties (UDefauti extends Oclass
(n order to Create a tashtable we necd to imbot it om
a.til
nashtable. hene are vari ous way in whu ch yau Can creak a hashtable.
Ex Hasstable <k,v> hta nens Hesttable <K,>)9
age-s7
Kopertiesclau in zavai The fraperties Clhss reforebeuta a persístont set of
Can be saved to a stram or lorded trom a Aham:
rerties. he þoojerhes instan te vaniable.
Jt belngs to gavautil pachage operhes define the alowing
tatres of roperhies Ctassi
() foperties is a subeless o Hash table
()3tis wwed do moain tain a ist of vadaes wich
in the
Cmd value is also QAng g+ Can be wsed to Atore amd retievky Ahing
data foma he þvoprrtie {e
(3) frobtr ies class Can sbtety 6fher abe fres ist as it% the de fa.lt
ta erticuar key pooperties ia not prescut in He original rujerty ist, t default
pvperties will be searched:
y boberhes object cdocs not reguire external yn chronizatioy Gmd mtijle
twreeds cay share a single proper ties object: Ais
Also 9t car be wsed fo retricve
the þuopeties oce Aystem
þublie cass Properties exknds Hasktable <object, objeet>
Ex dlb þaoperties
username Coder
þasshrd Aemin
Im þort Javautil *
þublic Class A 1
butie statie void maln ( String 3arys) fhrow exeephou
Elenoder radre neus tilereader("db jropeties D;
brokerties þ: men Pojerties ();
þload (reader);

nekhads o fropeorties ? 0gehajertier (Skingkey) (3)


(3) ist fsintshrom out) (9ist (frintloiter out) gettooherty
(s) load (anputsream insheam) (6) load(Reader rade t)
() þrojert;Nome sC)cte.
UNIT-5 fage 1
Aþpltation.
DL

Website Mobile Java is not cahasle for beter UT des"


wehabþicaion amd Mobile App dety
ment HTML
Reactn Andsoid web

frontol
Rresentation Mobile
KeaRAP
X M
T¢cus.

trame work for Ba, amd DL

web seruices - or web PI nyoT


fondalm Desktot web
Mobile,
SOAP boot r
REST Amdsod
React. Anqular
Socket, T)O for frontend

CoRBA
RMI ’ Jawa.
EJB ’ session, MD8, Eaty Beam (Tigiy onyleg eaiy Lage
weght
H£bernake
Sprimg kafka JPA
Rest TAKA (spring (Lghnig)
Sum has foovided 4 ai fos web SerUices.
JAX - RPC. (APL) (Tdhiy)
JAX M (Jdkiu)
JAX - WS (34k|.S)
TAX RS (JAK I.G)
CynchroOUs
JAX- RPC ( API) TAx- M
(wait for some keshonse)
JAX - S
cclint get immediate Response )
Gage
Synchrongusi web se rvices - To devlop Soap base webservice we need the
TAX-S (APL) tollow'r
L SoAP based
Beetbae TAX -RPC (API)
REST based. JAX-RS (JAX - RPC)
Seethe at feren ce
abstraet classes omd Tntertaces not
apr Contain only Contain
SOAP ßased absra
Inblementation
J AX- RP - (Jaa AlI for Xm Romote frocedur Call)
- devlop by Aum

tuis ts for both soat bated ebseruice and Soab baded clie
Lnplementaton: we have to dewnload
JAX- RPC - SJ (by Bum)- but not þont of jda
Geporate d
AXiS-I- Aþache oundation
- Neb lagic Lþleme utation. (GEA)
webspehre hbementation (IBm)
TBoss wpleneneton (AEDHAT)
Nete . A| th above classes Contauns wedl gene tatiom toots anl
Skele to)

TAX- ws (Tawa aþf for Xml webservices) (Soap gplications )


"Easlementation.
Bum
TAX-WS-RI C9iven by Aum but net uly mnpleented)-AI for
dowleadthis' Tar le.
reterence we nead to'searetly wth Tdk,
tis dk 1-6 Jt ?r weilable
kuy Imple mentetion ) net aailable in jdkl.
Meho C
(Apache toun dation ) or Axs wINKS
- Axis
mtegration but aisnot)
Aþache (X# (2t Subbort the sfríng7-slastys4
logic / - Tboss CBy sun) ateynalty
or
nel shahe re web REsT Based
abl for Xml- Restgull)
IAX- RS (Jowa
sum)
jercy ( By
(By redhat) loave)
che cr,Jrome
Yestesy
spring)
asache caC by aba che) (subjbort
dþa che wink c sy abache) (Not Sup þort shring Iitrrraien)
Ssring bott
boot opbication.
(reate shig
Mare
.

UT,MVc War

Java
Versiom- 17. Laguye
pacage Name
Sbring Boot Devtool s Tools are selected
Lam bok
Sping es
To we oggcren
Ralistatie um as
spriny boot afs

Bh anel DL Ser'ce, web APT


We hane to rrpae eb
API
Boot

SoAP REST
shring (Socket, T/o ) Tava.
for sharable ver netwerk
fubie clos Addi tion to wethis Code.
fnt add Cint num1, ntum2.)
ve£d
CORBA, &
|nt r mm1 t num2
’ RMI (ony Jara Can wsc
EJ6 ~ession, MDÉ, BCam)y
NOT
mlkooptrable soyies Hfavy wejgkt
Spring MYC KASKA
Sþing REST KAFKA
Hicbem
JPA
BL’ Sping Boot ,UI’ ngular, Reset Ege-4

Condollex
Data baselayer CRepo)
Service l ayer Ckainess logic)
DTO Laye?
Conhalley amotation for Conro ller Class making.
3bringomewrrk.
sping
ronsach cn
Saim_ core
Aop

MVC

Inversion ot Con bol Aim is to Gchive Loosly Caujoled .


mainJowa.
Aplicaton lonteet
Create Seme Jae iles. S)ringhramwmtocon teat
IMþort orA rmgomewk. tontext.,
lbort Classpahm
Com ioc
Airoblane Jva
BikeJava
Car.Ja cinter tace) Pablie woid yun (Shyine hey)
main Twa.
Atant c);
Baam m key
CaT. JOava.
Pubic cla Ss Cor Jmplement Bygine( ublie class
þublle void Skart () tatte void main (Shimg 4y)i
fublie s xnl
lmteet aC= hew classpadk
System etr pAnln ('Car Alicetin Appicotiom lonkktleay
Sfasred ") ;
gine ney CErgine)acgtbeam ('egines
).mnChey;
bgie.Jara.
ublie inkeface Brgime t
oid btattC) beons. xml: Here
only &MLis beig chonge cd
cbean id - "angine class= "Com. ioc. kar" /bean>
<Ibe>
fage-5

Sþring- ranme wok;- sring is a gteigt tromromek Aueh es Abuts,


becauye it þrovides ubþort to vanaous
baoader sense, Can be
ETB JS P ec, The frameurk,In
ibemate,Topeshy
aetined s a shuctn where we tind sotution ot the
varinut technical
tomeut mekes
þwblems. 3t was develobed by RodTohnhon in 2003 s pring
the easy developmnt ot Jata EE afplicatiom
are th desgu þatterns that are red toeesie
Inversion ot Conhul;- Thee make the Code
ma
debenden ey trom the programming coede. Thy
Yemore
to testamdmaintalh Let's nderilat wth c
Ctass Employ ee
Addrss address;
Enployee O!
address = new Address ): amd Address Gtight
beturen the Employee
2 thre is deþendency cenazio, we do t'ke this
n Such case, Inversion
loupling) En the o} Conbal
class Em þloyee {
Address addresS
Emblo ee CAddress address) f
thisaddress = address

Sing rmewnk, 10. ontoiner


loose (y Couple In
Ms t0c makes the Code desendency "we þroride meta data to the 20c Contain ätur
1>esponsible to nject the
by KML ile ls annt tatron:
Advamtage of defendeney njecten -
() makes thecode eay to best
meke the coce Coupiel do that eay to man taiy.
framewok (o bedefined Templates
abstoactiãn vi)Declavative ubport
toc Container- The 10c Container iA resþonsi ble to instantiate, lnigun and
semble the objects The 1oDC Container gets ntormatim rom theX MLHile omd
work acesdi ngl The maln tesks þeromed by loC Contain er ane
0) to Ins tan tiat the abbi'cati cm class.
) to contigure he oóject
i) to astemb)e the deþenden y behwen the objects:
There am two tpes ot Toc Conainer Hy
2: AphlatinCntext
DependenyInjectien ; Dependlency Enjection CDI) 0s a desigy atterm tnat
doole bo het it Can be easg to mamge
remores the dependency jom Coubled. Sn DÊ technique we
and test the applicatiot DI makes ow code Joosely
we an eþþooa ch knowm as Dehn denty ocku ajter
demand heve cam be variou ways to get ti resources for exOmple
A eoj = ne Alnplc);
in ueh way we get tth
tactuy metdhol:
me
resorte dinctly by Heas neyund Amotter way ik
Aobj= AgethC),
Amotherway,
Context Ctx= new Jitia Context );
JNDI (Jave Natin Directryy Zntegacc) as
lontert enviomat Ct= (Cenkt) che loekp(Javar lomf /envU?
A cbj (A) envirment cty Lookub("a):
Koblems in Dependencyf hje chion (ú) tigutlous ling () Noteasy tor esg
Tao waya to fergom Dehonden y injection in þrng fomewek
By lonshmetor ((oshctor Based DI)
(2) By setir Method ( Seter &ased D)
tine wil imvoke a Constuctor
() Conector Base d I- 3n this ,the on We want to set
repesenting a defenden y
argument frimanily "by typs, followed by
name
resolves ca Ch
Sring
f he atibute, amd index for disambiguetioh jor k
Berniguratiom
þublit cla ss Afbcon
Bean
þublie Ztem iem JC)
eturn nes Zhem ImpllO;
Dbeen store )
þublic store
Teturn new Stor litem ))

loniguration
B amo tatio me'cales that he class is a houte ot Bean
the cla sSes
definiti oms: we cam olso add it to the maltiple Contiguretion
define a Ban it e don'bAbccity
we wse 8 beam anotation en a metod todefault to the ne frod name.
a Custonm name, then the beon name nil
Contigurton of the Beay tr oML Cmtigurations.
to Ceale a
Arnother wa
<beon ia ="ikm 1" Cas:"or bac ldunf stue. IkmImþli"s
< bean id = "store class: "org baeldang Store store
< Cons bector- arg pe ="Iem Imbl ihdex "o nome'Itm"re
Mitcm>
</bean
for setter based DT,the Cntaner will Call seHcr
Kage-7d
(2) Setrr 6ated DI
Coshetor or n0-argumnt static
t our class alter in voking a n0-ogpned
het s creae his Contiguretion wsing
factoy mehod to nstantiate the bean
ammotations!

þrblie stoe store 0f


Store store new SfoYe C)
Btore setitm (item X0):
etun Atore;
We Cay also wse xML ke his
< beon ld: "Atore class"org. baeldungstore.Stoe >
hame "mret="ihem1' /
<poberty
<lbean7
we con Qom bine. Cunsnector based and settkr besed type of injection for th
Corsetor based
bome bean he Spring docwmentation e ommas Hter 7 mjection for optionl
blsed
or mandaly deben den
Injection cies, and se

AOP- A0P is aa fovgrammirg fandigm hatat ains


fongva mming jaandigm ains to incrak madularity by
the separation o crosstuting- loncerns: 3t does this by addin
allo"aisur to exsti"
additiomal existing bode witut modityng the code ts ely
nstrad, he ean deelge the ne code ond the me behaviour sepuatelt
Let's Atart by adcing S AoP Aboony dependen nthe pom:im:
< þarent
spingtamehvok boot </groupld
<grontid> 0g þring-boot-starter-
< artijact 14> % þareut <l artijact Id>
</herent
<dependencies>
<deandeny boot <igroupsd> Ia>
<grnfia gspringtramevork
sþaing-boot-A avter-ao5< /oritact
<artifactfA>
<jdeponden
</depndoncies loint cat Qduice
Vaspeet Cote
Yreçra
exccutio

Join þoints
"ge-8
togic.
) Bussiness objcct- 9t is a cass that has a nomal bußiness
þublic class Adder !
þublie nt add (into, nt b)

here e ane not lag anysing velathel annotatins.multiþe


ot Cumern that cuts acoss
(b) Asþe ct - An aspect is a modulaization loncerF
classes uniied ogging Cam be am exomblé of such Cross-Cutting
Con be
þublic class dderA}terRearn Asfect
private Logfer Jogger =ager factrny get logger Ctuis-gete lass):
trgk thrws Throweble 4
þublic void afterteturn Cobjcct etum value )

hoint duzing the erecution of a boogram,kuch 4A


Jointpoint a a foint during
(c) Joipoint - AAJointpoint of'an exception Jn A0f a Jeinpoint
he handling
the exéution of a method onexeution
alays brsnts a metuod motch an Advice to be. appliea d
C) o itut- A þobtat is a þredicate that hel the Advice with
Joinpoint he
we ofen
ofen awsoate
ansoc
by an Ashect at a banticular mMatched by the Bointat
Pointcut ex}ression, aneisit uns át ony Jointpoint ata partiouar goinboint
action taken by am
an aspect
(e)Advice- An Advice ts on Marroumd'y "before" and "afer".
Dierent tybes ot advice include
modeled as an inlercepher, maintaining a chan
In Shrig an Advice is
ot intercesters aromd the goin point New
New let's look
le's look at ho e can etz
and Aspect -
) wtring Business object a Aspect wh an Afkr-Retrnjng advite
wie a Gminess object to
Belss is the tontig es Adder"/>
<bean id="fonle der classz"ogbaeldung ogger.
<beon id="dongferRekerning-Acfec+' clace-"org. bacidung. Jogger Adderakr
vekmts ject"/>
<oop: tmtig
<aop: aspectid= 'aspechpontref="do hfter Reteminghsject°>="exeution
<abp: þoivteut td =" cutAfhr Rekrnin. oprsion
(* o8 baeldung kogger Adder +. *..) '/>
<aop:a}tr-returning netnod A}terReturn" metumning
="reirnvalae' fointat-"ref" point cufta}terketurming'
defining AOP Telatecl
<laop: asþect we Can we tag ao.' Gntig tor
Cont'guration oihin the tontig tag, we define the
<laop: lent lasi that e7resents on eshect
age -4
Bean Alopes! Lohen you create a bean detinihon,you cCreake a recipe tor (reating
actual inAtomces ot tne class deyined bt that beam definiHion The idá that a bean
letinitiom is a recipe is im þorant,beause it means hat, as wih a class, you
Can ceate
mant osj ect ihs ton ce's trom aa ingle recese:
you Can conHol not ony the vaniou debendehces amid onjiguration ela es that
are to be blugped nto añ obje ct that is Created tom a parhular bean detin on
but also (onal the scoje ot the objccts Created'
For exomble, to torce sfalng to paoduce ane bean istance cach
tme oe ib neded you Should declare the beam's beope attri bute to be
sfoing tokon
þrootype. Simiaaty ,i you want you totun th same beam mstan ce
each ye time one is needed, Should detane the beads Scobe
aHribute to be slngle fon.
The tolloutng toble describes the supported scopesi
object
Singleton-(Default) scopes a stgle bean definition to a single
ach Sfring l0¬ Container
Instonce tor each object
any number ot
þroBoty þe - Scopes a ngle beam definitiom to
ntom ces Becycte oj sigle
tquest - sco þes a stngle beom deinitiom to the own nstance ot a
HTTP reguest That is, each HTTP reguest has i
definition. nly velid
Bean ereetd ot the baek o a single beamicatonlon
0n the tontext ot a web-anare Sbri text:
a Angie bean defihom to the lijecycle of an
Session- Stopes
the Conhext ot a web-qWare
HTTP Scssion omly vali dd in sing
Pþþlicationnlmtxt
beam defin'Hon to fhe litecyc le of
Aþli cation; Scafesealya Bingie
vali in fhe Cntekt of a veb- geme
a ServietCon lext
lonteet
anrar Spring Acplicltion
websocked' sope a Aingle beaM definihon to the fecyele of nebso
cket. ralid in he lon t ot a web-awane Sprlng AppMic afion
lontet

() SingleBon Zope: - when w detine a bean th Single ton bcope.


Hhe lon tainer Creates a b ngle nston ce of that bean
AlI the requests tor that beom name ill return the same bje ct
wicn is Cache d' y moci}icotlons to the cbject wil be ref te ct d
in al weferen ces to thu bean The scope is the defautt valuei t no
ofher scope is dhec}icd
Lett creae a feson etiy to exemlifg he toncept ot seofes
{age-lo
publie class ferson
privae Shring- name
I/ Btondard Cons uutor, getter and setters
1.
wimthethe
terwads, we define the becm with Aingefon scape by uwing-the
OScope anotation.
@singialon Ostope ("Singlekri')
þusle RersOn person Singieton ) !
retun nes erson C)e

we Can alao we a Conibamt Instead ot the Shing value in the


folisuing
manner. Cohe.. Sing leton)
@Scope (vaue - Conigurebie Bean factr sthat turo eobje chs refering,
Mow we Co Jproceed to wile a test that shows
vaueS en it only ene of
eren
to thesame ban wt| hare the same
them chongestheir Stote, s thy are both efereneing thlsome
bean mstam ce
riake state tial shing NAMEaJohy Smith
Test
þublie void givenSingleBon Stope._ohensetName thentgualNomes)
Applicatiom Context ac= ne ClasslathtmlAplication lonkext ("Sepe xml):
Rerson A= (lerson) ac getBeam ( lerson Singletn U
ferson &: Cferson) ac et beon ("erson Singe ton )
AsetNome ( NAME)
ASsert anert Fquals CNáME, k9etNome ());
C(AbstractAþþlication lontxt)ac ). Close ;
definihion
The &eope Nmlfile in this exomple shuld con tain hu xme
ot the beans uted
<bean id e'resonSingieon" clacs ="og baeldung Scopesferson
tope =hsingle ton />
(2) frototybe scopej- Abeon with the pooto hyhe scohe willrekan
dijerat Intam ce crey time Jt 1s quested tom the Con alner.
3+ ic dcg ined by seting th raluc foohohy pe to the 8scope annotation
in he beon defin ition
Oscope( frototyey
pubtic feeson forson þaolobybec){ 6eamactoy ScOPE PRo70TY PE)
rtun new Persen);

You might also like