Charcater and Strings.ppt Charcater and Strings.ppt

mulualem37 36 views 37 slides May 08, 2024
Slide 1
Slide 1 of 37
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37

About This Presentation

new


Slide Content

Characters and Strings

•TheJavaplatformcontainsthreeclasses
1.Character:-Aclasswhoseinstancescanholdasingle
charactervalue
2.String:-Aclassforworkingwithimmutable
(unchanging)datacomposedofmultiplecharacters
3.StringBuffer:-Aclassforstoringandmanipulating
mutabledatacomposedofmultiplecharacters.
•Character
–useaCharacterobjectinsteadofaprimitivecharvariable
whenanobjectisrequired
–Forexample,whenpassingacharactervalueintoa
method

publicclassCharacterDemo{
publicstaticvoidmain(Stringargs[]){
Charactera=newCharacter('A');
Charactera2=newCharacter('a');
Characterb=newCharacter('b');
intdifference=a.compareTo(b);
if(difference==0){
System.out.println(a+"isequalto"+b);
}
elseif(difference<0)
System.out.println(a+"islessthan"+b);
else
System.out.println(a+"isgreaterthan"+b);

System.out.println(a+"is"+((a.equals(a2))?"equal":"not
equal")+"to"+a2);
System.out.println("Thecharacter"+a.toString()+"is"+
(Character.isUpperCase(a.charValue())?"upper":
"lower")+"case.");
}
}
•Output
–Aislessthanb
–Aisnotequaltoa
–ThecharacterAisuppercase.

Character Class
•Constant
–publicstaticfinalintMAX_RADIX=36
–publicstaticfinalcharMAX_VALUE=‘\ffff’
–publicstaticfinalintMIN_RADIX=2
–publicstaticfinalcharMIN_VALUE=’\0000’
•Method
–Character(charvalue):Constructortoinitializethe
objectasvalue
–charcharValue():Convertintochartype
–staticbooleanisDigit(charch):Testwhetherisdigit?
–staticbooleanisLetter(charch):Testwhetherisletter?
–staticbooleanisLetterOrDigit(charch):Returnwhenit
isletterordigit.

•String
–InJavaastringisasequenceofcharacters
–JavaimplementsstringsasobjectsoftypeString.
–objectsoftypeStringareimmutable;
–onceaStringobjectiscreated,itscontentscannotbealtered
–IfyouwanttochangeStringobject
•createanewstringthatcontainsthemodifications.
•UseStringBufferclass
–Stringscanbeconstructedavarietyofways.
•useastatementlike:
StringmyString="thisisatest";
•usingthenewkeywordandaconstructor
–Forexample:Stringstr=newString(charArray);
–BothStringandStringBufferaredeclaredfinal,which
meansthatneitheroftheseclassesmaybesubclassed.

•Stringsareimmutable
classStringTest{
publicstaticvoidmain(Stringargs[]){
Stringname=“Kebede”;
System.out.println(name);
name=name+“Tollosa”;
System.out.println(name);
}
}
•OutPut:
Kebede
KebedeTollosa
Memory
name Kebede
Kebede Tollosa

The String Constructors
•TheStringclasssupportsseveralconstructors.
Strings=newString();
–TocreateaStringinitializedbyanarrayofcharacters,usethe
constructor
String(charchars[])
–example:
charchars[]={'a','b','c'};
Strings=newString(chars);
–Thisconstructorinitializesswiththestring"abc".
–Youcanspecifyasub-rangeofacharacterarrayasan
initializerusingthefollowingconstructor:
String(charchars[],intstartIndex,intnumChars)
–startIndexspecifiestheindexatwhichthesubrangebegins,
andnumCharsspecifiesthenumberofcharacterstouse

–example:
charchars[]={'a','b','c','d','e','f'};
Strings=newString(chars,2,3);
–Thisinitializesswiththecharacterscde.
–YoucanconstructaStringobjectthatcontainsthesame
charactersequenceasanotherStringobjectusingthis
constructor:
String(StringstrObj)
–example:
classMakeString{
publicstaticvoidmain(Stringargs[]){
charc[]={'J','a','v','a'};
Strings1=newString(c);
Strings2=newString(s1);
System.out.println(s1);
System.out.println(s2);
}}

–Theoutputfromthisprogramisasfollows:
Java
Java
–Thefollowingprogramconvertsthegivenbytearrayinto
String
//Constructstringfromsubsetofchararray.
classSubStringCons{
publicstaticvoidmain(Stringargs[]){
byteascii[]={65,66,67,68,69,70};
Strings1=newString(ascii);
System.out.println(s1);
Strings2=newString(ascii,2,3);
System.out.println(s2);
}}
–Thisprogramgeneratesthefollowingoutput:
ABCDEF
CDE

String Class
•Method
–charcharAt(intindex):
•Returnthecharacteratspecificpositioninstring
–intlength():
•Returnthelengthofstring
–StringtoUpperCase():
•Convertthestringintouppercharacter
–StringtoLowerCase():
•Convertthestringintolowercharacter
–voidgetChars():
•extractmorethanonecharacteratatime
–Stringsubstring(intbeginIndex):
•MakethesubstringfrombeginIndextotheendofthe
string

•getChars()
–extractmorethanonecharacteratatime
–generalform:
voidgetChars(intStart,intEnd,chartarget[],inttargetStart)
–Startspecifiestheindexofthebeginningofthesubstring,
–Endspecifiesanindexthatisonepasttheendofthedesired
substring
–Thearraythatwillreceivethecharactersisspecifiedbytarget.
–Theindexwithintargetatwhichthesubstringwillbecopiedis
passedintargetStart

–ThefollowingprogramdemonstratesgetChars():
classgetCharsDemo{
publicstaticvoidmain(Stringargs[]){
Strings="ThisisademoofthegetCharsmethod.";
intstart=10;
intend=14;
charbuf[]=newchar[end-start];
s.getChars(start,end,buf,0);
System.out.println(buf);
}
}
–Hereistheoutputofthisprogram:
demo

•StringConcatenation
–+operator
–Example:
Stringage="9";
Strings="Heis"+age+"yearsold.";
System.out.println(s);
•StringConcatenationwithOtherDataTypes
intage=9;
Strings="Heis"+age+"yearsold.";
System.out.println(s);
–Thecompilerwillconvertanoperandtoitsstringequivalent
whenevertheotheroperandofthe+isaninstanceofString.

–Considerthefollowing:
Strings="four:"+2+2;
System.out.println(s);
–Thisfragmentdisplays
four:22
–Tocompletetheintegeradditionfirst,youmustuse
parentheses,likethis:
Strings="four:"+(2+2);
–Nowscontainsthestring"four:4".
•Youcanconcatenatetwostringsusingconcat()
Stringconcat(Stringstr)
Strings1="one";
Strings2=s1.concat("two");

•StringConversionandtoString()
–Javaconvertsdataintoitsstringrepresentationduring
concatenationby
•callingoneofthestringconversionmethodvalueOf()
•valueOf()isoverloadedforallthesimpletypesandfortype
Object
–Forthesimpletypes,valueOf()returnsastringthatcontains
thehuman-readableequivalentofthevaluewithwhichitis
called.
–Forobjects,valueOf()callsthetoString()methodonthe
object
–EveryclassimplementstoString()becauseitisdefinedby
Object
–ThetoString()methodhasthisgeneralform:
StringtoString()

•ThefollowingprogramdemonstratesoverridingtoString()
fortheBoxclass:
//OverridetoString()forBoxclass.
classBox{
doublewidth,height,depth;
Box(doublew,doubleh,doubled){
width=w;
height=h;
depth=d;
}
publicStringtoString(){
return"Dimensionsare"+width+"by"+depth+"by"
+height+".";
}
}

classtoStringDemo{
publicstaticvoidmain(Stringargs[]){
Boxb=newBox(10,12,14);
Strings="Boxb:"+b;//concatenateBoxobject
System.out.println(b);//convertBoxtostring
System.out.println(s);
}
}
–Theoutputofthisprogramisshownhere:
Dimensionsare10by14by12.
Boxb:Dimensionsare10by14by12

//AbubblesortforStrings.
classSortString{
staticStringarr[]={"Now","is","the","time","for","all",
"good",“persons","to","come","to","the","aid","of","their",
"country”};
publicstaticvoidmain(Stringargs[]){
for(intj=0;j<arr.length;j++){
for(inti=j+1;i<arr.length;i++){
if(arr[i].compareTo(arr[j])<0){
Stringt=arr[j];
arr[j]=arr[i];
arr[i]=t;
}
}
System.out.println(arr[j]);
}
}}

•SearchingStrings
–TheStringclassprovidestwomethodsthatallowyouto
searchastringforaspecifiedcharacterorsubstring:
–indexOf()Searchesforthefirstoccurrenceofacharacteror
substring.
–lastIndexOf()Searchesforthelastoccurrenceofacharacter
orsubstring.
–Tosearchforthefirstorlastoccurrenceofasubstring,use
intindexOf(Stringstr)
intlastIndexOf(Stringstr)
–strspecifiesthesubstring
–Youcanspecifyastartingpointforthesearchusingthese
forms:
intindexOf(chaech,intstartIndex)
intlastIndexOf(charch,intstartIndex)
intindexOf(Stringstr,intstartIndex)
intlastIndexOf(Stringstr,intstartIndex)

•ForindexOf(),thesearchrunsfromstartIndextotheendof
thestring.
•ForlastIndexOf(),thesearchrunsfromstartIndextozero.
//DemonstrateindexOf()andlastIndexOf().
classindexOfDemo{
publicstaticvoidmain(Stringargs[]){
Strings="Nowisthetimeforallgoodpersons"+"tocometo
theaidoftheircountry.";
System.out.println(s);
System.out.println("indexOf(t)="+s.indexOf('t'));
System.out.println("lastIndexOf(t)="+s.lastIndexOf('t'));
System.out.println("indexOf(the)="+s.indexOf("the"));
System.out.println("lastIndexOf(the)="+s.lastIndexOf("the"));

System.out.println("indexOf(t,10)="+s.indexOf('t',10));
System.out.println("lastIndexOf(t,60)="+s.lastIndexOf('t',60));
System.out.println("indexOf(the,10)="+s.indexOf("the",10));
System.out.println("lastIndexOf(the, 60)=“+s.lastIndexOf("the",60));
}
}
–theoutputofthisprogram:
Nowisthetimeforallgoodmentocometotheaidoftheircountry.
•Nowisthetimeforallgoodpersonstocometotheaidof
theircountry.
indexOf(t)=7 lastIndexOf(t)=68
indexOf(the)=7 lastIndexOf(the)=58
indexOf(t,10)=11 lastIndexOf(t,60)=58
indexOf(the,10)=47 lastIndexOf(the,60)=58

•ModifyingaString
–tomodifyaString,youmusteithercopyitintoa
StringBufferoruseoneofthefollowingStringmethods,
–substring()
•Ithastwoforms.
1.Stringsubstring(intstartIndex)
2.Stringsubstring(intstartIndex,intendIndex)
•Thestringreturnedcontainsallthecharactersfromthe
beginningindex,upto,butnotincluding,theendingindex.

//Substringreplacement.
classStringReplace{
publicstaticvoidmain(Stringargs[]){
Stringorg="Thisisatest.Thisis,too.";
Stringsearch="is";
Stringsub="was";
Stringresult="";
inti;
do{//replaceallmatchingsubstrings
System.out.println(org);
i=org.indexOf(search);
if(i!=-1){
result=org.substring(0,i);
result=result+sub;

result=result+org.substring(i+search.length());
org=result;
}//endofif
}while(i!=-1);
}
}
•Theoutput
Thisisatest.Thisis,too.
Thwasisatest.Thisis,too.
Thwaswasatest.Thisis,too.
Thwaswasatest.Thwasis,too.
Thwaswasatest.Thwaswas,too.

Exercise
•Writeaprogramthatperformsthefollowing
–Acceptsastring
–convertsitintoUppercaseorLowercase
–extractsubstringbasedontheusersinterest.
–SearchaPalindromewordwithinthegivenstring.
–countsthenumberofwords
–Extractthespecialcharacters

StringBuffer Class
•isapeerclassofString
•representsgrowableandwriteablecharactersequences.
•willautomaticallygrowtomakeroomforsuchadditions
•oftenhasmorecharacterspre-allocatedthanareactually
needed,toallowroomforgrowth.
–forexample,whenreadingtextdatafromafile.
•mayhavecharactersandsubstringsinsertedinthemiddleor
appendedtotheend.
•StringBufferdefinesthesethreeconstructors:
–StringBuffer()
–StringBuffer(intsize)
–StringBuffer(Stringstr)

•Thedefaultconstructor(theonewithnoparameters)
reservesroomfor16characterswithoutreallocation.
•Thesecondversionacceptsanintegerargumentthat
explicitlysetsthesizeofthebuffer.
•ThethirdversionacceptsaStringargumentthatsetsthe
initialcontentsoftheStringBufferobjectandreservesroom
for16morecharacterswithoutreallocation.
•Byallocatingroomforafewextracharacters,StringBuffer
reducesthenumberofreallocationsthattakeplace.

•length()andcapacity()
–ThecurrentlengthofaStringBuffercanbefoundviathe
length()method
–Thetotalallocatedcapacitycanbefoundthroughthe
capacity()method.
•Hereisanexample:
//StringBufferlength
classStringBufferDemo1{
publicstaticvoidmain(Stringargs[]){
StringBuffersb=newStringBuffer("Hello");
System.out.println("buffer="+sb);
System.out.println("length="+sb.length());
System.out.println("Capacity="+sb.capacity());
}}
•Output:buffer=Hello
length=5 Capacity=21

•append()
–Theappend()methodconcatenatesthestringrepresentationof
anyothertypeofdatatotheendoftheinvokingStringBuffer
object
–fewofitsforms:
StringBufferappend(Stringstr)
StringBufferappend(intnum)
StringBufferappend(Objectobj)

//Demonstrateappend().
classappendDemo{
publicstaticvoidmain(Stringargs[]){
Strings;
inta=42;
StringBuffersb=newStringBuffer(40);
s=sb.append("a=").append(a).append("!").toString();
System.out.println(s);
}
}
•Theoutputofthisexampleisshownhere:
a=42!

•insert()
–Theinsert()methodinsertsonestringintoanother
–fewofitsforms:
StringBufferinsert(intindex,Stringstr)
StringBufferinsert(intindex,charch)
StringBufferinsert(intindex,Objectobj)
//Demonstrateinsert().
classinsertDemo{
publicstaticvoidmain(Stringargs[]){
StringBuffersb=newStringBuffer("IJava!");
sb.insert(2,"like");
System.out.println(sb);
}
}
–Theoutput
IlikeJava!

•reverse()
StringBufferreverse()
//Usingreverse()toreverseaStringBuffer.
classReverseDemo{
publicstaticvoidmain(Stringargs[]){
StringBuffers=newStringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
–theoutput:
abcdef
fedcba

•delete()anddeleteCharAt()
–Thedelete()methoddeletesasequenceofcharactersfromthe
invokingobject.
StringBufferdelete(intstartIndex,intendIndex)
–startIndexspecifiestheindexofthefirstcharactertoremove,
andendIndexspecifiesanindexonepastthelastcharacterto
remove.
–thesubstringdeletedrunsfromstartIndextoendIndex–1.
StringBufferdeleteCharAt(intloc)
–deletesthecharacterattheindexspecifiedbyloc.

//Demonstratedelete()anddeleteCharAt()
classdeleteDemo{
publicstaticvoidmain(Stringargs[]){
StringBuffersb=newStringBuffer("Thisisatest.");
sb.delete(4,7);
System.out.println("Afterdelete:"+sb);
sb.deleteCharAt(0);
System.out.println("AfterdeleteCharAt:"+sb);
}
}
–Theoutput:
Afterdelete:Thisatest.
AfterdeleteCharAt:hisatest.

•replace()
–replacesonesetofcharacterswithanothersetinsidea
StringBufferobject.
StringBufferreplace(intstartIndex,intendIndex,Stringstr)
//Demonstratereplace()
classreplaceDemo{
publicstaticvoidmain(Stringargs[]){
StringBuffersb=newStringBuffer("Thisisatest.");
sb.replace(5,7,"was");
System.out.println("Afterreplace:"+sb);
}
}
–Theoutput:
Afterreplace:Thiswasatest.

StringBuffer Class
String now = new java.util.Date().toString();
StringBufferstrbuf= new StringBuffer(now);
strbuf.append(" : ").append(now.length()).append('.');
System.out.println(strbuf.toString());
Tags