0% found this document useful (0 votes)
95 views27 pages

Java String: Java String Class Provides A Lot of Methods To Perform Operations On String Such As

The document discusses Java strings. It explains that a Java string is an object that represents a sequence of characters. Strings can be created using string literals or the String class. The String class is immutable and provides many methods to perform operations on strings like compare(), concat(), length(), etc. It also discusses the differences between mutable and immutable strings in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views27 pages

Java String: Java String Class Provides A Lot of Methods To Perform Operations On String Such As

The document discusses Java strings. It explains that a Java string is an object that represents a sequence of characters. Strings can be created using string literals or the String class. The String class is immutable and provides many methods to perform operations on strings like compare(), concat(), length(), etc. It also discusses the differences between mutable and immutable strings in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Java String

In java, string is basically an object that represents sequence of char values. An


array of characters works same as java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};  
2. String s=new String(ch);  

is same as:

1. String s="javatpoint";  

Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.

The java.lang.String class implements Serializable, Comparable and


CharSequence interfaces.

CharSequence Interface

The CharSequence interface is used to represent sequence of characters. It is


implemented by String, StringBuffer and StringBuilder classes. It means, we can
create string in java by using these 3 classes.
The java String is immutable i.e. it cannot be changed. Whenever we change any
string, a new instance is created. For mutable string, you can use StringBuffer and
StringBuilder classes.

What is String in java

Generally, string is a sequence of characters. But in java, string is an object that


represents a sequence of characters. The java.lang.String class is used to create
string object.

How to create String object?

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

1. String s="welcome";  

Each time you create a string literal, the JVM checks the string constant pool first.
If the string already exists in the pool, a reference to the pooled instance is
returned. If string doesn't exist in the pool, a new string instance is created and
placed in the pool. For example:
1. String s1="Welcome";  
2. String s2="Welcome";//will not create new instance  

In the above example only one object will be created. Firstly JVM will not find any
string object with the value "Welcome" in string constant pool, so it will create a
new object. After that it will find the string with the value "Welcome" in the pool,
it will not create new object but will return the reference to the same instance.

Note: String objects are stored in a special memory area known as string
constant pool.
Why java uses concept of string literal?

To make Java more memory efficient (because no new objects are created if it
exists already in string constant pool).

2) By new keyword

String s=new String("Welcome");//creates two objects and one reference variable  

In such case, JVM will create a new string object in normal(non pool) heap
memory and the literal "Welcome" will be placed in the string constant pool. The
variable s will refer to the object in heap(non pool).

Java String Example

public class StringExample{  
public static void main(String args[]){  
String s1="java";//creating string by java string literal  
char ch[]={'s','t','r','i','n','g','s'};  
String s2=new String(ch);//converting char array to string  
String s3=new String("example");//creating java string by new keyword  
System.out.println(s1);  
System.out.println(s2);  
System.out.println(s3);  
}}  

Output
java
strings
example

Java String class methods

The java.lang.String class provides many useful methods to perform operations on


sequence of char values.

No. Method Description


returns char value for the
1 char charAt(int index)
particular index
2 int length() returns string length
static String format(String format, Object...
3 returns formatted string
args)
static String format(Locale l, String format, returns formatted string with
4
Object... args) given locale
returns substring for given
5 String substring(int beginIndex)
begin index
returns substring for given
6 String substring(int beginIndex, int endIndex)
begin index and end index
returns true or false after
7 boolean contains(CharSequence s) matching the sequence of char
value
static String join(CharSequence delimiter,
8 returns a joined string
CharSequence... elements)
static String join(CharSequence delimiter,
9 returns a joined string
Iterable<? extends CharSequence> elements)
checks the equality of string
10 boolean equals(Object another)
with object
11 boolean isEmpty() checks if string is empty
12 String concat(String str) concatinates specified string
replaces all occurrences of
13 String replace(char old, char new)
specified char value
String replace(CharSequence old, replaces all occurrences of
14
CharSequence new) specified CharSequence
compares another string. It
15 static String equalsIgnoreCase(String another)
doesn't check case.
returns splitted string matching
16 String[] split(String regex)
regex
returns splitted string matching
17 String[] split(String regex, int limit)
regex and limit
18 String intern() returns interned string
returns specified char value
19 int indexOf(int ch)
index
returns specified char value
20 int indexOf(int ch, int fromIndex)
index starting with given index
returns specified substring
21 int indexOf(String substring)
index
22 int indexOf(String substring, int fromIndex) returns specified substring
index starting with given index
23 String toLowerCase() returns string in lowercase.
returns string in lowercase
24 String toLowerCase(Locale l)
using specified locale.
25 String toUpperCase() returns string in uppercase.
returns string in uppercase
26 String toUpperCase(Locale l)
using specified locale.
removes beginning and ending
27 String trim()
spaces of this string.
converts given type into string.
28 static String valueOf(int value)
It is overloaded.

