1 2 3 4 5 6 Merged Java Notes
1 2 3 4 5 6 Merged Java Notes
Class Test
publ'e sfafie void main (shing CI aogs)
Tavac Testlass n
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
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)
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.
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)
2°
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&
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.
(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
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
Corating otject
tut = new tut ()°
teutie
Non-s method
Calling tou
(overiding E,
Cs Parmt f 7S t a c Meth
Static void Showl)
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 ()
).
Caled
Re cursion in Jawa , A mehwd that Calls its elt is ecursion.
recursi¡n method and this te chniqu e is knon as
method-name (harametors);
Sunot n matul numbcrs by nelusion.
Class A
2 Syste m. tensolc )
(n) mpost achagee
Synter! Cosole cjectname = Syctem Console ()
fage- 18
Ex. Imbort Jawa. io. Cendole ;
class A
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
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)
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
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
Class ß extends As
Static Alock,.
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
Cass D extends e
Clas &extnds A
1nt a 220
class s extend A Void Show)
Systemm eu print (a)
System oud printn (super a) :
Class Test
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)
class extends A
6()
Syper ()3
Systeny ont. þrint "Hello BI
Class Test
þubl'e Static void maun
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
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
Ax A
classA
Vaue
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
Clay tet
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 )
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
NStSupbrte
m Show ()
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)
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
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');
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
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.
mal
Vaniable finalty f'nalize
obiec.
Keywrd class Chn sed ahat method
(Énol) method
0 allocate d is releahed
atch( sinilize
Cleon ub Code.
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
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
Rrocest
babed
VThread(mit orendtng)
bahed
Dead
lage-to
= ne 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)
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
extonds| mplements
T
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)
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);
frontol
Rresentation Mobile
KeaRAP
X M
T¢cus.
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)
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
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
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!
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)