Difference Between String and StringBuffer in Java

String in Java

A string is an object representing a number of character values for Java. The Java string object is made up of a separate character value for each letter in the string. The char class represents the characters in Java. An array of char values can be written by users, which means the same thing as a string.

Example : String s="dataflair";

Stringbuffer in Java

A sequence of characters that are thread safe, mutable. The buffer is similar to a string, but it can be modified. Whenever there’s a particular sequence of characters, the length and content can be adjusted through some method calls. The use of string buffers by more than one thread is safe.

Example :

class StringBuffer
                         {  
                           public static void main(String args[])
                               {  
                                  StringBuffer sb=new StringBuffer("Hello ");  
                                  sb.append("Java");
                                  System.out.println(sb);                       
                               }  
                        }

Uses of String

  • The preservation of human text, such as words or sentences, is a key purpose of stringsreadable.
  • The information contained in the program is communicated to the user by means of strings.

Uses of Stringbuffer

  • Provides for system input and output through data streams, serialization and the file system.
  • Provides classes that are essential for the design of the Java programming language.
  • Provides class and interface to handle the text, dates, numbers or messages in a way which is not dependent on any of the natural languages.

Difference between String and StringBuffer in Java

SNO     String         Stringbuffer
  1     The String class is immutable.     The StringBuffer class is mutable.
  2     String is slow and consumes more memory when we concatenate too many strings because every time it creates a new instance.       StringBuffer is fast and consumes less memory when we concatenate the strings.
  3     String class overrides the equals() method of Object class. So you can compare the contents of two strings by the equals() method.     The StringBuffer class doesn’t override the equals() method of an Object class.
 4     String class is slower while performing concatenation operation.     The StringBuffer class is faster while performing concatenation operations.
  5     String class uses String constant pool.     StringBuffer uses Heap memory

Advantages of String

Text processing:

  • For the representation of text for programming languages, strings are used.
  • Depending on the type of text to be manipulated or processed, they may be employed for searching, replacing, parsing and formatting.

Data Representation:

  • The strings can be used to represent various types of data, e.g. numbers, dates and times. For example, you can use a string to represent a date in the format “YYYY-MM-DD”, or a time in the format “HH:MM:SS”.

Ease of Use:

  • It’s easy to use and manipulate the strings. There are several possibilities, for instance, to concatenate, slice and reverse them.
  • It has a straightforward and intuitive syntax that makes it easier for programmers of all skill levels to use.

Compatibility:

  • Strings are commonly used in programming languages, which makes them a common type of data.
  • As a result, strings will be available for easy transfer between various systems and platforms with the aim of making data communications and sharing more reliable and effective.

Disadvantages of String

Memory consumption:

  • The strings are capable of consuming a great deal of memory, in particular when they’re working with long strings or many strings.
  • In an environment with limited memory capacities, such as implanted systems and mobile devices, this may be a problem.

Immutability:

  • Strings are immutable in a lot of programming languages, which makes them impossible to change once they’re created.
  • This may be a disadvantage when working with large or complex strings that require frequent adjustments, as it can lead to inefficiencies and memory overhead.

Security vulnerabilities:

  • If the Strings are not treated properly, they may be exposed to security vulnerabilities like buffer overruns or injection attacks.
  • This is because the hackers can manipulate strings, which allows them to write malicious code.

Advantages of Stringbuffer

Mutable:

  • The stringBuffer objects are immutable, meaning that you can change the contents of an object when it is created.
  • On the other hand, string objects are immutable, which means that you cannot alter their contents once they’re created.

Efficiency:

  • Since StringBuffer objects are mutable, each time you change a string, they will be more effective than the creation of new strings.
  • This is particularly true when you must change a string multiple times as every modification of the String object produces new objects which are deleted from an older one.

Threadsafe:

  • The StringBuffer object is thread safe, meaning multiple threads are able to access and edit it at the same time so that they can be safely accessed and modified by more than one thread.
  • By contrast, String objects do not contain thread safe properties, and therefore, it will be necessary to employ synchronization when accessing a string object from more than one thread.

Disadvantages of Stringbuffer

  • The method in this class is publicly available and synchronized, so naturally they cannot be used at the same time on several threads.
  • That’s been a major disadvantage when using StringBuffer.
  • The StringBuffer class, on the other hand, provides thread safety.
  • The StringBuffer class is a peer class of strings that provides a great deal of string functionality.
  • The string is a fixed length, immutable sequence of characters while StringBuffer represents growable and writable character sequences.

Program on String and Stringbuffer

import java.util.*;
class TechVidvan
{  
public static void main(String args[])
{  
StringBuffer sb=new StringBuffer();  
System.out.println(sb.capacity()); 
sb.append("Hello");  
System.out.println(sb.capacity());
sb.append("java is my favourite language");  
System.out.println(sb.capacity()); 
}  
}

Output
16
16
34

String vs StringBuffer

Since String is immutable in Java, whenever we do String manipulation like concatenation, substring, etc., it generates a new String and discards the older String for garbage collection. These are heavy operations and generate a lot of garbage in the heap. So Java has provided StringBuffer and StringBuilder classes that should be used for String manipulation. StringBuffer and StringBuilder are mutable objects in Java. They provide append(), insert(), delete(), and substring() methods for String manipulation.

Conclusion

The StringBuffer class is faster than the String class and provides a number of additional methods for deleting the sequence elements, updating the sequence elements, etc. In the heap section of memory, an object called StringBuffer is allocated.