Immutable String in Java

In java, string objects are immutable. Immutable simply means unmodifiable or


unchangeable.

Once string object is created its data or state can't be changed but a new string
object is created.

Let's try to understand the immutability concept by the example given below:

class Testimmutablestring{  
 public static void main(String args[]){  
   String s="Sachin";  
   s.concat(" Tendulkar");//concat() method appends the string at the end  
   System.out.println(s);//will print Sachin because strings are immutable obj
ects  
 }  
}  
Output:
Sachin

Now it can be understood by the diagram given below. Here Sachin is not changed
but a new object is created with sachintendulkar. That is why string is known as
immutable.
As you can see in the above figure that two objects are created but s reference
variable still refers to "Sachin" not to "Sachin Tendulkar".

But if we explicitely assign it to the reference variable, it will refer to "Sachin


Tendulkar" object.For example:

class Testimmutablestring1{  
 public static void main(String args[]){  
   String s="Sachin";  
   s=s.concat(" Tendulkar");  
   System.out.println(s);  
 }  
}  
Output:
Sachin Tendulkar

In such case, s points to the "Sachin Tendulkar". Please notice that still sachin
object is not modified.

Why string objects are immutable in java?

Because java uses the concept of string literal.Suppose there are 5 reference
variables,all referes to one object "sachin".If one reference variable changes the
value of the object, it will be affected to all the reference variables. That is why
string objects are immutable in java.

JAVA STRING METHODS

Java String charAt()

The java string charAt() method returns a char value at the given index number.
The index number starts from 0. It returns StringIndexOutOfBoundsException if
given index number is greater than this string or negative index number.

public class CharAtExample
{  
public static void main(String args[])
{  
String name="javatpoint";  
char ch=name.charAt(4);  
System.out.println(ch);  
}
}  

Output:
t

Java String compareTo()


The java string compareTo() method compares the given string with current
string lexicographically. It returns positive number, negative number or 0.

It compares strings on the basis of Unicode value of each character in the strings.

If first string is lexicographically greater than second string, it returns positive


number (difference of character value). If first string is less than second string
lexicographically, it returns negative number and if first string is lexicographically
equal to second string, it returns 0.

if s1 > s2, it returns positive number  

if s1 < s2, it returns negative number  

if s1 == s2, it returns 0  

public class CompareToExample
{  
public static void main(String args[])
{  
String s1="hello";  
String s2="hello";  
String s3="meklo";  
String s4="hemlo";  
String s5="flag";  
System.out.println(s1.compareTo(s2)); 
System.out.println(s1.compareTo(s3)); 
System.out.println(s1.compareTo(s4));
System.out.println(s1.compareTo(s5));  
}
}

Output:
0
-5
-1
2

Java String concat


The java string concat() method combines specified string at the end of this
string. It returns combined string. It is like appending another string.

public class ConcatExample
{  
public static void main(String args[])
{  
String s1="java string";  
s1.concat("is immutable");  
System.out.println(s1);  
s1=s1.concat(" is immutable so assign it explicitly");  
System.out.println(s1);  
}
}  
Output:
java string
java string is immutable so assign it explicitly

Java String contains

The java string contains() method searches the sequence of characters in this
string. It returns true if sequence of char values are found in this string otherwise
returns false.

