String and String Builder Class in Java

String Class

In Java, Strings are made of up very many individual characters of the data type ‘char’. Therefore, strings can be defined as a combination or permutation of a sequence of characters. This can be demonstrated by the following example:

A character array contains a series of characters. This also happens to be the definition of strings. Therefore, you can assign such an array to a String object.

char[] ch = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’};
String str = new String(ch);
System.out.println (str);

Output: abcdefgh

The same example can be defined in one line by making a variable of String type:
String str = “abcdefg”

The String Class belongs to the java.lang.String package. There are two ways to make a string object.

String Literal

A String literal is enclosed by “ “. For example, String str = “hello” is a string literal. String literals are memory efficient. If a literal is already present in the String constant pool, rather than creating a new instance, a new reference is created that points to the same string.

Using New Keyboard

String str = new String (“Hello”); Here a new string object is created in the heap memory and the literal is added to the string constant pool.


String Builder Class

The difference between String and the StringBuilder class is that in the latter, you can create strings that are mutable (modifiable).


  • StringBuilder(): A new string builder is created with a default size of 16.
  • StringBuilder (String str): A new string builder is created with the mentioned string str.
  • StringBuilder (int length): Used to define the length of the string builder.

The Stringbuilder class has several methods namely append(String str), insert(int offset, String str), replace(int startIndex, int endIndex, String str), delete(int startIndex, int endIndex), reverse(), capacity(), charAt(int index), and several others.


  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.