0% found this document useful (0 votes)
14 views25 pages

String Literal

The document discusses the Java programming language, focusing on string literals, built-in methods for string manipulation, and object creation in memory. It covers various string operations such as concatenation, comparison, and character manipulation, along with examples and explanations of built-in methods. Additionally, it highlights the immutability of string objects and the importance of constructors in creating string instances.

Uploaded by

kaaushick10
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)
14 views25 pages

String Literal

The document discusses the Java programming language, focusing on string literals, built-in methods for string manipulation, and object creation in memory. It covers various string operations such as concatenation, comparison, and character manipulation, along with examples and explanations of built-in methods. Additionally, it highlights the immutability of string objects and the importance of constructors in creating string instances.

Uploaded by

kaaushick10
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/ 25

sloelas

Jiteral:
Strbg characters
gup
mulfvalue data which wfl be
(&r
enlosed
with doubbe quotes

Not
Aitesals ill
longuage
Jo c lanquage ing
be sored bi ustng aviay
\o

leltkyoire
uteral
Java
stbred by wsing ccct.
Ox 2

built-fn
wetaods
rteral stored
Sinca tt
bave beilt-io
Can

t perlovm ta Opeva on
terals

ot:
Java poufdes threa 2vent
atore
bluspht
stng iterals.
Creata
Obfecta
Bult-io class:
To Creati
to storc
data

3 Strfng Butlde
Claes :
Sbg
a nal claes culich
preunt Praide jova, lang pachage
Ce'e Can Create

tuo
Stinqliteval directly
kyuot.

By wang Shrîng lteral directly


st
Liteal detly Cons tent
bo

el
Cseatad ttie
area and that Objecte will be

netuo ed. HeapArea

Jox2
shie
shing
Hello / soh(S,);
Bye / s.o ph
Overideo
Nott:
fnt t e acteual
Van iablo,
Jnstead
data Ovtrfden i
Beceese
ttle stng claw.
S. o.plo (hlelcae ); OX2
scp

heap
S,

3) stnq 3, Ac' S Ox)

strig S3

str S3
Sgp
S.o-pln (s, S; /te
Sopln (Sa - Sg?; /t
Note :
whenever We are ttie
sty
uteral ba<ore creatry Obfect tte
Jvm wil! check Constent
Pool aea Obfect
not
a prent
it s nof
present. Obfect will be
Created and tu eference netuned
else Rnisting Obj eevenaCrechd.Meturmd
wsll not be
object
Java has
ewith
Vey
strang to
aory managenant
apaaly
ofdata
4)
-"ABe
shing
Safng
stv ing Ox) OX3

S3 -A8EFG
Ox 3)
Sopln (a, - );
Heap Area

5)
aut.printla ( "Hs tratanao bject)
Ox|
rue
clots

) By tg new

to
kyud byuovd
Ío Order
weed
Cret tte
to know Costctors
st+iy
claus

Jmpor tant Costctors clan

Sbngl)
Sbing (St tny str)
3. Strfng (chalJ ars) Convert to

stfng (byta CJ ar)


sttng (stng Bute
6 Stfng (Sthtnq Buzlde b)
STp
Fmple:
nauy Sthq"")
8 hew ("H"D;
X2 X3

Ox3
H

Joxa
hap ara
S2
Ox3

S.opla( Biquals (22));


H
/te
Note:
whenever wease
Creatngtt
ew
eyaond, obje oill
be Creattd in CAoea.

aso Over olen

claus.

basbCode C)
Overriden
stig
clas.
Example:
&opln (s, bashlode c);
Sanee

bashtod
So.plr (2hashlod));l 16 3s 4|
Charactevta ts
obfet
natue,
Smmutable
do auy modil'catm
data hew Obfect wtl
tte
Creatd.

oaloelas Ox3. OX2

Frample: Hell14
Helot
OA4
AeF)

Ox s |ABcDe
sttng
string |ox6