class ContainsExample
{  
public static void main(String args[])
{  
String name="what do you know about me";  
System.out.println(name.contains("do you know"));  
System.out.println(name.contains("about"));  
System.out.println(name.contains("hello"));  
}
}  
Output
true
true
false

Java String endsWith


The java string endsWith() method checks if this string ends with given suffix. It
returns true if this string ends with given suffix else returns false.

public class EndsWithExample
{  
public static void main(String args[])
{  
String s1="java by javatpoint";  
System.out.println(s1.endsWith("t"));  
System.out.println(s1.endsWith("point"));  
}
}  

Output:

true
true

Java String equals

The java string equals() method compares the two given strings based on the
content of the string. If any character is not matched, it returns false. If all
characters are matched, it returns true.

public class EqualsExample
{  
public static void main(String args[])
{  
String s1="javatpoint";  
String s2="javatpoint";  
String s3="JAVATPOINT";  
String s4="python";  
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3)); 
System.out.println(s1.equals(s4)); 
}
}  

Output:
true
false
false

Java String equalsIgnoreCase()

The String equalsIgnoreCase() method compares the two given strings on the
basis of content of the string irrespective of case of the string. It is like equals()
method but doesn't check case. If any character is not matched, it returns false
otherwise it returns true.

public class EqualsIgnoreCaseExample
{  
public static void main(String args[])
{  
String s1="javatpoint";  
String s2="javatpoint";  
String s3="JAVATPOINT";  
String s4="python";  
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.equalsIgnoreCase(s3));  
System.out.println(s1.equalsIgnoreCase(s4));
}
}  
Output
true
true
false

Java String getBytes()

The java string getBytes() method returns the byte array of the string. In other
words, it returns sequence of bytes.

public class StringGetBytesExample
{  
public static void main(String args[])
{  
String s1="ABCDEFG";  
byte[] barr=s1.getBytes();  
for(int i=0;i<barr.length;i++)
{  
System.out.println(barr[i]);  
}  
}
}  

Output:
65
66
67
68
69
70
71

Java String length

The java string length() method length of the string. It returns count of total
number of characters. The length of java string is same as the unicode code units of
the string.

public class LengthExample
{  
public static void main(String args[])
{  
String s1="javatpoint";  
String s2="python";  
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}
}  
Output
string length is: 10
string length is: 6

Java String replace

The java string replace() method returns a string replacing all the old char or
CharSequence to new char or CharSequence.

public class ReplaceExample1\
{  
public static void main(String args[])
{  
String s1="javatpoint is a very good website";  
String replaceString=s1.replace('a','e');  
System.out.println(replaceString);  
}
}  
Output
jevetpoint is e very good website

Java String replaceAll

The java string replaceAll() method returns a string replacing all the sequence of
characters matching regex and replacement string.

public class ReplaceAllExample1
{  
public static void main(String args[])
{  
String s1="javatpoint is a very good website";  
String replaceString=s1.replaceAll("a","e");
System.out.println(replaceString);  
}
}  
Output
jevetpoint is e very good website

Java String substring

The java string substring() method returns a part of the string.

We pass begin index and end index number position in the java substring method
where start index is inclusive and end index is exclusive. In other words, start
index starts from 0 whereas end index starts from 1.

public class SubstringExample
{  
public static void main(String args[])
{  
String s1="javatpoint";  
System.out.println(s1.substring(2,4));  
System.out.println(s1.substring(2));  
}
}  
Output
va
vatpoint

Java String toLowerCase()

The java string toLowerCase() method returns the string in lowercase letter. In
other words, it converts all characters of the string into lower case letter.

The toLowerCase() method works same as toLowerCase(Locale.getDefault())


method. It internally uses the default locale.

public class StringLowerExample
{  
public static void main(String args[])
{  
String s1="JAVATPOINT HELLO stRIng";  
String s1lower=s1.toLowerCase();  
System.out.println(s1lower);  
}
}  

Output:
javatpoint hello string

Java String toUpperCase

The java string toUpperCase() method returns the string in uppercase letter. In
other words, it converts all characters of the string into upper case letter.

