SlidePub
Home
Categories
Login
Register
Home
General
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
36 views
37 slides
May 08, 2024
Slide
1
of 37
Previous
Next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
About This Presentation
new
Size:
281.69 KB
Language:
en
Added:
May 08, 2024
Slides:
37 pages
Slide Content
Slide 1
Characters and Strings
Slide 2
•TheJavaplatformcontainsthreeclasses
1.Character:-Aclasswhoseinstancescanholdasingle
charactervalue
2.String:-Aclassforworkingwithimmutable
(unchanging)datacomposedofmultiplecharacters
3.StringBuffer:-Aclassforstoringandmanipulating
mutabledatacomposedofmultiplecharacters.
•Character
–useaCharacterobjectinsteadofaprimitivecharvariable
whenanobjectisrequired
–Forexample,whenpassingacharactervalueintoa
method
Slide 3
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);
Slide 4
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.
Slide 5
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.
Slide 6
•String
–InJavaastringisasequenceofcharacters
–JavaimplementsstringsasobjectsoftypeString.
–objectsoftypeStringareimmutable;
–onceaStringobjectiscreated,itscontentscannotbealtered
–IfyouwanttochangeStringobject
•createanewstringthatcontainsthemodifications.
•UseStringBufferclass
–Stringscanbeconstructedavarietyofways.
•useastatementlike:
StringmyString="thisisatest";
•usingthenewkeywordandaconstructor
–Forexample:Stringstr=newString(charArray);
–BothStringandStringBufferaredeclaredfinal,which
meansthatneitheroftheseclassesmaybesubclassed.
Slide 7
•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
Slide 8
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
Slide 9
–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);
}}
Slide 10
–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
Slide 11
String Class
•Method
–charcharAt(intindex):
•Returnthecharacteratspecificpositioninstring
–intlength():
•Returnthelengthofstring
–StringtoUpperCase():
•Convertthestringintouppercharacter
–StringtoLowerCase():
•Convertthestringintolowercharacter
–voidgetChars():
•extractmorethanonecharacteratatime
–Stringsubstring(intbeginIndex):
•MakethesubstringfrombeginIndextotheendofthe
string
Slide 12
•getChars()
–extractmorethanonecharacteratatime
–generalform:
voidgetChars(intStart,intEnd,chartarget[],inttargetStart)
–Startspecifiestheindexofthebeginningofthesubstring,
–Endspecifiesanindexthatisonepasttheendofthedesired
substring
–Thearraythatwillreceivethecharactersisspecifiedbytarget.
–Theindexwithintargetatwhichthesubstringwillbecopiedis
passedintargetStart
Slide 13
–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
Slide 14
•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.
Slide 15
–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");
Slide 16
•StringConversionandtoString()
–Javaconvertsdataintoitsstringrepresentationduring
concatenationby
•callingoneofthestringconversionmethodvalueOf()
•valueOf()isoverloadedforallthesimpletypesandfortype
Object
–Forthesimpletypes,valueOf()returnsastringthatcontains
thehuman-readableequivalentofthevaluewithwhichitis
called.
–Forobjects,valueOf()callsthetoString()methodonthe
object
–EveryclassimplementstoString()becauseitisdefinedby
Object
–ThetoString()methodhasthisgeneralform:
StringtoString()
Slide 17
•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+".";
}
}
Slide 18
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
Slide 19
//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]);
}
}}
Slide 20
•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)
Slide 21
•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"));
Slide 22
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
Slide 23
•ModifyingaString
–tomodifyaString,youmusteithercopyitintoa
StringBufferoruseoneofthefollowingStringmethods,
–substring()
•Ithastwoforms.
1.Stringsubstring(intstartIndex)
2.Stringsubstring(intstartIndex,intendIndex)
•Thestringreturnedcontainsallthecharactersfromthe
beginningindex,upto,butnotincluding,theendingindex.
Slide 24
//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;
Slide 25
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.
Slide 26
Exercise
•Writeaprogramthatperformsthefollowing
–Acceptsastring
–convertsitintoUppercaseorLowercase
–extractsubstringbasedontheusersinterest.
–SearchaPalindromewordwithinthegivenstring.
–countsthenumberofwords
–Extractthespecialcharacters
Slide 27
StringBuffer Class
•isapeerclassofString
•representsgrowableandwriteablecharactersequences.
•willautomaticallygrowtomakeroomforsuchadditions
•oftenhasmorecharacterspre-allocatedthanareactually
needed,toallowroomforgrowth.
–forexample,whenreadingtextdatafromafile.
•mayhavecharactersandsubstringsinsertedinthemiddleor
appendedtotheend.
•StringBufferdefinesthesethreeconstructors:
–StringBuffer()
–StringBuffer(intsize)
–StringBuffer(Stringstr)
Slide 28
•Thedefaultconstructor(theonewithnoparameters)
reservesroomfor16characterswithoutreallocation.
•Thesecondversionacceptsanintegerargumentthat
explicitlysetsthesizeofthebuffer.
•ThethirdversionacceptsaStringargumentthatsetsthe
initialcontentsoftheStringBufferobjectandreservesroom
for16morecharacterswithoutreallocation.
•Byallocatingroomforafewextracharacters,StringBuffer
reducesthenumberofreallocationsthattakeplace.
Slide 29
•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
Slide 30
•append()
–Theappend()methodconcatenatesthestringrepresentationof
anyothertypeofdatatotheendoftheinvokingStringBuffer
object
–fewofitsforms:
StringBufferappend(Stringstr)
StringBufferappend(intnum)
StringBufferappend(Objectobj)
Slide 31
//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!
Slide 32
•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!
Slide 33
•reverse()
StringBufferreverse()
//Usingreverse()toreverseaStringBuffer.
classReverseDemo{
publicstaticvoidmain(Stringargs[]){
StringBuffers=newStringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
–theoutput:
abcdef
fedcba
Slide 34
•delete()anddeleteCharAt()
–Thedelete()methoddeletesasequenceofcharactersfromthe
invokingobject.
StringBufferdelete(intstartIndex,intendIndex)
–startIndexspecifiestheindexofthefirstcharactertoremove,
andendIndexspecifiesanindexonepastthelastcharacterto
remove.
–thesubstringdeletedrunsfromstartIndextoendIndex–1.
StringBufferdeleteCharAt(intloc)
–deletesthecharacterattheindexspecifiedbyloc.
Slide 35
//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.
Slide 36
•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.
Slide 37
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
Categories
General
Download
Download Slideshow
Get the original presentation file
Quick Actions
Embed
Share
Save
Print
Full
Report
Statistics
Views
36
Slides
37
Age
574 days
Related Slideshows
22
Pray For The Peace Of Jerusalem and You Will Prosper
RodolfoMoralesMarcuc
32 views
26
Don_t_Waste_Your_Life_God.....powerpoint
chalobrido8
35 views
31
VILLASUR_FACTORS_TO_CONSIDER_IN_PLATING_SALAD_10-13.pdf
JaiJai148317
32 views
14
Fertility awareness methods for women in the society
Isaiah47
30 views
35
Chapter 5 Arithmetic Functions Computer Organisation and Architecture
RitikSharma297999
28 views
5
syakira bhasa inggris (1) (1).pptx.......
ourcommunity56
30 views
View More in This Category
Embed Slideshow
Dimensions
Width (px)
Height (px)
Start Page
Which slide to start from (1-37)
Options
Auto-play slides
Show controls
Embed Code
Copy Code
Share Slideshow
Share on Social Media
Share on Facebook
Share on Twitter
Share on LinkedIn
Share via Email
Or copy link
Copy
Report Content
Reason for reporting
*
Select a reason...
Inappropriate content
Copyright violation
Spam or misleading
Offensive or hateful
Privacy violation
Other
Slide number
Leave blank if it applies to the entire slideshow
Additional details
*
Help us understand the problem better