Advertisement



< Prev
Next >



String v/s StringBuffer Class





Difference between String and StringBuffer







Modification of String object.


let us understand by a short code -

String s1= new String("Hello"); //Statement1
String s2= new String("World"); //Statement2
s1= s1.concat(s2); 		//Statement3

Figure 1 represents the Heap memory after executing the above three statements. Dashed line indicates a deleted reference.








Modification of StringBuffer object.


The memory waste doesn't happen when we try to modify the a string of characters created by StringBuffer class because StringBuffer works directly with original object to modify it.
let us understand by a coding example -

StringBuffer s1= new StringBuffer("Hello");  // Statement1
StringBuffer s2= new StringBuffer("World");  // Statement2
s1.append(s2);		  		     // Statement3

Figure 2 represents the Heap memory after executing the above three statements.






Advertisement




StringBuffer example


Here in program below, we are trying to modify string of character created using StringBuffer class by calling its append() method.
// StringBuffer Class Example

class StringBufferEx
{
public static void main(String... ar)
{
StringBuffer sb= new StringBuffer("Keep");

System.out.println("Original String is : "+ sb);
sb.append("Learning");
System.out.println("Modified String is : "+ sb);
}
}


Output is :


Original String is : Blue
Modified String is : BlueSky


Program Analysis






Please share this article -




< Prev
Next >
< StringBuffer methods
StringBuilder methods >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement