What is the difference between String and StringBuffer in Java?

In this shot, we will discuss the difference between the String and StringBuffer classes in Java.

The table below lists some of the differences in properties between String and StringBuffer.

Parameter


String 

StringBuffer

Storage


String pool

Heap memory

Mutability


Immutable

Mutable

Performance



Slower than StringBuffer while performing concatenation

Faster than String  while performing concatenation

Length

Fixed

Can be increased

Usage in threaded environment


Not used in a threaded environment

Used in a multi-threaded environment

Synchronization

Not synchronized


Synchronized

Syntax

String variable=”String”;


String variable= new String(“String”);

StringBuffer variable= new StringBuffer(“String”);

Code

In the code below, we create objects of both the String and StringBuffer classes.

We perform concatenation on String instances with the += operator and concatenation on StringBuffer instances with the append() method.

class Main
{
public static void main(String[] args)
{
String s = new String("This ");
s += "is a ";
s += "String object";
System.out.println(s);
StringBuffer sb = new StringBuffer("This ");
sb.append("is a ");
sb.append("StringBuffer object");
System.out.println(sb);
}
}

Explanation

  • In line 1, we create the Main class.

  • In line 6, we initialize an instance of the String class and concatenate it with the other strings in lines 77 and 88. Each time the code performs the += operation, a new String is created in the String pool.

  • In line 9, we display the concatenated String.

  • In line 11, we initialize an instance of the StringBuffer class. The StringBuffer object is altered twice, in lines 1212 and 1313. Each time the code uses the append() operation, no new object is created.

  • In line 14, we display the concatenated StringBuffer object.

In this way, we analyzed the difference between String and StringBuffer in Java. The StringBuffer class can be used to boost performance when you concatenate many strings together in a loop.

Free Resources