StringBuilder class in Java

StringBuilder class is a mutable class, unlike the String class which is immutable. StringBuilder class is same like StringBuffer class excerpts String Builder is non-synchronized class.

StringBuilder class is mostly used when we want to concatenate many strings continuously and/or treat them like variable-length arrays.

String appends become increasingly expensive as strings become longer. More and more memory is required and the program becomes too slow down. The solution of this problem is StringBuilder class in Java It just reuses a single buffer. It speeds up appends, inserts.

 

Constructors in StringBuffer class

StringBuffer class define 3 constructors.

  1. StringBuilder ()
  2. StringBuilder (int size)
  3. StringBuilder (String str)

 

Example to express difference between String and StringBuilder

In the below example we are modifying String object str and StringBuilder object sb and we can see str is not modified.

Output:

Easy

EasyBix

 

Selenium Automation Testing Video Tutorial:

 

Methods in the StringBuilder Class

There are many methods in the StringBuilder class. Let’s see important methods with example-

1. append() method – This method will concatenate the given argument with this string.  append() method has several overloaded forms.

2. insert() method – The insert(int , String) method inserts the given string with this string at the given position.

3. reverse() method – The reverse() method reverses the characters of the String.

4. replace() method – The replace(start index, end index, String) method replaces the string from specified start index to the end index.

5. delete() method – The delete (start index, end index) method is used to delete the string from specified startIndex and endIndex.

6. charAt() method – The charAt (index) method is used to return the character at the specified position.

7. length() method – The length() method is used to return the length of the string

8. substring() method – The substring (beginIndex) method is used to return the substring from the specified beginIndex and method substring (beginIndex, endindex)is used to return the substring from the specified beginIndex and endIndex.

0 Comment

Leave a Reply