Java String, StringBuffer and StringBuilder

    String, StringBuffer and StringBuilder

    Difference between String and StringBuffer

    String

    StringBuffer

    String is immutable

    String is mutable

    String consumes more memory as a new instance is created every time.

    The string is fast and takes slow memory space while concatenating strings.

    It overrides the equal() method

    It does not override the equal() method

    Difference between StringBuffer and StringBuilder

    StringBuffer

    StringBuilder

    It is synchronized means it can handle threads safely. Two methods will not call the same method at the same time.

    It is not synchronized means it cannot handle threads safely. Two methods may call the same method at the same time.

    It is less efficient than StringBuilder

    It is more efficient than StringBuffer

    How to create immutable class

    You can create an immutable string using wrapper class or the string class. An immutable class can be created if we define the class and its data members as final.

    Example-

    class Simple{  
       final String str;
       
       public Simple(String str){  
          this.str=str;
        }  
    
       public String getdata(){  
         return str;  
        } 
    
       public static void main(String args[]){
      
       Simple s=new Simple("hello");
       s.getdata();
      }
    }  

    The above class is immutable because:

    • The instance variable of the class is the final means the value cannot be changed after creating an object.
    • The class is the final means we cannot create the subclass.
    • There are no setter methods means. we cannot change the value of the instance variable.