ComporeTo ( da fe ct )
fot.
rebuvnlg Csmpare To ( Sa);
8,.
return esutt .

uturn + ve
as eult
Veturo-re
S, S
Opavator and
Betueen +
Drenu
Compare Comcat (Sttng «)
+ Concat (st*fry
) "Hello+'H:" " He llo. Concat ( " ) ;

p- HelloHf e- Hallo Hs

2) "Hello + a! "Hello Concat (to) (CTE


p "Hetlo a' 'Hello (oncat ('a'); /|cTE
"Hello + t e "Helo' cn at (true),lcTE

3) "Hello" + null "Hello. Concat l(nul):


- "Helloll"
nul pofotevExeaptn.
4)

e- HellofullyQualilad atxa'

Draaseack Shto
shng Ooject.
Because tte fnenutab?liy new
Object wi1l beke (realtd or each and
So

ore aud th
paovmana
opplécahn wtll bi dedued.
Built-o Methccls fo Sbng clas:

tost»tng() eplae (char ch,char cha)


equals ( ob fect o) aplaafat (tig
equala lgnoeCae(Ckject o)) star tsuHh (stng ot)
eompaeto (aufect o) endswrth (Strtng str)
hashCode() matches (strng st)
to ChasAay) Contains (Char Seq uence s)
chauAt(fnt fnde) Laat Indexol (char cb)
get eya)
tofn()
to Upper ase t) (o do)s
tolowev Case()
Concat (stfng )
substring (nt încx)
sub sbeîng (ot start, int erd)
Ehdeey (char ch)
kngth )
geteya)
rekurntgpe - Strhg
Over ríden
method

Coject
fect clas.
Shfnq Clas. pom St
Teturn tie achual data in

str : "Hello;
sbrg

2) aquals (Ob•et o)
4 - Boolean
wturntgp
Thenwattod ao Ovemden

tod compare
tta Obect aud
data present
both are Sae
eun'
oterwfee wehurn halse.
example:
striy, str2 "Hello;
S. o.phcstr, equas(sta)): /twn
3) equalsignove Case (obfect o)
vetusntype - Bolean
JE
Jt Loupares two
ale dilkrens.
aample: str 3-hello";
S.opln (at2 . aquals IgnoreCae (sbrs));
I/ t e
4) compareto (Obfect o)
:fot
retusng two
tompaes
lonlographia ly
are equol
returns o - t| both
*ve number - i string!
qeatu than stvinq 2 .

veturns -Ve no. - s than


string'
Fxaupte :

sta fnq a
"apple";
string b
b= banana ;
Systeuu .o pln (a. compoe to( b)); |-I
becaue
we app le "< "banana"
S.opln (a. com pareTo (a));
S.opln ( b. compare To (a));
be Case " banana " "apple "

Note :
Jo Arays. sot), compaveTs ()
lo()
Caled

S) hash Code()
futdnally
returngea
nique fntegr ker te
Strfng bnd ib chara cters.
wuttuod ao Overríden
This
claus.
strhg clas mom oujet
enample: / P41
s.o.pla (stz hashlode (0); )1234s
Sopln ( sty). hashloda ()),
6) tachar Array)
- chavacted Array
rehurntya Lonvert a
striny
fnto a char array.
Axample.
'char(J arr str. to char Arry);

(H,e, l, l, o)
fnt
) CharAt (nde*)
char
char
wsed to

at a fndex in a stthg
S. o. pln (str.charAt (1)); /e

9)8) guteyta ()
veturntpe - byt (] array
Con ves t striy

Value.
Chauact Aseu

zxampl;
bytal] b str. gteyta)
[12, 1o1, 102, 102, )
4) tyim0
return type - shthg
I sed to remove
leading
and trai lfnq itespau joms a
enample:
Hello
shrry
S.opln(e-trfu0); Hello"

io) toUppar C a e ) s
vehrntpe - shg Cmvert all char
wsed. to
to
tng
example :
c. toUppy Cae );
shiny
Systen.ou-prntln( ) ; ) HELLO
) toLoanllase ()