The toUpperCase() method works same as toUpperCase(Locale.getDefault())


method. It internally uses the default locale.
public class StringUpperExample
{  
public static void main(String args[])
{  
String s1="hello string";  
String s1upper=s1.toUpperCase();  
System.out.println(s1upper);  
}
}  

Output:
HELLO STRING

Java String trim

The java string trim() method eliminates leading and trailing spaces. The unicode
value of space character is '\u0020'. The trim() method in java string checks this
unicode value before and after the string, if it exists then removes the spaces and
returns the omitted string.

public class StringTrimExample
{  
public static void main(String args[])
{  
String s1="  hello string   ";  
System.out.println(s1+"javatpoint"); 
System.out.println(s1.trim()+"javatpoint");
}
}  
Output
hello string javatpoint
hello stringjavatpoint

Java String 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.
public class StringValueOfExample
{  
public static void main(String args[])
{  
int value=30;  
String s1=String.valueOf(value);  
System.out.println(s1+10);  
}
}  

Output:
3010

Java StringBuffer class


Java StringBuffer class is used to create mutable (modifiable) string. The
StringBuffer class in java is same as String class except it is mutable i.e. it can be
changed.

Important Constructors of StringBuffer class

Constructor Description
creates an empty string buffer with the initial capacity of
StringBuffer()
16.
StringBuffer(String str) creates a string buffer with the specified string.
StringBuffer(int creates an empty string buffer with the specified capacity
capacity) as length.

Important methods of StringBuffer class

Modifier and
Method Description
Type
is used to append the specified string with
public this string. The append() method is
synchronized append(String s) overloaded like append(char),
StringBuffer append(boolean), append(int),
append(float), append(double) etc.
public insert(int offset, String is used to insert the specified string with
synchronized s) this string at the specified position. The
insert() method is overloaded like
insert(int, char), insert(int, boolean),
StringBuffer
insert(int, int), insert(int, float), insert(int,
double) etc.
public replace(int startIndex,
is used to replace the string from specified
synchronized int endIndex, String
startIndex and endIndex.
StringBuffer str)
public
delete(int startIndex, is used to delete the string from specified
synchronized
int endIndex) startIndex and endIndex.
StringBuffer
public
synchronized reverse() is used to reverse the string.
StringBuffer
public int capacity() is used to return the current capacity.
ensureCapacity(int is used to ensure the capacity at least
public void
minimumCapacity) equal to the given minimum.
is used to return the character at the
public char charAt(int index)
specified position.
is used to return the length of the string
public int length()
i.e. total number of characters.
substring(int is used to return the substring from the
public String
beginIndex) specified beginIndex.
substring(int
is used to return the substring from the
public String beginIndex, int
specified beginIndex and endIndex.
endIndex)

What is mutable string

A string that can be modified or changed is known as mutable string. StringBuffer


and StringBuilder classes are used for creating mutable string.

1) StringBuffer append() method

The append() method concatenates the given argument with this string.

class StringBufferExample
{  
public static void main(String args[])
{  
StringBuffer sb=new StringBuffer("Hello ");  
sb.append("Java");//now original string is changed  
System.out.println(sb);//prints Hello Java  
}  
}  

2) StringBuffer insert() method

The insert() method inserts the given string with this string at the given position.

class StringBufferExample2
{  
public static void main(String args[])
{  
StringBuffer sb=new StringBuffer("Hello ");  
sb.insert(1,"Java");//now original string is changed  
System.out.println(sb);//prints HJavaello  
}  
}  

3) StringBuffer replace() method

The replace() method replaces the given string from the specified beginIndex and
endIndex.

class StringBufferExample3
{  
public static void main(String args[])
{  
StringBuffer sb=new StringBuffer("Hello");  
sb.replace(1,3,"Java");  
System.out.println(sb);//prints HJavalo  
}  
}  

4) StringBuffer delete() method


The delete() method of StringBuffer class deletes the string from the specified
beginIndex to endIndex.

class StringBufferExample4
{  
public static void main(String args[])
{  
StringBuffer sb=new StringBuffer("Hello");  
sb.delete(1,3);  
System.out.println(sb);//prints Hlo  
}  
}  

