StringBuffer And StringBuilder Differ From String Class

In this article, I have tried to figure out how these two classes differ from String class.

Immutability :

This is the main reason why StringBuffer and StringBuilder are introduced. As objects of String class are immutable, objects of StringBuffer and StringBuilder class are mutable. You can change the contents of StringBuffer and StringBuilder objects at any time of execution. When you change the content, new objects are not created. Instead of that, the changes are applied to the existing object. Thus solving memory issues may be caused by String class.

Object Creation :

You have to use ‘new‘ operator to create objects to StringBuffer and StringBuilder classes. You can’t use string literals to create objects to these classes. For example, you can’t write StringBuffer sb = “JAVA” or StringBuilder sb = “JAVA”. It gives compile time error. But, you can use both string literals and new operator to create objects to String class.

Storage Area :

As objects of StringBuffer and StringBuilder are created using only the new operator, they are stored in heap memory. Whereas objects of String class are created using both string literals and new operator, they are stored in string constant pool as well as heap memory.

Thread Safety :

Any immutable object in java is thread safety. Because they are unchangeable once they are created. Any type of thread can’t change the content of the immutable object. This applies to objects of String class also. Of the StringBuffer and StringBuilder objects, only StringBuffer objects are thread safety. All necessary methods in StringBuffer class are synchronized so that only one thread can enter into its object at any point of time. Where as StringBuilder objects are not threaded safety.

equals() and hashCode() Methods :

In StringBuffer and StringBuilder classes, equals() and hashCode methods are not overridden. Whereas in String class they are overridden.

toString() Method :

toString() method is overridden in all three classes. You can also convert StringBuffer and StringBuilder objects to String type by calling the toString() method on them.

Comments

Popular posts from this blog

How to convert Stream to Set using java

Java Concurrency Method basic example

How to Learn Java Effectively