< 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.








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 -

Facebook Google Pinterest Reddit Tumblr Twitter



< Prev
Next >
< StringBuffer methods
StringBuilder methods >
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
C++ and Python

Ad2