5) StringBuffer reverse() method

The reverse() method of StringBuilder class reverses the current string.

class StringBufferExample5
{  
public static void main(String args[])
{  
StringBuffer sb=new StringBuffer("Hello");  
sb.reverse();  
System.out.println(sb);//prints olleH  
}  
}  

6) StringBuffer capacity() method

The capacity() method of StringBuffer class returns the current capacity of the
buffer. The default capacity of the buffer is 16. If the number of character increases
from its current capacity, it increases the capacity by (oldcapacity*2)+2. For
example if your current capacity is 16, it will be (16*2)+2=34.

class StringBufferExample6
{  
public static void main(String args[])
{  
StringBuffer sb=new StringBuffer();  
System.out.println(sb.capacity());//default 16  
sb.append("Hello");  
System.out.println(sb.capacity());//now 16  
sb.append("java is my favourite language");  
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldca
pacity*2)+2  
}  
}  

7) StringBuffer ensureCapacity() method

The ensureCapacity() method of StringBuffer class ensures that the given capacity
is the minimum to the current capacity. If it is greater than the current capacity, it
increases the capacity by (oldcapacity*2)+2. For example if your current capacity
is 16, it will be (16*2)+2=34.

class StringBufferExample7
{  
public static void main(String args[])
{  
StringBuffer sb=new StringBuffer();  
System.out.println(sb.capacity());//default 16  
sb.append("Hello");  
System.out.println(sb.capacity());//now 16  
sb.append("java is my favourite language");  
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldca
pacity*2)+2  
sb.ensureCapacity(10);//now no change  
System.out.println(sb.capacity());//now 34  
sb.ensureCapacity(50);//now (34*2)+2  
System.out.println(sb.capacity());//now 70  
}  

Java StringBuilder class


Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class except that it is non-
synchronized. It is available since JDK 1.5.

Important Constructors of StringBuilder class


Constructor Description
creates an empty string Builder with the initial capacity of
StringBuilder()
16.
StringBuilder(String str) creates a string Builder with the specified string.
StringBuilder(int creates an empty string Builder with the specified
length) capacity as length.

Important methods of StringBuilder class

Method Description
is used to append the specified string with this string.
public StringBuilder The append() method is overloaded like
append(String s) append(char), append(boolean), append(int),
append(float), append(double) etc.
is used to insert the specified string with this string at
the specified position. The insert() method is
public StringBuilder
overloaded like insert(int, char), insert(int, boolean),
insert(int offset, String s)
insert(int, int), insert(int, float), insert(int, double)
etc.
public StringBuilder
is used to replace the string from specified startIndex
replace(int startIndex, int
and endIndex.
endIndex, String str)
public StringBuilder
is used to delete the string from specified startIndex
delete(int startIndex, int
and endIndex.
endIndex)
public StringBuilder
is used to reverse the string.
reverse()
public int capacity() is used to return the current capacity.
public void
is used to ensure the capacity at least equal to the
ensureCapacity(int
given minimum.
minimumCapacity)
is used to return the character at the specified
public char charAt(int index)
position.
is used to return the length of the string i.e. total
public int length()
number of characters.
public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int is used to return the substring from the specified
beginIndex, int endIndex) beginIndex and endIndex.

Java StringBuilder Examples

Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method

The StringBuilder append() method concatenates the given argument with this
string.

class StringBuilderExample
{  
public static void main(String args[])
{  
StringBuilder sb=new StringBuilder("Hello ");  
sb.append("Java");//now original string is changed  
System.out.println(sb);//prints Hello Java  
}  
}  

2) StringBuilder insert() method

The StringBuilder insert() method inserts the given string with this string at the
given position.

class StringBuilderExample2
{  
public static void main(String args[])
{  
StringBuilder sb=new StringBuilder("Hello ");  
sb.insert(1,"Java");//now original string is changed  
System.out.println(sb);//prints HJavaello  
}  
}  

3) StringBuilder replace() method

