Java Strings
Java Strings
Java String
Java Stringprovidesalotofconceptsthatcanbe
performed on a string such as compare, concat,
equals, split, length, replace, compareTo, intern,
substringetc.
Injava,stringisbasicallyanobjectthatrepresents
sequenceofcharvalues.
Anarrayofcharactersworkssameasjavastring.
char[]ch={T',h',a',p',a',r',U',n',i'};
Strings=newString(ch);
Strings=ThaparUni";
2.Bynewkeyword
Strings="welcome";
Eachtimeyoucreateastringliteral,theJVMchecks
the string constant pool first. If the string already
exists in the pool, a reference to the pooled
instance is returned. If string doesn't exist in the
pool,anewstringinstanceiscreatedandplacedin
thepool.
String objects are stored in a
special memory area known
as string constant pool.
Strings1="Welcome";
Strings2="Welcome";
//willnotcreatenewinstance
Oncestringobjectiscreateditsdata
orstatecan'tbechangedbutanew
stringobjectiscreated.
Strings=newString("Welcome");
Insuchcase,JVMwillcreateanewstringobjectin
normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant
pool. The variable s will refer to the object in
heap(nonpool).
Substring in Java
Apartofstringiscalledsubstring.Inother
words,substringisasubsetofanotherstring.In
caseofsubstringstartIndexisinclusiveand
endIndexisexclusive.
public String substring(int startIndex):This
methodreturnsnewStringobjectcontainingthe
substringofthegivenstringfromspecified
startIndex(inclusive).
public String substring(int startIndex, int
endIndex): ThismethodreturnsnewString
objectcontainingthesubstringofthegivenstring
fromspecifiedstartIndextoendIndex.
classA{
publicstaticvoidmain(Stringargs[]){
StringBuffersb=newStringBuffer("Hello");
sb.append("Java");//noworiginalstringischanged
System.out.println(sb);//printsHelloJava
}
}
classA{
publicstaticvoidmain(Stringargs[]){
StringBuffersb=newStringBuffer("Hello");
sb.insert(1,"Java");//noworiginalstringischanged
System.out.println(sb);//printsHJavaello
}
}
String
StringBuffer
1)
Stringclassisimmutable.
StringBufferclassismutable.
2)
Stringisslowandconsumesmore StringBufferisfastandconsumesless
memorywhenyouconcattoomany memorywhenyoucancatstrings.
stringsbecauseeverytimeit
createsnewinstance.
3)
Stringclassoverridestheequals() StringBufferclassdoesn'toverridethe
methodofObjectclass.Soyoucan equals()methodofObjectclass.
comparethecontentsoftwostrings
byequals()method.