Difference Between String , StringBuilder And StringBuffer Classes

Difference Between String , StringBuilder And StringBuffer Classes

String

String is immutable ( as soon as created can not be changed )item . The item created as a String is saved inside the constant string pool. Each immutable object in java is thread secure ,that means string is also thread safe . String Cannot be utilized by threads concurrently. String once assigned cannot be changed.

StringBuffer

Stringbuffer is mutable way one can alternate the fee of the item . The object created Via stringbuffer is stored inside the heap. Stringbuffer has the identical techniques as the Stringbuilder , but every technique in stringbuffer is synchronized that is stringbuffer is thread Safe . Because of this it does now not allow threads to concurrently get right of entry to the same approach . Every Approach may be accessed by using one thread at a time . But being thread secure has dangers too because the overall performance of the stringbuffer hits due To thread safe assets . Thus stringbuilder is quicker than the stringbuffer while calling the Identical strategies of every magnificence. String buffer may be transformed to the string by means of the usage of Tostring() method.

StringBuffer demo1 = new StringBuffer("Hello") ;

// The above object stored in heap and its value can be changed .

demo1=new StringBuffer("Bye");

// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder

Stringbuilder is equal as the stringbuffer , this is it stores the item in heap and it could additionally Be modified . The primary difference between the stringbuffer and stringbuilder is That stringbuilder is likewise not thread safe. Stringbuilder is speedy because it isn't thread secure .

StringBuilder demo2= new StringBuilder("Hello");

// The above object too is stored in the heap and its value can be modified

demo2=new StringBuilder("Bye");

// Above statement is right as it modifies the value which is allowed in the StringBuilder