< Prev
Next >

String v/s StringBuilder Class

Differences between String and StringBuilder

Modification of String object.

Take a look at a short code and implication of its execution in the memory -

String s1= new String("Blue"); //Statement1
String s2= new String("Sky"); //Statement2
s1= s1.concat(s2); 		//Statement3

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


Modification of StringBuilder object.

The memory waste doesn't happen when we try to modify the strings created by StringBuilder class because StringBuilder works directly with original object to modify it.
let us understand by an example-

StringBuilder s1= new StringBuilder("Blue"); // Statement 1
StringBuilder s2= new StringBuilder("Sky");  // Statement 2
s1.append(s2);		  		     // Statement 3

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

StringBuilder example

// StringBuilder Class Example

class StringBuilderEx
public static void main(String... ar)
StringBuilder sb= new StringBuilder("Never ");

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

Output is :

Original String is : Never 
Modified String is : Never Give Up

Program Analysis

Please share this article -

< Prev
Next >
< StringBuilder class
StringBuilder methods >


Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page



Please check our latest addition