Understanding String and StringBuilder Class in Java

In this article, I will explain what is String Class and what is StringBuilder Class, and what are the major differences between them.

String

The string is the most widely used class in Java Language. One of the important features of String Class is it is immutable. This means once the String object is created, it can never be modified. The main advantage of this feature is it helps to reduced memory overhead and increase performance.

String uses a char array to store its value, and final keyword so that its values are never modified, once assigned. Here is a partial definition of the String class in java.

private final char val[];

There are a lot of methods that are defined in String array such as substring, trim, toLowerCase, etc. All these methods seem to modify the contents of the String object but actually, they create and return a new string object rather than modify the existing value.

StringBuilder

In contrast to the String class, the StringBuilder class is immutable. It is usually used when the strings are larger and we have to modify the content quite often. StringBuilder class inherits from its superclass AbstractStringBuilder. Here is a partial definition of the class.

abstract class AbstractStringBuilder implements Appendable, CharSequence {

char value[];

int count;

}

Some methods that we get with StringBuilder classes are appended, insert delete which can modify StringBuilder objects. Unlike String class, these methods won’t create a new object, rather will modify the existing object.