Monday, January 13, 2020

String, StringBuffer and StringBuilder

String, StringBuffer, and StringBuilder

String


The String is the immutable class it means that once you have created an object of String class then it cannot be changed. Java creates a constant string pool to store the string objects. All immutable objects in Java are thread-safe it means that String is also a thread-safe class. Thread safety means that the objects of the String class cannot be used by two threads simultaneously. String class objects once assigned a value cannot be changed. unlike C, in Java, a string is not an array of characters.
String str="Welcome to Strings in Java";


StringBuffer and StringBuilder


The objects of the StringBuffer and the StringBuilder classes are mutable it means that the objects of StringBuffer and StringBuilder classes can be changed once the value is assigned to be objects. Heap data structure is used to store the objects created for StringBuffer and StringBuilder class. 

StringBuffer and StringBuilder are very much same type classes and has the same set of methods, but each method in StringBuffer is synchronized it means that StringBuffer is thread-safe. StringBuilder is not thread-safe. 
Due to thread safety, the StringBuffer class also has a disadvantage of lack of performance. StringBuilder class has better performance in comparison to StringBuffer class as it is not thread-safe, it means that more than one thread can access the object of StringBuilder class. Access and retrieval of StringBuilder class objects are much faster in comparison to StringBuffer and String class objects. StringBuffer is comparatively faster than String. The value of the StringBuffer object can be changed, it means that they can be assigned a new value and the capacity of the StringBuffer class object can be dynamically changed at run-time. We can create an object of StringBuffer and StringBuilder class from the String class also.

StringBuffer message1 = new StringBuffer("welcome to Java") ;
StringBuilder message2 = new StringBuilder("welcome to programming") ;

For example

// To find if the given input string is palindrome or not
public class StringBufferDemo {
            public static void main(String[] a)
            {
                  StringBuffer sb=new StringBuffer();
                  StringBuffer sb1=new StringBuffer(20);
                  StringBuffer sb2=new StringBuffer("Something");
                  //test palindrome
                  StringBuffer test=new StringBuffer("abcdcba");
                  if(test.toString().equals(test.reverse().toString()))
                              {
                        System.out.println("pailndrome");
                              }
                  else
                  {
                        System.out.println("Not palindrome");
                  }
            }
}


Video Tutorial