Diffrence between String and StringBuffer

String: String Objects are immutable. when we create a String object and we performed some operation on String the new reference is created.
For Example : 
String s1 = new String("Hello");
s1.concate("Java");/now original string is not changed. new reference is created in memory. 
System.out.println("String Value"+ s1);

In the above example output is "Hello" because s1 is immutable.

StringBuffer: StringBuffer is mutable. when we create a StringBuffer object and we performed some operation on StringBuffer then it changes in the same object/Reference.

StringBuffer sb=new StringBuffer("Hello ");  
sb.append("Java");//now original string is changed  
System.out.println(sb);//prints Hello Java  

In the Above Example output is hello Java because sb is mutable.


Comments

Popular posts from this blog

Primitive Data Types in java

let - Keyword in JavaScript (Block scope)

Coding Problem 4: Smallest window containing 0, 1 and 2 [GFG - Problem Solving]