java - Why StringBuilder when there is String? -


i encountered stringbuilder first time , surprised since java has powerful string class allows appending.

why second string class?

where can learn more stringbuilder?

string not allow appending. each method invoke on string creates new object , returns it. because string immutable - cannot change internal state.

on other hand stringbuilder mutable. when call append(..) alters internal char array, rather creating new string object.

thus more efficient have:

stringbuilder sb = new stringbuilder(); (int = 0; < 500; ++) {     sb.append(i); } 

rather str += i, create 500 new string objects.

note in example use loop. helios notes in comments, compiler automatically translates expressions string d = + b + c like

string d = new stringbuilder(a).append(b).append(c).tostring(); 

note there stringbuffer in addition stringbuilder. difference former has synchronized methods. if use local variable, use stringbuilder. if happens it's possible accessed multiple threads, use stringbuffer (that's rarer)


Comments