used to Convert al char


LowerCse
strig
exampl

S. opln (); / ullo

12) Concat(shiny s)
to
sed to
foro
onothar.
end
Anample HELLOketllo
S.opln(us (4)); )2
concat (4));
substbq (tot frdex)
13)
stng ex tract a put
wsed to

t a end
to
given
fndox
exanpu ()di Mall
subathiy
Sopln (str,

4) subsbng (nt start, fat end)


antract porton

batwesn gren start

fndces.
ond
e ample: :

(4tr.Jubstiy
(1i4): lall
s.o-pln

char ch)
Is) fodex Ol ( - fnt
ahunkype wiad
bind ta fndax
Occurence
tt hirst
d
Chau n a

(str.fndax (u))j /2
S.o pln
l6) AastIndex ol (chay ch)
atun ae -nt
lat Occurren u ¢
bnd tta fndex s

gfven Char fn stig


S.o.ph ( str. lostInde oy (u)): / 3
I)length ()
- înt
vehrntgeesed to t nuneber
chauactu

exampk:
8.o pb (st. danyth)):
l8) split (sting s))
rehurntye
Ít i e d toto split a striy
band
substig
given separator.
enauplu
st= "java s
stry ");
tara; a"7un"J

( Java", 'a", "Good.]


Note:
Ja split) we Can se
Rgula
Epres ion .
1) Erophy) Boolean
to check
or not.

Anampu: /t u
S.o.po(". isEmphy 0);
S-o-pln (stEmpty0): /7ale
a0) aplauAI (Jbtiy Shiy )
ahantge- shiy all tt
wed to plaee
that match a

pa ttero (o) with anotthor srig (s )


Anaupl:
, abbacbbd":

S o pln (si eplaceAll(bb" ee,


// aeeaceed
21) eplau cchay ch, char cha)
abntgpe Teplau
st all tte
Char Cc,) n a
Occuy encs
anotter Char (Ca).

erample
Sopln(s: aplaca ( 'a', 6'

a2) uplacu Frst (st-thg


wed tsto uplae brst
Occurenee
buty t rst matck
o te patern
eample:
3.opln (s. eplau Arst(bb" "ee)
/ aeeac bbd
3) start with (sthy st)
- tecean

(with tt

examplu: /tue.
(AG");
"ABc". start with

4)ende wtth ( stty st)


etuntyp - boolean
check encs with
tta

Rnauple
Aec. enduwith ("Bc");
a5) watches (Stfay st)
turnlpe - boclesn
ten eutire
matcwes
enactly
enpresn str.

"4". matces 4");


H', atches (" [A-J"); ) t e
"H1 matches ( [A-Za-z 0-13); Wae
HI".matues C(A-72-o-9]* "); /1t
"o2". watces ("c^a-j"); /tue
Contains ( Charegunu a)
26)
beoleanaibsd

led to cluck f t
Char
Pnctuda ta
S.

