What is the difference between String and String Buffer?

String objects are "immutable" and String buffer objects are "mutable".

String:

Once we create a string object, we cannot perform any changes on that same string object. If we try to perform any operation on that object, then a new object will get created with those changes. This non changeable behavior of string object is called "immutability". 
example:
String s = new String("Programmers"); // a string object s is created and has a value "programmers". 
s.concat("language"); // new object "Programmers language" will be created and left unassigned to any variable.(will be removed by garbage collector) 
System.out.println(s);   
o/p: Programmers

String Buffer:

Once we creates a string buffer object, we can perform any type of changes on the existing object itself. This changeable behavior of String Buffer objects is called "mutability".
example:
String sb = new String("Programmers"); // a string object s is created and has a value "programmers". 
sb.append("language"); // object  will be modified to "Programmers language"
System.out.println(sb);   
o/p: Programmers language

No comments:

Post a Comment