The StringBuilder replace() method replaces the given string from the specified
beginIndex and endIndex.
class StringBuilderExample3
{  
public static void main(String args[])
{  
StringBuilder sb=new StringBuilder("Hello");  
sb.replace(1,3,"Java");  
System.out.println(sb);//prints HJavalo  
}  
}  

4) StringBuilder delete() method

The delete() method of StringBuilder class deletes the string from the specified
beginIndex to endIndex.

class StringBuilderExample4
{  
public static void main(String args[])
{  
StringBuilder sb=new StringBuilder("Hello");  
sb.delete(1,3);  
System.out.println(sb);//prints Hlo  
}  
}  

5) StringBuilder reverse() method

The reverse() method of StringBuilder class reverses the current string.

class StringBuilderExample5
{  
public static void main(String args[])
{  
StringBuilder sb=new StringBuilder("Hello");  
sb.reverse();  
System.out.println(sb);//prints olleH  
}  
}  

6) StringBuilder capacity() method


The capacity() method of StringBuilder class returns the current capacity of the
Builder. The default capacity of the Builder is 16. If the number of character
increases from its current capacity, it increases the capacity by (oldcapacity*2)+2.
For example if your current capacity is 16, it will be (16*2)+2=34.

class StringBuilderExample6
{  
public static void main(String args[])
{  
StringBuilder sb=new StringBuilder();  
System.out.println(sb.capacity());//default 16  
sb.append("Hello");  
System.out.println(sb.capacity());//now 16  
sb.append("java is my favourite language");  
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldca
pacity*2)+2  
}  
}  

7) StringBuilder ensureCapacity() method

The ensureCapacity() method of StringBuilder class ensures that the given capacity
is the minimum to the current capacity. If it is greater than the current capacity, it
increases the capacity by (oldcapacity*2)+2. For example if your current capacity
is 16, it will be (16*2)+2=34.

class StringBuilderExample7
{  
public static void main(String args[])
{  
StringBuilder sb=new StringBuilder();  
System.out.println(sb.capacity());//default 16  
sb.append("Hello");  
System.out.println(sb.capacity());//now 16  
sb.append("java is my favourite language");  
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldca
pacity*2)+2  
sb.ensureCapacity(10);//now no change  
System.out.println(sb.capacity());//now 34  
sb.ensureCapacity(50);//now (34*2)+2  
System.out.println(sb.capacity());//now 70  
}  

What is Difference between String and StringBuffer in Java?

There are several differences between String and StringBuffer in Java. They are as
follows:
1. String class is immutable, but StringBuffer class is mutable.
2. String objects can be created using string literal and new operator, but
StringBuffer objects can be created only using new operator.
3. String class uses string constant pool to store string objects, but StringBuffer
class does not use string constant pool.
4. Strings are of fixed length, whereas StringBuffers are of variable length.
5. String is slower than StringBuffer.
6. String consumes more memory when we will concat too many strings, but
StringBuffer consumes less memory when we concat or update strings.
7. Java String class overrides the equal() method of the Object class. So, we can
compare contents of two strings by using equals() method. The StringBuffer class
does not override the equals() method of Object class.
8. String should be used when we do not need to change or modify the content of
string. Whereas, StringBuffer should be used when we need to change or modify
the content of string frequently.
9. String cannot be used in a threaded environment, but StringBuffer can be used in
a multithreaded environment.

What is Difference between StringBuffer and StringBuilder in Java?

There are mainly five differences between StringBuffer and StringBuilder in Java.
They are as follows:
1. Methods of StringBuffer is synchronized. That means, two threads cannot call
methods of StringBuffer simultaneously. Therefore, StringBuffer is thread-safe.
But, methods of StringBuilder is not synchronized. That means, two or more
threads can call methods of StringBuilder simultaneously. Therefore, StringBuilder
is not thread-safe.
2. It is faster than StringBuffer.
3. It is more efficient than StringBuffer.
4. StringBuilder was added in Java 5 version, whereas StringBuffer was added in
Java 1 version.
5. StringBuffer is used in a multithreaded environment, but StringBuilder is used in
the single threaded environment.

You might also like