traugle:t
"ara pogramni
7tee
S-o pln (e. eoata'y"helo)),
S-opln (c. Cuta'hs ("a-14-1] D

CherSoquane:
,Parent sn terjau bor
metlods
hare tti LommSn
wich snd to stoiy, sb, b sbuills

ila dnyth), Bmpty(), ate,.."


Regular Expresim:
pattem sd to match

character wihin
we Can
dgulas Pepresfon
iu split0,AuplaieAu(), natcsl ).
Note:
Over coue tha drawkack
(reatt mutable Oejecti.
Can Cuiat mutalsa

to
and
stbig

fhal clas wuich


inside
prent
How to Creat

CoutctoA fo

3.

Note :
The delault Capauty
16.
ample
Ox
hew

new Stxiy Blle(ec) OX2

Stiy Bulke» (2o); 16


copacy
OX3
1643-|4
ABc
topaity

Ezample:
= hew
striglguc;
- l6
Bo.ph (db. capactty0);
So.po (ab. dangth0);
Srpo sb. append ('Aec") ;
S.o-pln( ab. capatby(0); -I6
Ss0.ph ( sb. ngtho)>; -
sb. appand ('AAAAAAAAAAAAA);
S.o-pln (ab. capadty(0);
Sso.ph( sb. dngth0); - l6
sb.appnd ('a '))
S.o.plo(ab. capaury ); - 34
S.o. pn(sb. dength)); - 17
sb, appard ("gg... );
S.o.pln (sb. capatt 0; - 34
S.o pln(sb. ang th(0) ; - 34
sb. append (" ");
S.opln(sb. capauG0);
- 35
So-pln(ub. lenyth)); - 35
Ox 2
sb sCP
|AC
OX3
4A4....
l6 capaia

34 Copacity

Fomula
new
capaut - (old capauty ’ )"
= (lb+ )*2
34
Fxample
=. new

Sty Bukfe (ABe );


sb; sbi+sb, / CTE
choractestetu trhg Bulf
l Instane mutable.
Con catenato s posaTble
with
shg
respe to

+ operato.
wilbe Creatrd
3.
strthg Bulf cbjet
aea
tte
Fonmple
sb, new
=

So.pln(sbi = sba) te
Sting Bu sbz =new
So-pln(sb, sb); tabe
So- plo(sb,. squas(ubsj); / ale To

S.opln (sb|-hash Code 0; 1967150


Sopln (&b3. hashiod()); 204656 o2
Ox3
Soph (sb); n Jova Java Saal

S.o-pln (sba);
Not:
Overrtden te
shgBulfu.
-’ bash lode () agualts are not
Overdan sbigao
Note:
we eed to Conrert
iuto strfng to Compare Data

String(sbi). equale(naw Striy labs)


(ov)

sab, tostring(). squab (abs. toSbio)


Band
Jirate

states

xanple
lode()
sbi. toStrfing t). hasb hashcode
sbg -to String(). has btoda)

Draukocle stringB
Sigtor cbjects are thread so
all tt mettods are

because
gnekronisad.
tsk
will allow ony
take
at a tiue trat
wore tfue to ereute ltiple tosk.

Not: wesd
To Overce
to Creatu wot tread saje
safe object (sttny Butao)

Not Thread Safe


Tbread Sa7
Grehdnizd)
Data Data

task ! tosk3
S ec

Total - 5 sec
task
S e tauk 3
StohgBuilder: {nal clas which
Present sfde

charactertstia:
are not Thred
all ta enmatniy
cheattetsHu are sfmtla to

SttngBu|e String Builder


Strfg
utable wtable
immutable

we Can

obË by eatng kigword.


iterals directy
aswelas
keood

There a The delault


capauty
tstrig), qualby tostrig my tostrig
Overr den üOverrfolen!
A hashCodu) are
Overid en.

Cantatnati stng cm atfratih sbiy Concattnalin


String, not postble
pottble by + oprator.
uatig +

Tu obf will
Tu Ob? wl be The Se obË will
Credtd fn both be Creattd be creatd only
ScP teop fnssde haap area futde heap are
area
low Perlorman u Medium Pelormara Hhgh feoans
AU wtlods AU ntods AU matody
Qre not are Aynchonized. are not
ynchronied. synchronod.

obf striye
stdread
are

sote. (Be cawbecan all


thread sale are not thrad
|safe be caute of
a l wehoo ar
o t e fnmutab uttods are

cho zed. kot synchronizad

tteres w e n teere when tare u


when
a wed o beqsnt| ed brequnt
no
brequent modilicatn
modilícation mmcdilícaton, we
with uultthreadty
te sty go wi
uteral, we
Con
with
|st-fngBuyer SbingBulder

to Create Im mutable
claa /obj:
Coreati the clas as nal.
attributs
Make al

prfvat nal. attribut by


Jitialye tta
onstautor.
don 't
Provide y gte (),
provide setert)

You might also like