String vs. StringBuffer classes - Core Java

What is the difference between the String and StringBuffer classes?

String class is immutable. The characters of string objects can not be changed / modified. StringBuffer is mutable. The characters of StringBuffer objects can be modified / changed.

String class is used for simple investigations on string objects.

StringBuffer’s performance is faster than String when concatenating other strings. String class concatenates the other string by using + sign. After concatenation, it returns another String object. This string object can be reassigned to the original String reference.

Example :
str = str + “to India” ;// where str=”Welcome”

The concatenation creates a temporary String object, and is reassigned to str.

Using StringBuffer, the concatenation is done by using append() method.

Example:
str.append(“to India”); // str is a StringBuffer object’s reference variable and //assigned “Welcome”.

The concatenation is done only by appending the “string to India” to the original StringBuffer object “Welcome”.

The StringBuffer is class to manipulate the string objects. This class has similar functionalities that of String class. The StringBuffer class is mutable, which means, the strings can be altered. For example, new strings can be appended, inserted. Characters from the string can be deleted. Where as the String class is immutable, which can not make changes to the existing objects.

String class provides the concatenation facility with concat() method. But it creates a new String object and returns it. Where as the StringBuffer just appends / adds the new string to the existing StringBuffer object. This process is pretty quicker than concatenation using + or concat() method of String class.
What is the Dictionary class? - Core Java
What is the Dictionary class? - The Dictionary class is an abstract class. The class maps keys to values...
What is the ResourceBundle class? - Core Java
What is the ResourceBundle class? - A ResourceBundle is a group of related sub classes which are sharing the same base name...
What is the Vector class? - Core Java
What is the Vector class? - The capability of implementing a growable array of objects is provided by the class Vector...
Post your comment