Show Menu
Cheatography

Java String&StringBuilder(OCA) Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

String

a sequence of charac­ters, implim­ented as array
create using 1) constr­uctor new String­("") 2) literals 3)conc­ate­nation
empty string "­"

Concat­enation

if anyone of operand is string, all other operands are cast to String
toString() for reference type
primary is convert directly to string
If none of operand is String, the return will not be string
int x=3;y=4; String s=x+y; // error can not assign int to String
Default toString() return memory address for Object class: class name@m­emo­rya­ddress

Compare String

==
memory location, only for test
equals­();­equ­als­Ign­ore­Case()
content
compar­eTo()
content

Immuta­bility and String Pool

Once initia­lized, never changed again, Chain of methods results in multiple Strings
String literals could be a largest chuck of memory.
String pool
string litera­ls,­literal concat­enation ( compiler time)
obj.in­tern(): will return a string in string pool or added if not exist
String s = "­Hel­" + lo;//r­untime concat­ena­tion, not using string pool
Math, Wrapper class, String: immutable
Math,W­rapper, String, String­Bui­lde­r,S­ystem: final

Methods

length()
method instead of attribute, trade-­off­space and perfor­mance
charAt()
String­Ind­exO­utO­fBo­und­sEx­ception
indexOf()
0..len­gth­()-1, -1
substr­ing­(be­gin­,end)
[ ...), exception, empty string
toLowe­rCase()
toUppe­rCase()
startW­ith()
endWith()
s1.con­tai­ns(s2)
s.inde­xOf(s2) !=-1
replac­e(o­ldC­har­,ne­wChar)
replac­e(o­ldC­har­Seq­,ne­wCh­arSeq)
character sequence - String, String­Builder
trim()
trim white space
 

Why String­Builder

efficient memory usage
Mutable and chain of operation will result in one sb
before java5, String­Buffer was used, but slower due to thread safe.

Create a String­Builder

new String­Bui­lder();
new String­Bui­lder( sb2 );
new String­Bui­lde­r(5);
size()=0; capacity=5

SringB­uider Methods

append­(str)
insert­(of­fse­t,str)
delete­(fr­om,to)
[from,to)
delete­Cha­rAt()
reverse()
toString()
sb for perfor­mance, convert to string in the end
subStr­ing­(int), subStr­ing­(in­t,int)
returns string type
CharAt­();­ind­exO­f()­;le­ngt­h()­;su­bst­ring() see String class

equals() is not overriden in String­Bui­lder, use toStri­ng(­).e­qua­ls(s1);