Usngremaes yuan reuse esing
Teatwestoensingcassetnoutonnveg
Ryonandngntvough te nndee
seraimnetnee mpemaned 28
,
sates,
,
t
sémensena
,
eansepartgteactrontha tal
~ vngabracon yuseneony esi
+ inn abt eet by
t
t
7
t
1
coring Cnt erent
1
‘
7
7 Pymearsman on MoS means
{ome stanyinguhicsac maple
forms ced srplynepho,
1 treampetercenetems yey ke
miles ak 5 poymo7sn.
+ inev mereve totes!
‘omarpem-staepoymorssmand
‘imamcpmopir
¥ tye ore rhmention
oyna
¥ Opec veoxangnatederoetng
‘tcacnctr vedere at
seorpisatnsteonynorton
'
'
+ sovensysherrownpeymertonst
frtretctchedrene
amon
+ tatodoveringthebescxarlact
‘ymamepmepnsn.
ni
epee
spent ge in ed,
‘enc =rer sce
seacoast
'
7 aneigotataardoertonsiobe
pestormedonthat atta sng tie
fcapatonin nn conbe scheveby
‘egos net
lepers wnacegon tose
seedy dengan
‘orale ste on pow pe
t
pbesosesumere rare)
'java.lang.String Methods
Strings Basics
What are strings?
Strings are nothing but the sequence of
characters enclosed within double quotes. For
example, "ABC", "eye", "123" otc
How strings are represented in Java?
Tn some other Fanguages, strings are
reprasentad a3 array of charactara, But in
Java, stags are represented as objects of
javatlang.String class.
How do you create string objects in Java?
‘There are two ways to create string objects in
save
1 Using String Uterals
String 21 = "ARC"
2) Using naw Operator
String £1 = new String(“ABC");
String £2 = new Sting("12");
How string objects are stored in the
memory?
‘Whenever you create string objacta using
string iterale, those objects wil be stored fn
string conatant pool and whenever you ereate
string objects using new operator, auch objects
‘ull Be etored in normal heap memory
String constant pool i a part of heap memory
which Is especialy declested to stare sting
Objects. 1UM allocates poo! space to an abject
depending upon its content. There will be no
‘wo objects in the string constant poe! with
\Whanever you create a string object using
string taral, VM first checks contont of an
object to bo created. If there exist an objact in
‘the pool with same content, then returns
reference of that object. T dowsn’t craato now
lbjact. Ifthe content & different from the
existing objects then only & creates new
object.
Java.lang.string objects are immutable :
java.lang.String objects, ether created using
Sting itarals or using naw operator, are
immutable in nature. That means, onca you
Create a string object, you can't modify the
contonts of that object. 1 you try to modify
the contents of a string abjact, a now string
object wil be created with modified contort
ccarat() replace()
comparetot) replaceAlt)
coneat() replaceFist()
contains() som)
contentequals() subsequence()
copyvaleor() substring()
fendawith() ‘techararray()
startaWth() toLowerCare()
equal) teUppercase()
fequalsignorecase() | trim)
Format() vakieot()
10x01)
laetindoxor() Java 8 :
Itong) Join)
lsempty()
Fenath() Java 9:
smatches() chars0)
codePoints()
javadang.StringBuffer Class
java tang. StringBuffer clas fs used to create
‘mutable and thread-safe string objects. Tn
father terms, this lass Is same as
Javactang. String class except Rs objects are
mutable.
1s not possible to create Stringauffer objects
ising string Hera. You have to use new
‘operator to create Stringauffer objects.
mportant Methods : append(), Insert),
replace(), delete(), reverse(), length
charat() and substring(),
Java 11:
iselank()
fnes()
opeat()
stip)
stripLoading()
striptraiing()
Java 15
formatted()
strigindent)
fransiatetscapes()
gaya 12:
indent()
tranaform()
ddescribecanstable()
FesolveConstanDes()
java.lang StringBuilder Class
java.lang. StringBuilder dass fe used to craate
‘mutable and non thread-cafe string objects. In
‘other terms, this class Is same as
Java.lang. StringBuffer class except its objects
{are not thread-sare
1s alo not possible to create Stringbuilder
fbjects using string fRerais. You have to ure
ew operator to create Stringaulleer objects
Important Methods : append(), Insert),
replace(), delete(), reverse(), length)
charat() and substring(),
String Vs StringBuffer Vs StringBuilder
‘Objects can be created elther
string StringBuffer
‘immutable Mutable
Thread-sate Thread-safe
through string eral or
through new operator
Objects can be created only
through new operator
StringBi
mutable
Not thread-safe
Objects can be created only
‘through naw oporator,
Objects are stored in string Objacts are stored in heap | Objects are storad in heap
constant pool as wellas heap mamory only memory only,
memory.
Slower Slower Faster
String Intern
‘String Itarn raferst string object in the string constant peo.
Inteming Is the process of creating a string object in String Constant Pool which wil be exact
copy of string object in heap memary.
Intern() method of java.lang.String class Is used to perform interning
lof heap string abject in string canstant pool
creating an exact copyBEE war au eli
‘Array isa fixed size Index based data structure
containing similar type of objects
For example :
intl] a = neve int{10]
(nf an array of 10 integers)
charf] ¢= new char{15]
(aeis an array of 15 characters)
‘StringI] = = new String(20],
(is an array of 20 strings)
‘arrays in Java ure zero-basae Indexing to store
‘oe elements where first element is stored at
DO ingax, second slement at 3 index, thie
slament at 2” index and 50 on,
Ine] Intarray = (24, 15, 37, 53, 17)
> indices
‘There are two ways to declare arrays in Java.
are throe ways to intlize array
laments,
41) Toitiaizing individual elements
Intl] ntarray = new Int{S];
intarray(o] = 21;
Inearray—t}
Iintarray[2]
Iinearray[s}
inearrayTa]
2) Passing
operator
elements ata time with new
Int] intarray = mow int{1 £24, 13,37,33, 173;
3) Passing all elements at a time without
new operator
intl] intarray = £24, 15, 37, 93, 17%;
‘There are two ways to traversean array.
Int(] Imtarray = 424, 15, 37, 53, 17>;
1) Using for loop :
for (Int § = 0; 1< intarray Jengthy; 1+)
ements
2) Using advanced for loo
for (int
€
intarray)
‘System.out printin(
>
Multidimensional arrays can be defined as arrays of arrays.
‘Two Dimensional Array :
Int QL] twobimensionalArray = <1, 2, 3h 4, 5, Oh (7, 8 5
‘Three Dimensional Array =
I i srecinesisnrny = 660,29, 5.9,. 0.89),
(do 14) 12), £43, 14, 15}, (16, 17, 18) J,
{18,20 21F, £22, 25, 24), (25, 26, 2773 92
java.uti.Arrays classic an utility class which
Contains many static methods to perform basic
operations on an array.
41) sort(
fed to sort an array.
2) stream() : Returns a stream containing all
laments of 29 array.
3) spliterator() = Returns spiterator of an
array
44) setAlK) : Iniazes 38
array.
ants of an
5) f1N() = Fils the gWvon array wth the given
value.
6) copyort) : Creates copy of an array.
2) astist() + Returns 2 Ist containing 38
Slaments of an aray.
8) binarysearch() : tis used to search an
array forthe given vahe
| Easy to use and implement
‘© Can old both primikive types as woll as
reference types
4 Faster data retrieval
Jagged Arrays:
Jagged arrays are also multidimensional arrays
Containing arrays of different length.
14, 2.3%
£4, 5,6, 7%
8, 8, 10, 41, 12} 32
intlI0 jaggedAcray =
Ustestring> lst
Arrays.astist("One", "Two", "Three", "Four",
"Five"
Arrays.streaminew intl) (y 2-3, 4, 53)2
Intl) intarray = new Intl] (4, 2,2, 4, SI;
System. cut pritinintarray.lonath):
Hfourput = 5
“Anonymous array fs an array without reference
new intl] 1, 2 3, 4 SP
‘cons =
© Fined size
© Not typa safe
© No in-built methodsJava Exception Handling Cheat Sheet Gjovaconceptoftheday.com)
Ba: Types Of Exceptions
Tit eran? Tie a ps oT
Lcntonlsanainemalcnatonnhichocais | 4, cheidtuepons tte eacestons hare ceded dat comsaton st
Sig eedindtipagier sn dat | te ee Se er ocr
fo hunberomttaagtinthmatcacetha, | (epaaer ome TRaiEEERS
Inravindosontondstxcapbon, Story dace competing Tey ac a henalS aE
iatcaceato aerator, eras saphtincueme Taare inrasmune
Screener OaoMemsyeorsc. | HERES SSG wepey amir] tes ese BST TORT
Scot ning v0 Basse |Snee e
fxepnin me a handed cach on | nhc aFN Gh eso ROTSRSESCR
mares, Micuiesaiganennimeceeoaae | maul iewmciae slcimatnorae
shore nial nee
© SSS cin nea SE water,
Tssckconthastaemmes wither —_| [HEH cman Se stunten
throw exceptions dunpruntine.
{atchecetion )
Hierarchy Of Exceptions
javedang.Throwable i the super cles oral ype oferavsand exceptinsin va
Th bockhandies the exceptions thrown bythe
| ty block hae two sub larses
fay 1 Javaang.trror: ite the superclass orl types of errors in 0.
‘fellate shen aneosicirisecan 2 Javadang.exception: 1s the super cls fr al yper of exceptions vs
Exceoton Is thrown ornat and thrown exceton
‘ules To Follow while Writing try-catch-fnally
Blocks:
ty cateh and hay blocks form one unit
{Ich blocks, finaly Block's optional.
the bloc.
+ Afthere are mutile catch blocs, he onder of
Ghblecs musthelron mostspedlete
Genera ones lower classesin the lrarchy
ff exceptiens must came ist and higher
‘asses ter
Mtrycatehinaly blocks are supposedtoretuma | wimielamatacetin
vabe nae)
Cate blocks may ormaynotretum sale throw'Keyprort irouis Rerwire
Winaty block does notretumavalue then | Throy Raynor ured to tow an ercenion ‘rena Keywords ueeao spec he exceptonstat
tothtryand cach blocks mustretim avaue, | expe maybe thrown bythe method
hay Boek overtdesretum dues om tt
sri catch tock, wy raturatype method samearamete ft) throws
nay Block be sivavs executedeven | ception at “ :
though ryandcateniock are retuming te throw instanceof hrowabierype: t
cont > some statements
‘teh instanceotTiromableType) ,
Frequently Occurring Exceptions | here exception ft ithe it of exceptonsthat
é method mayehrow excentons muntbe seperated by
"Ty nallpointerbxception occurs when vour comma.
spplestontsesto acess nil abla
hor, instanccOfTremableType must be an object
2)arrayindexoutoteoundsexception occu's | Btypd mraable or subassrTiowable
Invatléngexie index pester than te ray length
or witha negative index.
'8) NumberFormatException is thrown when you Try with Resources,
are ningto converts sting ts numere vuelto
integer Moat, double ee butingut stings aot
vad amb. osed, No needte clea the resources exp. But Java 7 try wth resources has one drawback I requires
4) classNotFoundexception i thrown amen an | resourcesto be decared local withintry Bock t doesnt ecooniz resources celaedoutié the tr bleck,
Sppication resto fonda cles at rn ime bot he
‘las ttn spacttad name notfouncin tne
dlasspath
S)anthmeticexcestions thrownwhenan — |___—Beforelava? ‘| Altera ‘ater va
Sisal thmesccononatcosa sn
conto Terns Ticincrmenies ORs a | Txterawesiee
$s txaton strom wn an apatn sitemaps
times seruronomteraing thie | { spre cea
‘abae ' Mare of
Tetescstercamion ces whmancberot | renraian ae ON emara
‘one type cannot be casted to another type. F es =
$ 10excnton ocr when an operant
seine
2) cies underror stro hen
Rite Sstan ae ousthe detonate
21) stachovertowtror ia rntine or nh
‘eis unsere sbappran
‘outa cng the meted ect
Ty with resource bodes are introduced rom iva 7 In these Hacks, recourcr ured in ry blk are ako
‘That isu hasbeen rasohed inva 9
ath cating i d
(cschecagtochaetiny — | ea bxepne
oneenepesrecety |} 0
Iesehectore beet,
ees ond ,
nerds cress
pacar
(Moret derePees ekcats oss
2a Clectn Famanorks a framework hin proves some pratnn! cess and ieraces to store and mana the ro obec, Usa a8
‘lection framework, you an stre the je eo ast ef ara Sel or as. Gurus or ara Hap ad perform ri operons tka adding removing. pasts,
‘Why Dav Collection Framework?
aa aeaye arated tsar he croup eebjac. Si, arays are tha aba. You can chang tha an ofan ary ana ie dfn. enue ete a
‘textes wna handing the aro Oebects. To overcome ths drawback ot arrays lava Clacton Framawerke Mwai 9M 2% 3.2.
[A te cacses ad interfaces robtod to v2 colcens are het fava. package Ut, Set, Quoun and Map ae four top lvl ntefacs of 49 calecton
{ramawerk a thse ieraces oreagt Map) mer trom ova Cobacton evertace whi the rot mest ace the 43 section framework
tro otro “tee ‘oteo
pecs "evens are aaced romans end | " atneeokates "| "kapnuy pastas en oy
+ Sie pti ins {Sine to oe une and Eetimmtace dos ot nave ne | Setocatad th 3 an
removed orratived fom any “_ * Interface jt applies estedon | het Colton terface.
siaeor postion vara an iteser | Gia le ypaty FO (Fstn | onmudads So tak dntete
inde Fist) Spe & eae Souatwe, | Slmerts re aoys svoced, | Rp MpIeMaNTaONS
Popuir Implementations : | popular implementations : | Popular rmplementations : + vatsap,Unkeaohtag nd
+ faraye ctr And tnkaast | « wrortyquve,avrayOeque na | « Hoohsa,unkeahoshset and
erasures UUnadlae Gripen Ut cls) |“ Trees” nternal structure =
Anternal structure = tnternl structure = + Hashatay <1 tena uses an
ArrayList: eral wos ‘Stave bates wna oh
ae ceric Sere” | PintyQuaue ci teaty wee | + Manhet: ntraty wee | Raa wn Id ett
{inkeaiuesmap = Same a2
‘icin wut actioaty ures =
ity et at
+ nop ay ats Res
+ Prortyqucue =e ated ‘coment ‘asap = nly one mut Keyan
‘Mal Elments = 1 AreayBoque Si stow + nediaehst :ttxinum one |" Con have oui ha ate
na cement «+ nkeassap ony no ail key
Arraytist ses ‘bwpticate Eoments « Treagetonntaton vena |” ana can have mule i ake,
Uaedtist Fes Soca tai ing thay bt con have
+ ArrayDeque = Yes Duplicate Elements : rmutiple mill valves.
eet onder or ements: fist od wpe Homan:
ees «rrrayag guns xo | eth + agen tk
‘nt Se | = a
Order OF Elements : ‘no Comparator is supplied, ++ LinkedttastiMtop : Doesn't afow
tera: reer ocr | * Heeger ten | same te ce owe | Soe nce
ese meena tres Sal diene
Cineedistseercen Orr | Symes resin tapped Comp * Keysbatcan nove pete
Synchronization = “+ PriorityQueue : Not ‘Comparator is supplied.
‘synchronized Order Of Elements :
1 ArrayList : Hot synchronized “+ ArrayDeque = Not synchronized | Synchronization:
+ Vector : Synchronized pare ‘+ HashMap = sie Order
TENT | sean | iat iene one
Performance: ++ Priorityueue : Insertion => ‘synchronized according to supplied Comparator
+ peng marine spy er | MORE Setne> eran. | « owtet set crctria | a wf ee Few
ral aray tnd eon) | * Aceytoaue ewe 0) | Perens syncniation =
Seah wena | AS dinsamrelnarwis
See Ta Pe SS, | snasman amore
ara, El be 910). wren to use? 2 nase i acaeaeee ine
+ Heo e toute | remmouae uc totnyen | "Sree das «espns
“syrchrorization. | some spacific ordar. + Treaiat : nsortion -> o(log(a)), | Performance:
ee enon > acy, |. hetyockisaccinuan as | * omacl’? Smo eat
Sesh’ | * Mere Sexe) «ey ttn
:
!
“peepee ieee Sone dence wt ty
+ Trettap:rearton > of)
+ nkeditnchsat : usa than |" Ramoral-> lias esses
re Ent pereee eit senare e |Si)
"Sd remaval are recded ‘See |
rue. sean cer + Haha «Use yu wan ty
Kye gas nto any or
UUkecatinep ie yo
+ Treelop: uso whan you want,‘What are control flow statements?
41. Decision Making Statements
2. Looping statements
3. Branching Statoments
Decision making statements determine which
statements to execute dapencing upon the
outcome of a suppiiod coniition or an
expression,
‘There are two different decision making
statements avaliable fn 25a
a, statements
2. gwitch statement
1) if Statements
12) simple if statement
if (condition)
«
750 of statements
‘U7tiese are executed only ifcondtion TRUE
»
b) if-else statement
if (condition)
«
U3et of statements
{pthase are executed when condition lo TRUE
»
se
«
fst of statements
{fthese ar executed when conditions FALSE
>
©) iFelseif Statement
it (condition 2)
«
730 of statements
{pthese are executed condition 11s TRUE
»
false (condéon 2)
set of statements
{pmiese ar executed i condition 2s TRUE
2) switch statement
‘sitet (key)
«
case valie_1 : Statement_1;
breaks
case value 2 : Statement 2:
break:
dafauie | Default statement;
break
»
ase
1/50 ofstatements
‘Ufthese ar executed ial conditions are FALSE
y
Control flow statomants are the statements in a program which control the Flow of execution ofa program.
“There are three types of contral flow statements in Java,
‘Looping statements are used to execute a set
of statements repeatedly until supplied
Condon becomes FALSE.
‘Thoro are four typos of oop statements in
ava,
forloop
vale loop
‘do-utile oop
for-each lop
4) for Loop
for (nivalzation; termination; inerament /
decrement)
<
{1)52t of statements
>
2) while loop
White (condition)
‘
{Set of statements
{ithese are executed unt condon ls TRUE
>
2) do-while toop
0
{et of statements
‘These are executed until conltion fe TRUE
2
while (condition):
4) for-vach loop / advanced for loop
For (datatype variable. Name array /
collection)
<
1180k of statements
>
‘ranching statements or jump statements are
Use to transfer the control of execution to
some othar part ofthe program.
‘There are three branching statements in Java.
1 braak staternent
2. continua statement
3. return statement
1) break statement
wi (condition)
4
{[15ome statements
IF (condition to break)
£
break
>
11S0me statements
>
2) continue Statement
wie (condition)
<
{1some statemants
IF (condition to continue)
«
>
continues
11S0me statements
y
2) return Statement
return type anymetnod(pass_argumants_
Here)
«
{15ome statements
return anyThing oF Nothing:
»BEE Mead
process. Thvaad Mat Hs own pat of execution
Fs process process can have matte
What Is process?
Process an executing hetanee of an
Sppicaton. For example, when you double
{ek MS Word ian in Your computer you start
Srocersthat wi run MS word appa,
2opcaton i program we» esa 0
Mord Gouge Come, 2 eo or aso paper
‘nat is mutttnreaded programming?
1m a program orn an appeation, when two 0°
mora tread> aceite tel eae
imutaneousy then eled matihreaded
programming, va supports mutinreaded
“There ate two ways to create teads Java
1) By extending Java.nacthread class
ase Myhead extends Tread
t
over
Puc void ant)
meso te task to be porformedhare
>
>
‘ereating and starting myttrend
teed myriad = nw MTs
2) oy
Implementing javatang Runnable intertac
ass MyRunnatie Implomenes Runnable
‘
overite
pute vo ant)
«
meso te task tb porformedhare
)
=a:
5 388
are two types of
1) User Threads
‘ha appeeaon wer. Tey atehigh Bray
freadas WM we oo itu ure throne
2) Daemon Threads
‘omy cresteaby the hi these tres de
[hays funn background) Those treads are
‘Stadt perform some background take Bee
roy trends. WM wi ot wa forenese
SiS al wrens ch ek
MaN_ PRIORITY
NORM_PRIORTTY +
2 defines he normal pony that thread can
fave and Ws va
1 defn the highest pity that 2 theead can
“he dau pany of 2 trea is came ae that
rts parent te tan change te prorty of
tecad t any tne ening satPrirey) method
“Thre ares tread states
NEW, RUMMAGLE, GLOCKED, WAITING, TED
NEW # A thred tl ben tls state bore
tng start) method
RUNNABLE : thro wil be this sate
srr eating oe str) meted
ymca rathodock ors Ure ll Be
inthis sat #aensoce etirs
WAITING + thread wil bein ens sate when
wnat) oro) method bested
“TIMED_WATFING = 4 tread wil bein this
tate whan seep) or wat) wi tneOut or
Join th nett cates
once Rfinshes Re exacitions
creating and starting MyRunnable
meee ree nab
stort
‘Tough syacvonaaten, we an make me
‘Syetronzaten ft Javale schived using
Synchronized keyed
nen method or lok s declared at
eed oy ara thand can eter io
nt cate object eck or mon
‘Any teead wants to ante nto synchronized
Imathoas or bbcks of any obec hay
ust acquire object lock ssocatd wth that
‘nject ad lease te lock after they are gone
si he xeon,
mcrronced void sychronzetethod)
e
syeereonzed Method
Dennen Javaie 3 eandton neh curs
‘when two or move eas pet blocked wating
Toreach other for anfite period of tine 10
‘elsae the rarcurcae (Loca) they Nad
Lock orig and ook timeout ae wo
tock Ordering #n wis madiod of avoing
the Geil, sme rnin oes sped
Lock Tinout £m santher deadock
Drover matod in when me spec the
time Fors tread to aque the lock. fas
to See te specie ck ne genie,
"ear after sone ne
start)
ean)
steer)
"mash rn eacng end
me, Wnan ta tread gaia forsee,
(des nt release te leks hd
Joint):
sing hie method, you can maka the curently
fxecithg tread to walt for some etor
‘reads to Fish ther task
vita)
1 causes the crrey xeciiog tread to
amporaray pause ts execution 2rd aw other
"vende to erect
wait) =
I makes the currenty executing thread to
eles the ek of the object a sk nl
Same car tread notes
notty()
1 wakeup one thread randomly heh Ee
otiyac =
he joc stock Bu, only one thrase il
equa bok of he cbectdaperding upon he
ret.
Isalive()
Ipaemon()
or urer thread
setbaemon():
Ie sets daemon sas of thread
correntthread()
1 reture a reference corrnty exacting
Iotorrape()
1 une to inerrugt a trea
Istnterrapteat
etry)
returns 1 ofa ten,
getstated):
Ie returns current etate of red
‘getwamet) and satName() +
attr and setter Forname ofa tren
getPriorty() and aetPriority()
Getter and etter For pithy ofa thread
getThreadéroup()
1 returns atv sad group to whch this twead
Belnge
{ng wa, neti) and raehyal) methods,
ri) Tas met ie he cri
‘his cae wte t some oer teed
‘equras the same lock and ett fusing
ihr nt) or ety) methods
say)