Module-2
String , String Buffer and String Builder
String Handling :The String Constructors, String Length, Special String
Operations,Character Extraction-charAt( ), getChars( ), getBytes( )
toCharArray(), String Comparison-equals( ) and equalsIgnoreCase( ),
regionMatches( ) startsWith( ) and endsWith( ), equals( ) Versus == ,
compareTo( ) Searching Strings, Modifying a String- substring( ), concat(
), replace( ), trim( ), Data Conversion Using valueOf( ), Changing the Case
of Characters Within a String, Additional String Methods, StringBuffer ,
StringBuffer Constructors, length( ) and capacity( ), ensureCapacity( ),
setLength( ), charAt( ) and setCharAt( ), getChars( ),append( ), insert( ),
reverse( ), delete( ) and deleteCharAt( ), replace( ), substring( ),
StringBuilder
String Handling
• In Java a string is a sequence of characters.
• Java implements strings as objects of type String.
• when you create a String object, you are creating a string that cannot
be changed. That is, once a String object has been created, you
cannot change the characters that comprise that string.
• immutable strings can be implemented more efficiently.
• modifiable string is desired, Java provides two options: StringBuffer
and StringBuilder. Both hold strings that can be modified after they
are created.
• The String, StringBuffer, and StringBuilder classes are defined in
[Link].
The String Constructors
• The String class supports several constructors.
[Link] create an empty String, you call the default constructor.
String s = new String();
will create an instance of String with no characters in it.
[Link] create a String initialized by an array of characters, use the constructor
shown here:
String(char chars[ ])
[Link] can specify a subrange of a character array as an initializer using the
following
constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and
numChars specifies the number of characters to use.
[Link] can construct a String object that contains the same character sequence
as another
String object using this constructor:
String(String strObj)
Here, strObj is a String object.
[Link] String class provides constructors that initialize a string when given a
byte array.
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Here, asciiChars specifies the array of bytes. The second form allows you to
specify a
subrange.
• In each of these constructors, the byte-to-character conversion is done by
using
the default character encoding of the platform.
[Link] first supports the extended Unicode character set and is shown here:
String(int codePoints[ ], int startIndex, int numChars)
• Here, codePoints is an array that contains Unicode code points. The
resulting string is constructed from the range that begins at startIndex and
runs for numChars.
[Link] second new constructor supports the new StringBuilder class. It is shown
here:
String(StringBuilder strBuildObj)
• This constructs a String from the StringBuilder passed in strBuildObj.
class MakeString
{
public static void main(String args[])
{
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
[Link](s);
char chars1[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String ss = new String(chars1, 2, 3);
[Link](ss);
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
[Link](s1);
[Link](s2);
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s3 = new String(ascii);
[Link](s3);
String s4 = new String(ascii, 2, 3);
[Link](s4);
}
}
String Length
• The length of a string is the number of characters that it contains. To
obtain this value, call the length( ) method:
int length( )
class StringLengthDemo
{
public static void main(String args[])
{
String s=new String(“Hello World”);
String s = new String(s);
[Link]([Link]());
}
}
Special String Operations
• Java has added special support for several string operations within the syntax of
the language. These operations include
1. The automatic creation of new String instances from string literals.
2. Concatenation of multiple String objects by use of the + operator and
3. The conversion of other data types to a string representation.
• There are explicit methods available to perform all of these functions, but Java
does them automatically as a convenience for the programmer and to add clarity.
String Literals
• For each string literal in your program, Java automatically constructs a String
object. Thus, you can use a string literal to initialize a String object.
class StringLiteralDemo
{
public static void main(String args[])
{
String s2 = "abc"; // use string literal
[Link]([Link]());
}
}
String Concatenation
• The + operator, which concatenates two strings, producing a String
object as the result.
class StringConcatDemo
{
public static void main(String args[])
{
String age = "9";
String s = "He is " + age + " years old.";
[Link](s);
}
}
class ConCat
{
public static void main(String args[])
{
String longStr = "This could have been " +"a very long line that would have "
+"wrapped around. But string concatenation " +"prevents this.";
[Link](longStr);
}
}
String Concatenation with Other Data Types
• You can concatenate strings with other types of data.
class StringConcatDemo
{
public static void main(String args[])
{
int age = "9";
String s = "He is " + age + " years old.";
[Link](s);
}
}
• The compiler will convert an operand to its string equivalent
whenever the other operand of the + is an instance of String.
class ConCat
{
public static void main(String args[])
{
String s = "four: " + 2 + 2;
//String s = "four: " + (2 + 2);
[Link](s);
}
}
String Conversion and toString( )
• The toString( ) method has this general form:
String toString( )
• To implement toString( ), simply return a String object that contains
the human-readable string that appropriately describes an object of
your class.
class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
public String toString()
{
return "Dimensions are " + width + " by " +depth + " by " + height + ".";
}
}
class toStringDemo
{
public static void main(String args[])
{
Box b = new Box(10, 12, 14);
[Link](b);
}}
Character Extraction
• The String class provides a number of ways in which characters can
be extracted from a String object.
• The string indexes begin at zero.
[Link]( )
• To extract a single character from a String.
char charAt(int where)
• Here, where is the index of the character that you want to obtain.
class CharStringDemo
{
public static void main(String args[])
{
String s3="abc";
char ch;
ch = [Link](1);
[Link](ch);
}
}
[Link]( )
• If you need to extract more than one character at a time, you can
use the getChars( ) method.
• It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int
targetStart)
• Here, sourceStart specifies the index of the beginning of the
substring, and sourceEnd specifies an index that is one past the end
of the desired substring.
• Thus, the substring contains the characters from sourceStart through
sourceEnd.
• The array that will receive the characters is specified by target.
• The index within target at which the substring will be copied is passed
in targetStart.
class getCharsDemo
{
public static void main(String args[])
{
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[4];
[Link](start, end, buf, 0);
[Link](buf);
}
}
[Link]( )
• It stores the characters in an array of bytes.
byte[ ] getBytes( )
public class StringGetBytesExample
{
public static void main(String args[])
{
String s1="ABCDEFG";
byte[] barr=[Link]();
for(int i=0;i<[Link];i++)
{
[Link](barr[i]);
}
}
}
[Link]( )
• If you want to convert all the characters in a String object into a
character array.
• It returns an array of characters for the entire string.
char[ ] toCharArray( )
public class StringDemo
{
public static void main(String[] args)
{
String str = " Java was developed by James Gosling";
char retval[] = [Link]();
[Link]("Converted value to character array = ");
[Link](retval);
}
}
String Comparison
• The String class includes several methods that compare strings or
substrings within strings.
equals( ) and equalsIgnoreCase( )
• To compare two strings for equality, use equals( ).
boolean equals(Object str)
• Here, str is the String object being compared with the invoking String
object. It returns true if the strings contain the same characters in the
same order, and false otherwise. The comparison is case-sensitive.
• To perform a comparison that ignores case differences, call
equalsIgnoreCase( ). When it compares two strings, it considers A-Z
to be the same as a-z.
boolean equalsIgnoreCase(String str)
• Here, str is the String object being compared with the invoking String
object. It, too, returns true if the strings contain the same characters
in the same order, and false otherwise.
class equalsDemo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
[Link](s1 + " equals " + s2 + " -> " +[Link](s2));
[Link](s1 + " equals " + s3 + " -> " +[Link](s3));
[Link](s1 + " equals " + s4 + " -> " +[Link](s4));
[Link](s1 + " equalsIgnoreCase " + s4 + " -> " +[Link](s4));
}
}
[Link]( )
• The regionMatches( ) method compares a specific region inside a
string with another specific region in another string.
boolean regionMatches(int startIndex, String str2, int str2StartIndex, int
numChars)
boolean regionMatches(boolean ignoreCase, int startIndex, String
str2,int str2StartIndex, int numChars)
• For both versions, startIndex specifies the index at which the region
begins within the invoking String object.
• The String being compared is specified by str2.
• The index at which the comparison will start within str2 is specified
by str2StartIndex.
• The length of the substring being compared is passed in numChars.
• In the second version, if ignoreCase is true, the case of the characters
is ignored.
class Main {
public static void main(String args[]) {
String str1 = new String("This is regionMatches() example");
String str2 = new String("region");
String str3 = new String("world");
[Link]("str1 and str2 region matches: " +
[Link](8, str2, 0, 6));
[Link]("str1 and str3 region matches: " +
[Link](8, str3, 0, 6));
}
}
[Link]( ) and endsWith( )
• The startsWith( ) method determines whether a given String begins with a
specified string.
• endsWith( ) determines whether the String in question ends with a
specified string.
boolean startsWith(String str)
boolean endsWith(String str)
• Here, str is the String being tested. If the string matches, true is returned.
Otherwise, false is returned.
For Example:
Class Demo
{
public static void main(String args[])
{
String myStr = " Foobar ";
[Link]([Link]("bar"))
[Link]([Link]("Foo"))
}}
equals( ) Versus ==
• The equals( ) method compares the characters inside a String object.
The == operator compares two object references to see whether they
refer to the same instance.
class EqualsNotEqualTo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = new String(s1);
[Link](s1 + " equals " + s2 + " -> " +[Link](s2));
[Link](s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
[Link]( )
• whether two strings are identical. For sorting applications, you need to
know which is less than, equal to, or greater than the next.
• A string is less than another if it comes before the other in dictionary order.
• A string is greater than another if it comes after the other in dictionary
order.
• The String method compareTo( ) serves this purpose.
int compareTo(String str)
• Here, str is the String being compared with the invoking String.
• If you want to ignore case differences when comparing two strings, use
compareToIgnoreCase( ), as shown here:
int compareToIgnoreCase(String str)
• This method returns the same results as compareTo( ), except that case
differences are ignored.
class CompareToExample
{
public static void main(String args[])
{
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
[Link]([Link](s2));//0 because both are equal
[Link]([Link](s3));//-5 because "h" is 5 times lower than "m"
[Link]([Link](s4));//-1 because "l" is 1 times lower than "m"
[Link]([Link](s5));//2 because "h" is 2 times greater than "f"
}
}
Searching Strings
• The String class provides two methods that allow you to search a
string for a specified character or substring:
• indexOf( ) Searches for the first occurrence of a character or
substring.
• lastIndexOf( ) Searches for the last occurrence of a character or
substring.
• To search for the first occurrence of a character, use
int indexOf(int ch)
• To search for the last occurrence of a character, use
int lastIndexOf(int ch)
• Here, ch is the character being sought.
• To search for the first or last occurrence of a substring, use
int indexOf(String str)
int lastIndexOf(String str)
• Here, str specifies the substring.
• You can specify a starting point for the search using these forms:
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
• Here, startIndex specifies the index at which point the search begins.
• For indexOf( ), the search runs from startIndex to the end of the
string. For lastIndexOf( ), the search runs from startIndex to zero.
class indexOfDemo
{
public static void main(String args[])
{
String s = "Now is the time for all good men " +"to come to the aid of their country.";
[Link](s);
[Link]("indexOf(t) = "+[Link]('t'));
[Link]("lastIndexOf(t) = "+[Link]('t'));
[Link]("indexOf(t, 10) = "+[Link]('t', 10));
[Link]("lastIndexOf(t, 60) = "+[Link]('t', 60));
[Link]("indexOf(the) = "+[Link]("the"));
[Link]("lastIndexOf(the) = "+[Link]("the"));
[Link]("indexOf(the, 10) = "+[Link]("the", 10));
[Link]("lastIndexOf(the, 60) = "+[Link]("the", 60))
}
} Output:
Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55
Modifying a String
substring( )
• You can extract a substring using substring( ). It has two forms.
• The first is
String substring(int startIndex)
• Here, startIndex specifies the index at which the substring will begin.
• This form returns a copy of the substring that begins at startIndex and
runs to the end of the invoking string.
• The second form of substring( ) allows you to specify both the
beginning and ending index of the substring:
String substring(int startIndex, int endIndex)
• Here, startIndex specifies the beginning index, and endIndex specifies
the stopping point.
class TestSubstring
{
public static void main(String args[])
{
String s="SachinTendulkar";
[Link]("Original String: "+ s);
[Link]("Substring starting from index 6: "+[Link](6));
[Link]("Substring starting from index 0 to 6:"+[Link](0,6));
}
}
Output:
Original String: Sachin Tendulkar
Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6:Sachin
concat( )
• You can concatenate two strings using concat( ), shown here:
String concat(String str)
For example,
String s1 = "one";
String s2 = [Link]("two");
• puts the string “onetwo” into s2. It generates the same result as the
following sequence:
String s1 = "one";
String s2 = s1 + "two";
replace( )
• The replace( ) method has two forms.
• The first replaces all occurrences of one character in the invoking
string with another character. It has the following general form:
String replace(char original, char replacement)
• Here, original specifies the character to be replaced by the character
specified by replacement.
• The resulting string is returned.
• For example,
String s = "Hello".replace('l', 'w');
• puts the string “Hewwo” into s.
• The second form of replace( ) replaces one character sequence with
another. It has this general form:
String replace(CharSequence original, CharSequence replacement)
trim( )
• The trim( ) method returns a copy of the invoking string from which
any leading and trailing whitespace has been removed.
• It has this general form:
String trim( )
• Here is an example:
String s = " Hello World ".trim();
• This puts the string “Hello World” into s.
Data Conversion Using valueOf( )
• The java string valueOf() method converts different types of values
into string. By the help of string valueOf() method, you can convert
int to string, long to string, boolean to string, character to string, float
to string, double to string, object to string and char array to string.
• Here are a few of its forms:
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])
• static String valueOf(char chars[ ], int startIndex, int numChars)
• Here, chars is the array that holds the characters, startIndex is the
index into the array of characters at which the desired substring
begins, and numChars specifies the length of the substring.
class StringValueOfExample
{
public static void main(String args[])
{
int value=30;
String s1=[Link](value);
[Link](s1+10);
}
}
Changing the Case of Characters Within a String
• The method toLowerCase( ) converts all the characters in a string
from uppercase to lowercase.
• The toUpperCase( ) method converts all the characters in a string
from lowercase to uppercase.
• Here are the general forms of these methods:
String toLowerCase( )
String toUpperCase( )
• Both methods return a String object that contains the uppercase or
lowercase equivalent of the invoking String.
class ChangeCase
{
public static void main(String args[])
{
String s = "This is a test.";
[Link]("Original: " + s);
String upper = [Link]();
String lower = [Link]();
[Link]("Uppercase: " + upper);
[Link]("Lowercase: " + lower); } }
Additional String Methods
[Link]() method
class ContainsDemo
{
public static void main(String args[])
{
String s1 = "My name is venkatesh";
[Link]([Link]("venkatesh"));
[Link]([Link]("Hi"));
}
}
[Link]() Method
class ContentEqualsDemo {
public static void main(String[] args)
{
String str= new String("GFG is a portal for MVJCE");
String is a portal for MVJCE";
String two = "GFG is a portal for gamers";
[Link]("String one equals to specified
String :"+ [Link](str));
[Link]("String two equals to specified
String :"+ [Link](str));
}
}
[Link]() method
class Main {
public static void main(String[] args) {
String str = "Java";
String formatStr = [Link]("Language: %s",
str);
[Link](formatStr);
}
}
[Link]() method
class Main {
public static void main(String[] args) {
// four letter string that starts with 'J' and end with
'a'
String regex = "^J..a$";
[Link]("Java".matches(regex));
}
}
•
[Link]()
class Main {
public static void main(String[] args) {
String str1 = "aabbaaac";
// the first occurrence of "aa" is replaced with "zz"
[Link]([Link]("aa", "zz")); //
zzbbaaac
}
}
[Link]() Method
class Main {
public static void main(String[] args) {
String str1 = "Java123is456fun";
// regex for sequence of digits
String regex = "\\d+";
// replace all occurrences of numeric
// digits by a space
[Link]([Link](regex, " "));
}
}
Output: Java is fun
[Link]() methods
• The split() method is used to break a string into parts
using a regular expression (regex) as the delimiter.
public class Main {
public static void main(String[] arg) {
String str = "how:to:split:a:string:in:java";
String[] arrOfStr = [Link](":");
for (String a : arrOfStr) {
[Link](a);
}
}
}
StringBuffer
• String represents fixed-length, immutable character sequences.
• StringBuffer represents growable and writeable character sequences.
• StringBuffer may have characters and substrings inserted in the middle or
appended to the end.
StringBuffer Constructors
• StringBuffer defines these four constructors:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
• The default constructor reserves room for 16 characters without
reallocation.
• The second version accepts an integer argument that explicitly sets the size
of the buffer.
• The third version accepts a String argument that sets the initial contents of
the StringBuffer object and reserves room for 16 more characters without
reallocation.
• The fourth constructor creates an object that contains the character
sequence contained in chars.
length( ) and capacity( )
• The current length of a StringBuffer can be found via the length( )
method,
• while the total allocated capacity can be found through the capacity(
) method.
• They have the following general forms:
int length( )
int capacity( )
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer = " + sb);
[Link]("length = " + [Link]());
[Link]("capacity = " + [Link]());
}
}
ensureCapacity( )
• If you want to preallocate room for a certain number of characters
after a StringBuffer has been constructed.
• you can use ensureCapacity( ) to set the size of the buffer.
• ensureCapacity( ) has this general form:
void ensureCapacity(int capacity)
• Here, capacity specifies the size of the buffer.
setLength( )
• To set the length of the buffer within a StringBuffer object, use
setLength( ).
• Its general form is shown here:
void setLength(int len)
Here, len specifies the length of the buffer.
charAt( ) and setCharAt( )
• The value of a single character can be obtained from a StringBuffer
via the charAt( ) method.
• You can set the value of a character within a StringBuffer using
setCharAt( ).
• Their general forms are shown here:
char charAt(int where)
void setCharAt(int where, char ch)
• For charAt( ), where specifies the index of the character being
obtained.
• For setCharAt( ),where specifies the index of the character being set,
and ch specifies the new value of that character.
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer = " + sb);
[Link]("length = " + [Link]());
[Link]("capacity = " + [Link]());
[Link](40);
[Link]("capacity = " + [Link]());
}
}
class setCharAtDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer before = " + sb);
[Link]("charAt(1) before = " + [Link](1));
[Link](1, 'i');
[Link](2);
[Link]("buffer after = " + sb);
[Link]("charAt(1) after = " + [Link](1));
getChars( )
• To copy a substring of a StringBuffer into an array, use the getChars( )
method.
• It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int
targetStart)
• Here, sourceStart specifies the index of the beginning of the
substring, and sourceEnd specifies an index that is one past the end
of the desired substring. The array that will receive the characters is
specified by target. The index within target at which the substring will
be copied is passed in targetStart.
class getCharsDemo
{
public static void main(String args[])
{
StringBuffer s =new StringBuffer("This is a demo of the getChars method.");
int start = 10;
int end = 14;
char buf[] = new char[4];
[Link](start, end, buf, 0);
[Link](buf);
}
}
append( )
• The append( ) method concatenates the string representation of any other
type of data to the end of the invoking StringBuffer object.
• It has several overloaded versions. Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
class appendDemo
{
public static void main(String args[])
{
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = [Link]("a = ").append(a).append("!").toString();
[Link](s);
}
}
insert( )
• The insert( ) method inserts one string into another.
• These are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
• Here, index specifies the index at which point the string will be
inserted into the invoking StringBuffer object.
class insertDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("I Java!");
[Link](2, "like ");
[Link](sb);
}
}
reverse( )
• You can reverse the characters within a StringBuffer object using
reverse( ), shown here:
StringBuffer reverse( )
• This method returns the reversed object on which it was called.
class ReverseDemo
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("abcdef");
[Link](s);
[Link]();
[Link](s);
}
}
delete( ) and deleteCharAt( )
• You can delete characters within a StringBuffer by using the methods
delete( ) and deleteCharAt( ).
• These methods are shown here:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
• The delete( ) method deletes a sequence of characters from the
invoking object. Here, startIndex specifies the index of the first
character to remove, and endIndex specifies an index one past the
last character to remove.
• The deleteCharAt( ) method deletes the character at the index
specified by loc.
• It returns the resulting StringBuffer object.
class deleteDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a test.");
[Link](4, 7);
[Link]("After delete: " + sb);
[Link](0);
[Link]("After deleteCharAt: " + sb);
}
}
replace( )
• You can replace one set of characters with another set inside a
StringBuffer object by calling replace( ).
• Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
• The substring being replaced is specified by the indexes startIndex
and endIndex. Thus, the substring at startIndex through endIndex1 is
replaced.
class replaceDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a test.");
[Link](5, 7, "was");
[Link]("After replace: " + sb);
}
}
substring( )
• You can obtain a portion of a StringBuffer by calling substring( ).
• It has the following two forms:
String substring(int startIndex)
String substring(int startIndex, int endIndex)
• The first form returns the substring that starts at startIndex and runs
to the end of the invoking StringBuffer object.
• The second form returns the substring that starts at startIndex and
runs through endIndex.
class TestSubstring
{
public static void main(String args[])
{
StringBuffer s=new StringBuffer("SachinTendulkar");
[Link]("Original String: "+ s);
[Link]("Substring starting from index 6: "+[Link](6));
[Link]("Substring starting from index 0 to 6:"+[Link](0,6));
}
}
Output:
Original String: Sachin Tendulkar
Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6:Sachin
Additional StringBuffer Methods
class IndexOfDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("one two one");
int i;
i = [Link]("one");
[Link]("First index: " + i);
i = [Link]("one");
[Link]("Last index: " + i);
}
}
StringBuilder
• J2SE 5 adds a new string class to Java’s already powerful string
handling capabilities.
• This new class is called StringBuilder.
• It is identical to StringBuffer except for one important difference: it is
not synchronized, which means that it is not thread-safe.
• The advantage of StringBuilder is faster performance.