StringBuilder Class

I wrote a blog post about String and StringBuilder last week but I haven’t discussed more in detail about StringBuilder. So in this blog post, I will talk about more in detail on StringBuilder class in Java.

StringBuilder is a mutable sequence of characters. It means that when you modify the contents of the StringBuilder object, java does not instantiate intermediate String objects (except for any String literal you pass into the StringBuilder) unlike String.


new StringBuilder("Live").append("What").append("You").append("Love");

//LiveWhatYouLove

Since StringBuilder is mutable, it can perform these operations:

  1.  Append – appends the string representation of the parameter(boolean, int, char, double, object, etc) to the char sequence.

Append method is overloaded so it can receive different data types like int, long, double, boolean.


new StringBuilder("You are").append(true).append(2).append("me");

//You are true2me

2.  Insert – appends the string representation of  the parameter(boolean, int, char, double, object, etc) to the char sequence. It differs to append because in insert, you can specify the place where you insert whereas append you just adding or concatenating the string after the last character.


StringBuilder couple = new StringBuilder("JunaldBeverly");

couple.insert(6, " Love ");

//Junald Love Beverly

3. Delete – deletes the substring in the char sequence based on the starting index and ending index.


StringBuilder greeting = new StringBuilder("Happy New Year");

greeting.delete(5, 8);

//Happy Year

4. Reverse –  reverses the char sequence.


StringBuilder food = new StringBuilder("stressed");

food = food.reverse();

//desserts

There are lot of methods in StringBuilder like substring, replace, trimToSize. If you want to learn more about those methods you must check out the Java documentation.

If you liked this post, don’t forget to share! Thanks

 

Advertisements

One thought on “StringBuilder Class

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s