Java

Java StringBuilder

A string object, instantiated from the Java String class, is an object that encapsulates a string literal. The problem with the string object in Java is that the literal characters cannot be modified. The StringBuffer class comes to the rescue. The literal for the StringBuffer is mutable. The StringBuffer also has the advantage of being thread-safe (safe for use by multiple threads). However, operations with the StringBuffer can be relatively long. So, there is a simpler form of the StringBuffer class, which is the StringBuilder class. StringBuilder is not thread-safe. The class is in the java.lang.* package, and does not need importation. This article explains the basics of the StringBuilder.

StringBuilder Construction

This class has four overloaded constructors. Three are explained here.

public StringBuilder()

This constructor creates an empty StringBuilder object, as shown in the following statement:

StringBuilder st = new StringBuilder();

Characters can then be appended to the StringBuilder object, st.

public StringBuilder(CharSequence seq)

This constructor takes a string literal as an argument, as shown by following code segment:

StringBuilder st = new StringBuilder("This is the dancer.");

System.out.println(st);

The output is:

This is the dancer.

public StringBuilder(String str)

This constructor method, takes a string identifier as an argument, as shown in the following code segment:

StringBuilder st = new StringBuilder("This is the dancer.");

StringBuilder st1 = new StringBuilder(st);

System.out.println(st1);

The output is:

This is the dancer.

StringBuilder Methods

public StringBuilder append(char c)

This appends a character to the StringBuilder object, which might be empty. The following code segment illustrates this:

StringBuilder st = new StringBuilder();

st.append('T'); st.append('h'); st.append('i'); st.append('s'); st.append(' ');

st.append('i'); st.append('s');

System.out.println(st);

The output is:

This is

public StringBuilder append(CharSequence s)

This appends a string sequence (string literal). The following code segment illustrates this:

StringBuilder st = new StringBuilder("This is");

st.append(" the ");

System.out.println(st);

The output is:

“This is the ”

public StringBuilder append(String str)

This uses a string identifier for appending. The following code segment illustrates this:

String strr = "dancer";

StringBuilder st = new StringBuilder("This is the ");

st.append(strr);

System.out.println(st);

The output is:

This is the dancer

public int length()

This method returns the number of characters in the string, as shown in the following code segment:

StringBuilder st = new StringBuilder("This is the dancer.");

int sz = st.length();

System.out.println(sz);

The output is:

19

The length is 19, meaning there are 19 characters.

public char charAt(int index)

This method returns a copy of the char at the index. Index counting begins from 0. The for-loop in the following code segment, returns all the characters of the StringBuilder object:

StringBuilder sb = new StringBuilder("This is the dancer.");

for (int i=0; i<sb.length(); i++) {

char ch = sb.charAt(i);

System.out.print(ch);

}

System.out.println();

The output is:

This is the dancer.

public void setCharAt(int index, char ch)

The character at an index position can be changed. Index counting begins from 0. The following code segment uses this method to change, ‘i’ in “This” to ‘u’, making “Thus”:

StringBuilder sb = new StringBuilder("This is the dancer.");

sb.setCharAt(2, 'u');

System.out.println(sb);

The output is:

Thus is the dancer.

public void setLength(int newLength)

This method changes the length of the string. If the given length is smaller than that of the original string, there is truncation. The counting of newLength begins from 1. The following code segment truncates the string to a length of 7:

StringBuilder sb = new StringBuilder("This is the dancer.");

sb.setLength(7);

System.out.println(sb);

The output is:

This is

public int indexOf(String subStr)

Index counting begins from 0. This returns the start index of the first occurrence of the substring given as argument. The following code is an illustration:

StringBuilder sb = new StringBuilder("This is the dancer.");

String sst = "is";

int ret = sb.indexOf(sst);

System.out.println(ret);

The output is 2, for the “is” in “This”.

public int indexOf(String str, int fromIndex)

Index counting begins from 0. This returns the first occurrence of the substring given as first argument, beginning at the value of the second argument. The following code illustrates this:

StringBuilder sb = new StringBuilder("This is the dancer.");

String sst = "is";

int ret = sb.indexOf(sst);

System.out.println(ret);

The output is 12.

public StringBuilder deleteCharAt(int index)

This deletes a particular character. In the following code segment, characters at index 8, index 9, index 10, and index 11 are deleted. Both the old and new strings are changed simultaneously each time.

StringBuilder sb = new StringBuilder("This is the dancer.");

sb.deleteCharAt(8); sb.deleteCharAt(8); sb.deleteCharAt(8);

StringBuilder ret = sb.deleteCharAt(8);

System.out.println(sb); System.out.println(ret);

The output is:

This is dancer.

This is dancer.

public StringBuilder delete(int start, int end)

In the previous code, when the character at index 8 was deleted, the next one became the character at index 8. Instead of deleting one by one, the characters from index 8 to index 11 can be deleted in one command, as the following code shows:

StringBuilder sb = new StringBuilder("This is the dancer.");

StringBuilder ret = sb.delete(8, 12);

System.out.println(sb); System.out.println(ret);

The output is:

This is dancer.

This is dancer.

Note that the method’s end index (12) is not included in the effective range.

public StringBuilder replace(int start, int end, String str)

A sub-string in the original string, can be replaced by another string, str, which may be longer or shorter than the original string. The following code segment illustrates this:

StringBuilder sb = new StringBuilder("This is the dancer.");

StringBuilder ret = sb.replace(0, 7, "Here:");

System.out.println(sb); System.out.println(ret);

The output is:

Here: the dancer.

Here: the dancer.

Again, the end index is one higher than the actual end of the range.

public StringBuilder insert(int offset, char c)

This inserts a character into the string, increasing the length by one. Offset is the index where the character will be inserted. The counting of offset begins from 1 and not 0. On the right of what is inserted, the characters in the string are shifted one place to the right. In the following code, ‘s’ is inserted between ‘r’ and ‘.’ :

StringBuilder sb = new StringBuilder("This is the dancer.");

StringBuilder ret = sb.insert(18, 's');

System.out.println(sb);

System.out.println(ret);

The output is:

This is the dancers.

This is the dancers.

The method returns a new string. Both the old and new strings are modified. The output sentence is not good English, and it will be addressed below:

public StringBuilder insert(int offset, char[] str)

Remember that offset counting in Java, begins from one, not zero. With that, a sub-string can be inserted into the original string, as in the following code:

StringBuilder sb = new StringBuilder("This is the dancer.");

StringBuilder ret = sb.insert(12, "big ");

System.out.println(sb); System.out.println(ret);

The output is:

This is the big dancer.

This is the big dancer.

Both the original and the return strings had the change.

public StringBuilder insert(int index, char[] str, int offset, int len)

A sub-string from another string can be inserted into the original string, as illustrated in the following code sample:

StringBuilder sb = new StringBuilder("This is the dancer.");

StringBuilder anotherStr = new StringBuilder("The big boss.");

StringBuilder ret = sb.insert(12, anotherStr, 4, 8);

System.out.println(sb); System.out.println(ret);

The output is:

This is the big dancer.

This is the big dancer.

The substring portion taken from the other string is: len – offset, e.g. 8 – 4 to get “big”.

Conclusion

The string literal cannot be edited with the String class in Java. The StringBuilder class is a string class whose literal can be edited. The class is in the java.lang.* package and does not need importation. This class has constructors and methods. The more commonly used ones have been explained in the previous sections. We hope you found this article helpful. Check out other Linux Hint articles for more tips and tutorials.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.